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