1 // This file is Copyright its original authors, visible in version control
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
10 use bitcoin::amount::Amount;
11 use bitcoin::blockdata::constants::ChainHash;
12 use bitcoin::blockdata::script::Builder;
13 use bitcoin::blockdata::transaction::TxOut;
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,
27 use lightning::routing::scoring::{
28 ProbabilisticScorer, ProbabilisticScoringDecayParameters, ProbabilisticScoringFeeParameters,
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;
35 use bitcoin::hashes::Hash;
36 use bitcoin::network::Network;
37 use bitcoin::secp256k1::PublicKey;
39 use crate::utils::test_logger;
41 use std::convert::TryInto;
42 use std::sync::atomic::{AtomicUsize, Ordering};
46 pub fn slice_to_be16(v: &[u8]) -> u16 {
47 ((v[0] as u16) << 8 * 1) | ((v[1] as u16) << 8 * 0)
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)
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)
72 read_pos: AtomicUsize,
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 {
80 Some(&self.data[old_pos..old_pos + len])
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 {
87 Some(&self.data[old_pos..old_pos + len])
91 struct FuzzChainSource<'a, 'b, Out: test_logger::Output> {
92 input: Arc<InputData>,
93 net_graph: &'a NetworkGraph<&'b test_logger::TestLogger<Out>>,
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));
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(),
107 &[0, _] => UtxoResult::Sync(Err(UtxoLookupError::UnknownChain)),
108 &[1, _] => UtxoResult::Sync(Err(UtxoLookupError::UnknownTx)),
110 let future = UtxoFuture::new();
111 future.resolve_without_forwarding(self.net_graph, Ok(txo_res));
112 UtxoResult::Async(future.clone())
115 let future = UtxoFuture::new();
116 future.resolve_without_forwarding(self.net_graph, Err(UtxoLookupError::UnknownTx));
117 UtxoResult::Async(future.clone())
120 UtxoResult::Async(UtxoFuture::new()) // the future will never resolve
122 &[..] => UtxoResult::Sync(Ok(txo_res)),
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 {
132 match input.get_slice_nonadvancing($len as usize) {
133 Some(slice) => slice,
138 macro_rules! get_slice {
140 match input.get_slice($len as usize) {
141 Some(slice) => slice,
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) {
152 assert_eq!(reader.position(), $len as u64);
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,
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)
176 macro_rules! get_pubkey_from_node_id {
177 ($node_id: expr ) => {
178 match PublicKey::from_slice($node_id.as_slice()) {
185 macro_rules! get_pubkey {
187 match PublicKey::from_slice(get_slice!(33)) {
194 let logger = test_logger::TestLogger::new("".to_owned(), out);
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 };
200 let mut node_pks = new_hash_map();
203 macro_rules! first_hops {
204 ($first_hops_vec: expr) => {
205 match get_slice!(1)[0] {
210 let skip = u16::from_be_bytes(get_slice!(2).try_into().unwrap()) as usize
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 {
218 features: channelmanager::provided_init_features(
219 &UserConfig::default(),
221 unspendable_punishment_reserve: 0,
222 forwarding_info: None,
223 outbound_htlc_minimum_msat: None,
224 outbound_htlc_maximum_msat: None,
226 funding_txo: Some(OutPoint {
227 txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(),
231 short_channel_id: Some(scid),
232 inbound_scid_alias: None,
233 outbound_scid_alias: None,
234 channel_value_satoshis: capacity,
236 inbound_capacity_msat: 0,
237 unspendable_punishment_reserve: None,
238 confirmations_required: None,
240 force_close_spend_delay: None,
242 is_channel_ready: true,
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,
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(),
258 Some(&$first_hops_vec[..])
264 macro_rules! last_hops {
265 ($last_hops: expr) => {
266 let count = get_slice!(1)[0];
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 {
273 short_channel_id: scid,
275 base_msat: slice_to_be32(get_slice!(4)),
276 proportional_millionths: slice_to_be32(get_slice!(4)),
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,
286 macro_rules! find_routes {
287 ($first_hops: expr, $node_pks: expr, $route_params: expr) => {
288 let scorer = ProbabilisticScorer::new(
289 ProbabilisticScoringDecayParameters::default(),
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);
303 .map(|c| c.iter().collect::<Vec<_>>())
305 .map(|a| a.as_slice()),
308 &ProbabilisticScoringFeeParameters::default(),
316 match get_slice!(1)[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],
323 if addr_len > (37 + 1) * 4 {
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);
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), ());
336 .update_channel_from_unsigned_announcement::<&FuzzChainSource<'_, '_, Out>>(
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), ());
346 net_graph.update_channel_from_unsigned_announcement(&msg, &Some(&chain_source));
350 .update_channel_unsigned(&decode_msg!(msgs::UnsignedChannelUpdate, 72));
353 let short_channel_id = slice_to_be64(get_slice!(8));
354 net_graph.channel_failed_permanent(short_channel_id);
356 _ if node_pks.is_empty() => {},
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);
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())
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
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(),
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(),
406 introduction_node: IntroductionNode::NodeId(hop.src_node_id),
407 blinding_point: dummy_pk,
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())
428 pub fn router_test<Out: test_logger::Output>(data: &[u8], out: Out) {
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 {});