Qualify the BOLT 12 parse error
[rust-lightning] / fuzz / src / bech32_parse.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 use crate::utils::test_logger;
11 use core::convert::TryFrom;
12 use lightning::offers::parse::{Bech32Encode, Bolt12ParseError};
13
14 #[inline]
15 pub fn do_test<Out: test_logger::Output>(data: &[u8], _out: Out) {
16         if let Ok(bech32_encoded) = std::str::from_utf8(data) {
17                 if let Ok(bytes) = Bytes::from_bech32_str(bech32_encoded) {
18                         let bech32_encoded = bytes.to_string();
19                         assert_eq!(bytes, Bytes::from_bech32_str(&bech32_encoded).unwrap());
20                 }
21         }
22 }
23
24 #[derive(Debug, PartialEq)]
25 struct Bytes(Vec<u8>);
26
27 impl Bech32Encode for Bytes {
28         const BECH32_HRP: &'static str = "lno";
29 }
30
31 impl AsRef<[u8]> for Bytes {
32         fn as_ref(&self) -> &[u8] {
33                 &self.0
34         }
35 }
36
37 impl TryFrom<Vec<u8>> for Bytes {
38         type Error = Bolt12ParseError;
39         fn try_from(data: Vec<u8>) -> Result<Self, Bolt12ParseError> {
40                 Ok(Bytes(data))
41         }
42 }
43
44 impl core::fmt::Display for Bytes {
45         fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
46                 self.fmt_bech32_str(f)
47         }
48 }
49
50 pub fn bech32_parse_test<Out: test_logger::Output>(data: &[u8], out: Out) {
51         do_test(data, out);
52 }
53
54 #[no_mangle]
55 pub extern "C" fn bech32_parse_run(data: *const u8, datalen: usize) {
56         do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull {});
57 }