Pure import of lightning-invoice crate
[rust-lightning] / lightning-invoice / fuzz / fuzz_targets / serde_data_part.rs
1 extern crate lightning_invoice;
2 extern crate bech32;
3
4 use lightning_invoice::RawDataPart;
5 use bech32::{FromBase32, ToBase32, u5};
6
7 fn do_test(data: &[u8]) {
8     let bech32 = data.iter().map(|x| u5::try_from_u8(x % 32).unwrap()).collect::<Vec<_>>();
9     let invoice = match RawDataPart::from_base32(&bech32) {
10         Ok(invoice) => invoice,
11         Err(_) => return,
12     };
13
14     // Our encoding is not worse than the input
15     assert!(invoice.to_base32().len() <= bech32.len());
16
17     // Our serialization is loss-less
18     assert_eq!(
19         RawDataPart::from_base32(&invoice.to_base32()).expect("faild parsing out own encoding"),
20         invoice
21     );
22 }
23
24 #[cfg(feature = "afl")]
25 #[macro_use] extern crate afl;
26 #[cfg(feature = "afl")]
27 fn main() {
28     fuzz!(|data| {
29         do_test(&data);
30     });
31 }
32
33 #[cfg(feature = "honggfuzz")]
34 #[macro_use] extern crate honggfuzz;
35 #[cfg(feature = "honggfuzz")]
36 fn main() {
37     loop {
38         fuzz!(|data| {
39             do_test(data);
40         });
41     }
42 }
43
44 #[cfg(test)]
45 mod tests {
46     fn extend_vec_from_hex(hex: &str, out: &mut Vec<u8>) {
47         let mut b = 0;
48         for (idx, c) in hex.as_bytes().iter().filter(|&&c| c != b'\n').enumerate() {
49             b <<= 4;
50             match *c {
51                 b'A'...b'F' => b |= c - b'A' + 10,
52                 b'a'...b'f' => b |= c - b'a' + 10,
53                 b'0'...b'9' => b |= c - b'0',
54                 _ => panic!("Bad hex"),
55             }
56             if (idx & 1) == 1 {
57                 out.push(b);
58                 b = 0;
59             }
60         }
61     }
62
63     #[test]
64     fn duplicate_crash() {
65         let mut a = Vec::new();
66         extend_vec_from_hex("000000", &mut a);
67         super::do_test(&a);
68     }
69 }