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