Drop individual fuzz target duplicate_crash tests for file reader
[rust-lightning] / fuzz / src / router.rs
1 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
2 use bitcoin::blockdata::script::{Script, Builder};
3 use bitcoin::blockdata::block::Block;
4 use bitcoin::blockdata::transaction::Transaction;
5
6 use lightning::chain::chaininterface::{ChainError,ChainWatchInterface};
7 use lightning::ln::channelmanager::ChannelDetails;
8 use lightning::ln::msgs;
9 use lightning::ln::msgs::{RoutingMessageHandler};
10 use lightning::ln::router::{Router, RouteHint};
11 use lightning::util::logger::Logger;
12 use lightning::util::ser::Readable;
13
14 use secp256k1::key::PublicKey;
15
16 use utils::test_logger;
17
18 use std::sync::Arc;
19 use std::sync::atomic::{AtomicUsize, Ordering};
20
21 #[inline]
22 pub fn slice_to_be16(v: &[u8]) -> u16 {
23         ((v[0] as u16) << 8*1) |
24         ((v[1] as u16) << 8*0)
25 }
26
27 #[inline]
28 pub fn slice_to_be32(v: &[u8]) -> u32 {
29         ((v[0] as u32) << 8*3) |
30         ((v[1] as u32) << 8*2) |
31         ((v[2] as u32) << 8*1) |
32         ((v[3] as u32) << 8*0)
33 }
34
35 #[inline]
36 pub fn slice_to_be64(v: &[u8]) -> u64 {
37         ((v[0] as u64) << 8*7) |
38         ((v[1] as u64) << 8*6) |
39         ((v[2] as u64) << 8*5) |
40         ((v[3] as u64) << 8*4) |
41         ((v[4] as u64) << 8*3) |
42         ((v[5] as u64) << 8*2) |
43         ((v[6] as u64) << 8*1) |
44         ((v[7] as u64) << 8*0)
45 }
46
47
48 struct InputData {
49         data: Vec<u8>,
50         read_pos: AtomicUsize,
51 }
52 impl InputData {
53         fn get_slice(&self, len: usize) -> Option<&[u8]> {
54                 let old_pos = self.read_pos.fetch_add(len, Ordering::AcqRel);
55                 if self.data.len() < old_pos + len {
56                         return None;
57                 }
58                 Some(&self.data[old_pos..old_pos + len])
59         }
60         fn get_slice_nonadvancing(&self, len: usize) -> Option<&[u8]> {
61                 let old_pos = self.read_pos.load(Ordering::Acquire);
62                 if self.data.len() < old_pos + len {
63                         return None;
64                 }
65                 Some(&self.data[old_pos..old_pos + len])
66         }
67 }
68
69 struct DummyChainWatcher {
70         input: Arc<InputData>,
71 }
72
73 impl ChainWatchInterface for DummyChainWatcher {
74         fn install_watch_tx(&self, _txid: &Sha256dHash, _script_pub_key: &Script) { }
75         fn install_watch_outpoint(&self, _outpoint: (Sha256dHash, u32), _out_script: &Script) { }
76         fn watch_all_txn(&self) { }
77         fn filter_block<'a>(&self, _block: &'a Block) -> (Vec<&'a Transaction>, Vec<u32>) {
78                 (Vec::new(), Vec::new())
79         }
80         fn reentered(&self) -> usize { 0 }
81
82         fn get_chain_utxo(&self, _genesis_hash: Sha256dHash, _unspent_tx_output_identifier: u64) -> Result<(Script, u64), ChainError> {
83                 match self.input.get_slice(2) {
84                         Some(&[0, _]) => Err(ChainError::NotSupported),
85                         Some(&[1, _]) => Err(ChainError::NotWatched),
86                         Some(&[2, _]) => Err(ChainError::UnknownTx),
87                         Some(&[_, x]) => Ok((Builder::new().push_int(x as i64).into_script().to_v0_p2wsh(), 0)),
88                         None => Err(ChainError::UnknownTx),
89                         _ => unreachable!(),
90                 }
91         }
92 }
93
94 #[inline]
95 pub fn do_test(data: &[u8]) {
96         let input = Arc::new(InputData {
97                 data: data.to_vec(),
98                 read_pos: AtomicUsize::new(0),
99         });
100         macro_rules! get_slice_nonadvancing {
101                 ($len: expr) => {
102                         match input.get_slice_nonadvancing($len as usize) {
103                                 Some(slice) => slice,
104                                 None => return,
105                         }
106                 }
107         }
108         macro_rules! get_slice {
109                 ($len: expr) => {
110                         match input.get_slice($len as usize) {
111                                 Some(slice) => slice,
112                                 None => return,
113                         }
114                 }
115         }
116
117         macro_rules! decode_msg {
118                 ($MsgType: path, $len: expr) => {{
119                         let mut reader = ::std::io::Cursor::new(get_slice!($len));
120                         match <($MsgType)>::read(&mut reader) {
121                                 Ok(msg) => msg,
122                                 Err(e) => match e {
123                                         msgs::DecodeError::UnknownVersion => return,
124                                         msgs::DecodeError::UnknownRequiredFeature => return,
125                                         msgs::DecodeError::InvalidValue => return,
126                                         msgs::DecodeError::ExtraAddressesPerType => return,
127                                         msgs::DecodeError::BadLengthDescriptor => return,
128                                         msgs::DecodeError::ShortRead => panic!("We picked the length..."),
129                                         msgs::DecodeError::Io(e) => panic!(format!("{}", e)),
130                                 }
131                         }
132                 }}
133         }
134
135         macro_rules! decode_msg_with_len16 {
136                 ($MsgType: path, $begin_len: expr, $excess: expr) => {
137                         {
138                                 let extra_len = slice_to_be16(&get_slice_nonadvancing!($begin_len as usize + 2)[$begin_len..$begin_len + 2]);
139                                 decode_msg!($MsgType, $begin_len as usize + 2 + (extra_len as usize) + $excess)
140                         }
141                 }
142         }
143
144         macro_rules! get_pubkey {
145                 () => {
146                         match PublicKey::from_slice(get_slice!(33)) {
147                                 Ok(key) => key,
148                                 Err(_) => return,
149                         }
150                 }
151         }
152
153         let logger: Arc<dyn Logger> = Arc::new(test_logger::TestLogger::new("".to_owned()));
154         let chain_monitor = Arc::new(DummyChainWatcher {
155                 input: Arc::clone(&input),
156         });
157
158         let our_pubkey = get_pubkey!();
159         let router = Router::new(our_pubkey.clone(), chain_monitor, Arc::clone(&logger));
160
161         loop {
162                 match get_slice!(1)[0] {
163                         0 => {
164                                 let start_len = slice_to_be16(&get_slice_nonadvancing!(64 + 2)[64..64 + 2]) as usize;
165                                 let addr_len = slice_to_be16(&get_slice_nonadvancing!(64+start_len+2 + 74)[64+start_len+2 + 72..64+start_len+2 + 74]);
166                                 if addr_len > (37+1)*4 {
167                                         return;
168                                 }
169                                 let _ = router.handle_node_announcement(&decode_msg_with_len16!(msgs::NodeAnnouncement, 64, 288));
170                         },
171                         1 => {
172                                 let _ = router.handle_channel_announcement(&decode_msg_with_len16!(msgs::ChannelAnnouncement, 64*4, 32+8+33*4));
173                         },
174                         2 => {
175                                 let _ = router.handle_channel_update(&decode_msg!(msgs::ChannelUpdate, 128));
176                         },
177                         3 => {
178                                 match get_slice!(1)[0] {
179                                         0 => {
180                                                 router.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelUpdateMessage {msg: decode_msg!(msgs::ChannelUpdate, 128)});
181                                         },
182                                         1 => {
183                                                 let short_channel_id = slice_to_be64(get_slice!(8));
184                                                 router.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed {short_channel_id, is_permanent: false});
185                                         },
186                                         _ => return,
187                                 }
188                         },
189                         4 => {
190                                 let target = get_pubkey!();
191                                 let mut first_hops_vec = Vec::new();
192                                 let first_hops = match get_slice!(1)[0] {
193                                         0 => None,
194                                         1 => {
195                                                 let count = slice_to_be16(get_slice!(2));
196                                                 for _ in 0..count {
197                                                         first_hops_vec.push(ChannelDetails {
198                                                                 channel_id: [0; 32],
199                                                                 short_channel_id: Some(slice_to_be64(get_slice!(8))),
200                                                                 remote_network_id: get_pubkey!(),
201                                                                 channel_value_satoshis: slice_to_be64(get_slice!(8)),
202                                                                 user_id: 0,
203                                                                 inbound_capacity_msat: 0,
204                                                                 is_live: true,
205                                                                 outbound_capacity_msat: 0,
206                                                         });
207                                                 }
208                                                 Some(&first_hops_vec[..])
209                                         },
210                                         _ => return,
211                                 };
212                                 let mut last_hops_vec = Vec::new();
213                                 let last_hops = {
214                                         let count = slice_to_be16(get_slice!(2));
215                                         for _ in 0..count {
216                                                 last_hops_vec.push(RouteHint {
217                                                         src_node_id: get_pubkey!(),
218                                                         short_channel_id: slice_to_be64(get_slice!(8)),
219                                                         fee_base_msat: slice_to_be32(get_slice!(4)),
220                                                         fee_proportional_millionths: slice_to_be32(get_slice!(4)),
221                                                         cltv_expiry_delta: slice_to_be16(get_slice!(2)),
222                                                         htlc_minimum_msat: slice_to_be64(get_slice!(8)),
223                                                 });
224                                         }
225                                         &last_hops_vec[..]
226                                 };
227                                 let _ = router.get_route(&target, first_hops, last_hops, slice_to_be64(get_slice!(8)), slice_to_be32(get_slice!(4)));
228                         },
229                         _ => return,
230                 }
231         }
232 }
233
234 #[no_mangle]
235 pub extern "C" fn router_run(data: *const u8, datalen: usize) {
236         do_test(unsafe { std::slice::from_raw_parts(data, datalen) });
237 }