a7c50de4a471de122c501d8a5789aced9e76bf53
[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::Builder;
11 use bitcoin::blockdata::transaction::TxOut;
12 use bitcoin::hash_types::BlockHash;
13
14 use lightning::chain::transaction::OutPoint;
15 use lightning::ln::channelmanager::{self, ChannelDetails, ChannelCounterparty};
16 use lightning::ln::msgs;
17 use lightning::routing::gossip::{NetworkGraph, RoutingFees};
18 use lightning::routing::utxo::{UtxoFuture, UtxoLookup, UtxoLookupError, UtxoResult};
19 use lightning::routing::router::{find_route, PaymentParameters, RouteHint, RouteHintHop, RouteParameters};
20 use lightning::routing::scoring::FixedPenaltyScorer;
21 use lightning::util::config::UserConfig;
22 use lightning::util::ser::Readable;
23
24 use bitcoin::hashes::Hash;
25 use bitcoin::secp256k1::PublicKey;
26 use bitcoin::network::constants::Network;
27 use bitcoin::blockdata::constants::genesis_block;
28
29 use crate::utils::test_logger;
30
31 use std::convert::TryInto;
32 use hashbrown::HashSet;
33 use std::sync::Arc;
34 use std::sync::atomic::{AtomicUsize, Ordering};
35
36 #[inline]
37 pub fn slice_to_be16(v: &[u8]) -> u16 {
38         ((v[0] as u16) << 8*1) |
39         ((v[1] as u16) << 8*0)
40 }
41
42 #[inline]
43 pub fn slice_to_be32(v: &[u8]) -> u32 {
44         ((v[0] as u32) << 8*3) |
45         ((v[1] as u32) << 8*2) |
46         ((v[2] as u32) << 8*1) |
47         ((v[3] as u32) << 8*0)
48 }
49
50 #[inline]
51 pub fn slice_to_be64(v: &[u8]) -> u64 {
52         ((v[0] as u64) << 8*7) |
53         ((v[1] as u64) << 8*6) |
54         ((v[2] as u64) << 8*5) |
55         ((v[3] as u64) << 8*4) |
56         ((v[4] as u64) << 8*3) |
57         ((v[5] as u64) << 8*2) |
58         ((v[6] as u64) << 8*1) |
59         ((v[7] as u64) << 8*0)
60 }
61
62
63 struct InputData {
64         data: Vec<u8>,
65         read_pos: AtomicUsize,
66 }
67 impl InputData {
68         fn get_slice(&self, len: usize) -> Option<&[u8]> {
69                 let old_pos = self.read_pos.fetch_add(len, Ordering::AcqRel);
70                 if self.data.len() < old_pos + len {
71                         return None;
72                 }
73                 Some(&self.data[old_pos..old_pos + len])
74         }
75         fn get_slice_nonadvancing(&self, len: usize) -> Option<&[u8]> {
76                 let old_pos = self.read_pos.load(Ordering::Acquire);
77                 if self.data.len() < old_pos + len {
78                         return None;
79                 }
80                 Some(&self.data[old_pos..old_pos + len])
81         }
82 }
83
84 struct FuzzChainSource<'a, 'b, Out: test_logger::Output> {
85         input: Arc<InputData>,
86         net_graph: &'a NetworkGraph<&'b test_logger::TestLogger<Out>>,
87 }
88 impl<Out: test_logger::Output> UtxoLookup for FuzzChainSource<'_, '_, Out> {
89         fn get_utxo(&self, _genesis_hash: &BlockHash, _short_channel_id: u64) -> UtxoResult {
90                 let input_slice = self.input.get_slice(2);
91                 if input_slice.is_none() { return UtxoResult::Sync(Err(UtxoLookupError::UnknownTx)); }
92                 let input_slice = input_slice.unwrap();
93                 let txo_res = TxOut {
94                         value: if input_slice[0] % 2 == 0 { 1_000_000 } else { 1_000 },
95                         script_pubkey: Builder::new().push_int(input_slice[1] as i64).into_script().to_v0_p2wsh(),
96                 };
97                 match input_slice {
98                         &[0, _] => UtxoResult::Sync(Err(UtxoLookupError::UnknownChain)),
99                         &[1, _] => UtxoResult::Sync(Err(UtxoLookupError::UnknownTx)),
100                         &[2, _] => {
101                                 let future = UtxoFuture::new();
102                                 future.resolve_without_forwarding(self.net_graph, Ok(txo_res));
103                                 UtxoResult::Async(future.clone())
104                         },
105                         &[3, _] => {
106                                 let future = UtxoFuture::new();
107                                 future.resolve_without_forwarding(self.net_graph, Err(UtxoLookupError::UnknownTx));
108                                 UtxoResult::Async(future.clone())
109                         },
110                         &[4, _] => {
111                                 UtxoResult::Async(UtxoFuture::new()) // the future will never resolve
112                         },
113                         &[..] => UtxoResult::Sync(Ok(txo_res)),
114                 }
115         }
116 }
117
118 #[inline]
119 pub fn do_test<Out: test_logger::Output>(data: &[u8], out: Out) {
120         let input = Arc::new(InputData {
121                 data: data.to_vec(),
122                 read_pos: AtomicUsize::new(0),
123         });
124         macro_rules! get_slice_nonadvancing {
125                 ($len: expr) => {
126                         match input.get_slice_nonadvancing($len as usize) {
127                                 Some(slice) => slice,
128                                 None => return,
129                         }
130                 }
131         }
132         macro_rules! get_slice {
133                 ($len: expr) => {
134                         match input.get_slice($len as usize) {
135                                 Some(slice) => slice,
136                                 None => return,
137                         }
138                 }
139         }
140
141         macro_rules! decode_msg {
142                 ($MsgType: path, $len: expr) => {{
143                         let mut reader = ::std::io::Cursor::new(get_slice!($len));
144                         match <$MsgType>::read(&mut reader) {
145                                 Ok(msg) => {
146                                         assert_eq!(reader.position(), $len as u64);
147                                         msg
148                                 },
149                                 Err(e) => match e {
150                                         msgs::DecodeError::UnknownVersion => return,
151                                         msgs::DecodeError::UnknownRequiredFeature => return,
152                                         msgs::DecodeError::InvalidValue => return,
153                                         msgs::DecodeError::BadLengthDescriptor => return,
154                                         msgs::DecodeError::ShortRead => panic!("We picked the length..."),
155                                         msgs::DecodeError::Io(e) => panic!("{:?}", e),
156                                         msgs::DecodeError::UnsupportedCompression => return,
157                                 }
158                         }
159                 }}
160         }
161
162         macro_rules! decode_msg_with_len16 {
163                 ($MsgType: path, $excess: expr) => {
164                         {
165                                 let extra_len = slice_to_be16(get_slice_nonadvancing!(2));
166                                 decode_msg!($MsgType, 2 + (extra_len as usize) + $excess)
167                         }
168                 }
169         }
170
171         macro_rules! get_pubkey_from_node_id {
172                 ($node_id: expr ) => {
173                         match PublicKey::from_slice($node_id.as_slice()) {
174                                 Ok(pk) => pk,
175                                 Err(_) => return,
176                         }
177                 }
178         }
179
180         macro_rules! get_pubkey {
181                 () => {
182                         match PublicKey::from_slice(get_slice!(33)) {
183                                 Ok(key) => key,
184                                 Err(_) => return,
185                         }
186                 }
187         }
188
189         let logger = test_logger::TestLogger::new("".to_owned(), out);
190
191         let our_pubkey = get_pubkey!();
192         let net_graph = NetworkGraph::new(genesis_block(Network::Bitcoin).header.block_hash(), &logger);
193         let chain_source = FuzzChainSource {
194                 input: Arc::clone(&input),
195                 net_graph: &net_graph,
196         };
197
198         let mut node_pks = HashSet::new();
199         let mut scid = 42;
200
201         loop {
202                 match get_slice!(1)[0] {
203                         0 => {
204                                 let start_len = slice_to_be16(&get_slice_nonadvancing!(2)[0..2]) as usize;
205                                 let addr_len = slice_to_be16(&get_slice_nonadvancing!(start_len+2 + 74)[start_len+2 + 72..start_len+2 + 74]);
206                                 if addr_len > (37+1)*4 {
207                                         return;
208                                 }
209                                 let msg = decode_msg_with_len16!(msgs::UnsignedNodeAnnouncement, 288);
210                                 node_pks.insert(get_pubkey_from_node_id!(msg.node_id));
211                                 let _ = net_graph.update_node_from_unsigned_announcement(&msg);
212                         },
213                         1 => {
214                                 let msg = decode_msg_with_len16!(msgs::UnsignedChannelAnnouncement, 32+8+33*4);
215                                 node_pks.insert(get_pubkey_from_node_id!(msg.node_id_1));
216                                 node_pks.insert(get_pubkey_from_node_id!(msg.node_id_2));
217                                 let _ = net_graph.update_channel_from_unsigned_announcement::
218                                         <&FuzzChainSource<'_, '_, Out>>(&msg, &None);
219                         },
220                         2 => {
221                                 let msg = decode_msg_with_len16!(msgs::UnsignedChannelAnnouncement, 32+8+33*4);
222                                 node_pks.insert(get_pubkey_from_node_id!(msg.node_id_1));
223                                 node_pks.insert(get_pubkey_from_node_id!(msg.node_id_2));
224                                 let _ = net_graph.update_channel_from_unsigned_announcement(&msg, &Some(&chain_source));
225                         },
226                         3 => {
227                                 let _ = net_graph.update_channel_unsigned(&decode_msg!(msgs::UnsignedChannelUpdate, 72));
228                         },
229                         4 => {
230                                 let short_channel_id = slice_to_be64(get_slice!(8));
231                                 net_graph.channel_failed(short_channel_id, false);
232                         },
233                         _ if node_pks.is_empty() => {},
234                         _ => {
235                                 let mut first_hops_vec = Vec::new();
236                                 let first_hops = match get_slice!(1)[0] {
237                                         0 => None,
238                                         count => {
239                                                 for _ in 0..count {
240                                                         scid += 1;
241                                                         let rnid = node_pks.iter().skip(u16::from_be_bytes(get_slice!(2).try_into().unwrap()) as usize % node_pks.len()).next().unwrap();
242                                                         let capacity = u64::from_be_bytes(get_slice!(8).try_into().unwrap());
243                                                         first_hops_vec.push(ChannelDetails {
244                                                                 channel_id: [0; 32],
245                                                                 counterparty: ChannelCounterparty {
246                                                                         node_id: *rnid,
247                                                                         features: channelmanager::provided_init_features(&UserConfig::default()),
248                                                                         unspendable_punishment_reserve: 0,
249                                                                         forwarding_info: None,
250                                                                         outbound_htlc_minimum_msat: None,
251                                                                         outbound_htlc_maximum_msat: None,
252                                                                 },
253                                                                 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
254                                                                 channel_type: None,
255                                                                 short_channel_id: Some(scid),
256                                                                 inbound_scid_alias: None,
257                                                                 outbound_scid_alias: None,
258                                                                 channel_value_satoshis: capacity,
259                                                                 user_channel_id: 0, inbound_capacity_msat: 0,
260                                                                 unspendable_punishment_reserve: None,
261                                                                 confirmations_required: None,
262                                                                 confirmations: None,
263                                                                 force_close_spend_delay: None,
264                                                                 is_outbound: true, is_channel_ready: true,
265                                                                 is_usable: true, is_public: true,
266                                                                 balance_msat: 0,
267                                                                 outbound_capacity_msat: capacity.saturating_mul(1000),
268                                                                 next_outbound_htlc_limit_msat: capacity.saturating_mul(1000),
269                                                                 inbound_htlc_minimum_msat: None,
270                                                                 inbound_htlc_maximum_msat: None,
271                                                                 config: None,
272                                                         });
273                                                 }
274                                                 Some(&first_hops_vec[..])
275                                         },
276                                 };
277                                 let mut last_hops = Vec::new();
278                                 {
279                                         let count = get_slice!(1)[0];
280                                         for _ in 0..count {
281                                                 scid += 1;
282                                                 let rnid = node_pks.iter().skip(slice_to_be16(get_slice!(2))as usize % node_pks.len()).next().unwrap();
283                                                 last_hops.push(RouteHint(vec![RouteHintHop {
284                                                         src_node_id: *rnid,
285                                                         short_channel_id: scid,
286                                                         fees: RoutingFees {
287                                                                 base_msat: slice_to_be32(get_slice!(4)),
288                                                                 proportional_millionths: slice_to_be32(get_slice!(4)),
289                                                         },
290                                                         cltv_expiry_delta: slice_to_be16(get_slice!(2)),
291                                                         htlc_minimum_msat: Some(slice_to_be64(get_slice!(8))),
292                                                         htlc_maximum_msat: None,
293                                                 }]));
294                                         }
295                                 }
296                                 let scorer = FixedPenaltyScorer::with_penalty(0);
297                                 let random_seed_bytes: [u8; 32] = [get_slice!(1)[0]; 32];
298                                 for target in node_pks.iter() {
299                                         let final_value_msat = slice_to_be64(get_slice!(8));
300                                         let final_cltv_expiry_delta = slice_to_be32(get_slice!(4));
301                                         let route_params = RouteParameters {
302                                                 payment_params: PaymentParameters::from_node_id(*target, final_cltv_expiry_delta)
303                                                         .with_route_hints(last_hops.clone()),
304                                                 final_value_msat,
305                                                 final_cltv_expiry_delta,
306                                         };
307                                         let _ = find_route(&our_pubkey, &route_params, &net_graph,
308                                                 first_hops.map(|c| c.iter().collect::<Vec<_>>()).as_ref().map(|a| a.as_slice()),
309                                                 &logger, &scorer, &random_seed_bytes);
310                                 }
311                         },
312                 }
313         }
314 }
315
316 pub fn router_test<Out: test_logger::Output>(data: &[u8], out: Out) {
317         do_test(data, out);
318 }
319
320 #[no_mangle]
321 pub extern "C" fn router_run(data: *const u8, datalen: usize) {
322         do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull {});
323 }