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