Add subcrate which impls a simple SPV client from Bitcoin Core RPC
[rust-lightning] / lightning-block-sync / src / utils.rs
1 use bitcoin::util::uint::Uint256;
2
3 pub fn hex_to_uint256(hex: &str) -> Option<Uint256> {
4         if hex.len() != 64 { return None; }
5         let mut out = [0u64; 4];
6
7         let mut b: u64 = 0;
8         for (idx, c) in hex.as_bytes().iter().enumerate() {
9                 b <<= 4;
10                 match *c {
11                         b'A'..=b'F' => b |= (c - b'A' + 10) as u64,
12                         b'a'..=b'f' => b |= (c - b'a' + 10) as u64,
13                         b'0'..=b'9' => b |= (c - b'0') as u64,
14                         _ => return None,
15                 }
16                 if idx % 16 == 15 {
17                         out[3 - (idx / 16)] = b;
18                         b = 0;
19                 }
20         }
21         Some(Uint256::from(&out[..]))
22 }
23
24 #[cfg(feature = "rpc-client")]
25 pub fn hex_to_vec(hex: &str) -> Option<Vec<u8>> {
26         let mut out = Vec::with_capacity(hex.len() / 2);
27
28         let mut b = 0;
29         for (idx, c) in hex.as_bytes().iter().enumerate() {
30                 b <<= 4;
31                 match *c {
32                         b'A'..=b'F' => b |= c - b'A' + 10,
33                         b'a'..=b'f' => b |= c - b'a' + 10,
34                         b'0'..=b'9' => b |= c - b'0',
35                         _ => return None,
36                 }
37                 if (idx & 1) == 1 {
38                         out.push(b);
39                         b = 0;
40                 }
41         }
42
43         Some(out)
44 }