Initial commit.
[rapid-gossip-sync-server] / src / hex_utils.rs
1 use bitcoin::secp256k1::PublicKey;
2
3 pub fn to_vec(hex: &str) -> Option<Vec<u8>> {
4     let mut out = Vec::with_capacity(hex.len() / 2);
5
6     let mut b = 0;
7     for (idx, c) in hex.as_bytes().iter().enumerate() {
8         b <<= 4;
9         match *c {
10             b'A'..=b'F' => b |= c - b'A' + 10,
11             b'a'..=b'f' => b |= c - b'a' + 10,
12             b'0'..=b'9' => b |= c - b'0',
13             _ => return None,
14         }
15         if (idx & 1) == 1 {
16             out.push(b);
17             b = 0;
18         }
19     }
20
21     Some(out)
22 }
23
24 #[inline]
25 pub fn hex_str(value: &[u8]) -> String {
26     let mut res = String::with_capacity(64);
27     for v in value {
28         res += &format!("{:02x}", v);
29     }
30     res
31 }
32
33 pub fn to_compressed_pubkey(hex: &str) -> Option<PublicKey> {
34     let data = match to_vec(&hex[0..33 * 2]) {
35         Some(bytes) => bytes,
36         None => return None,
37     };
38     match PublicKey::from_slice(&data) {
39         Ok(pk) => Some(pk),
40         Err(_) => None,
41     }
42 }