verity_ic/crypto/
mod.rs

1//! This submodule contains cryptographic related operations.
2
3pub mod config;
4pub mod ecdsa;
5pub mod ethereum;
6
7/// Converts a hexadecimal string (optionally prefixed with '0x') to a vector of bytes.
8pub fn string_to_vec_u8(str: &str) -> Vec<u8> {
9    let starts_from: usize;
10    if str.starts_with("0x") {
11        starts_from = 2;
12    } else {
13        starts_from = 0;
14    }
15
16    (starts_from..str.len())
17        .step_by(2)
18        .map(|i| u8::from_str_radix(&str[i..i + 2], 16).unwrap())
19        .collect::<Vec<u8>>()
20}
21
22/// Converts a vector of bytes to a hexadecimal string.
23pub fn vec_u8_to_string(vec: &Vec<u8>) -> String {
24    vec.iter()
25        .map(|r| format!("{:02x}", r))
26        .collect::<Vec<String>>()
27        .join("")
28        .to_string()
29}
30
31/// Removes the leading elements from a vector that match the specified element.
32pub fn remove_leading(vec: &Vec<u8>, element: u8) -> Vec<u8> {
33    let start = vec.iter().position(|&x| x != element).unwrap();
34    let result = &vec[start..];
35    result.to_vec()
36}
37
38#[cfg(test)]
39mod tests {
40    use super::*;
41
42    #[test]
43    fn test_string_to_vec_u8() {
44        let hex_string = "0x5c8e3a7c16fa5cdde9f74751d6b2395176f05c55";
45        let hex_output = [
46            92, 142, 58, 124, 22, 250, 92, 221, 233, 247, 71, 81, 214, 178, 57, 81, 118, 240, 92,
47            85,
48        ]
49        .to_vec();
50
51        let output_vector = string_to_vec_u8(&hex_string);
52        assert_eq!(hex_output, output_vector);
53    }
54
55    #[test]
56    fn test_vec_u8_to_string() {
57        let hex_string = "5c8e3a7c16fa5cdde9f74751d6b2395176f05c55";
58        let hex_output = [
59            92, 142, 58, 124, 22, 250, 92, 221, 233, 247, 71, 81, 214, 178, 57, 81, 118, 240, 92,
60            85,
61        ]
62        .to_vec();
63
64        let output_hex_string = vec_u8_to_string(&hex_output);
65        assert_eq!(hex_string, output_hex_string);
66    }
67}