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