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::ChannelId;
18 use lightning::ln::channel_state::{ChannelDetails, ChannelCounterparty, ChannelShutdownState};
19 use lightning::ln::channelmanager;
20 use lightning::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures};
21 use lightning::ln::msgs;
22 use lightning::offers::invoice::BlindedPayInfo;
23 use lightning::routing::gossip::{NetworkGraph, RoutingFees};
24 use lightning::routing::utxo::{UtxoFuture, UtxoLookup, UtxoLookupError, UtxoResult};
25 use lightning::routing::router::{find_route, PaymentParameters, RouteHint, RouteHintHop, RouteParameters};
26 use lightning::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
27 use lightning::util::config::UserConfig;
28 use lightning::util::hash_tables::*;
29 use lightning::util::ser::Readable;
31 use bitcoin::hashes::Hash;
32 use bitcoin::secp256k1::PublicKey;
33 use bitcoin::network::Network;
35 use crate::utils::test_logger;
37 use std::convert::TryInto;
39 use std::sync::atomic::{AtomicUsize, Ordering};
42 pub fn slice_to_be16(v: &[u8]) -> u16 {
43 ((v[0] as u16) << 8*1) |
44 ((v[1] as u16) << 8*0)
48 pub fn slice_to_be32(v: &[u8]) -> u32 {
49 ((v[0] as u32) << 8*3) |
50 ((v[1] as u32) << 8*2) |
51 ((v[2] as u32) << 8*1) |
52 ((v[3] as u32) << 8*0)
56 pub fn slice_to_be64(v: &[u8]) -> u64 {
57 ((v[0] as u64) << 8*7) |
58 ((v[1] as u64) << 8*6) |
59 ((v[2] as u64) << 8*5) |
60 ((v[3] as u64) << 8*4) |
61 ((v[4] as u64) << 8*3) |
62 ((v[5] as u64) << 8*2) |
63 ((v[6] as u64) << 8*1) |
64 ((v[7] as u64) << 8*0)
70 read_pos: AtomicUsize,
73 fn get_slice(&self, len: usize) -> Option<&[u8]> {
74 let old_pos = self.read_pos.fetch_add(len, Ordering::AcqRel);
75 if self.data.len() < old_pos + len {
78 Some(&self.data[old_pos..old_pos + len])
80 fn get_slice_nonadvancing(&self, len: usize) -> Option<&[u8]> {
81 let old_pos = self.read_pos.load(Ordering::Acquire);
82 if self.data.len() < old_pos + len {
85 Some(&self.data[old_pos..old_pos + len])
89 struct FuzzChainSource<'a, 'b, Out: test_logger::Output> {
90 input: Arc<InputData>,
91 net_graph: &'a NetworkGraph<&'b test_logger::TestLogger<Out>>,
93 impl<Out: test_logger::Output> UtxoLookup for FuzzChainSource<'_, '_, Out> {
94 fn get_utxo(&self, _chain_hash: &ChainHash, _short_channel_id: u64) -> UtxoResult {
95 let input_slice = self.input.get_slice(2);
96 if input_slice.is_none() { return UtxoResult::Sync(Err(UtxoLookupError::UnknownTx)); }
97 let input_slice = input_slice.unwrap();
99 value: Amount::from_sat(if input_slice[0] % 2 == 0 { 1_000_000 } else { 1_000 }),
100 script_pubkey: Builder::new().push_int(input_slice[1] as i64).into_script().to_p2wsh(),
103 &[0, _] => UtxoResult::Sync(Err(UtxoLookupError::UnknownChain)),
104 &[1, _] => UtxoResult::Sync(Err(UtxoLookupError::UnknownTx)),
106 let future = UtxoFuture::new();
107 future.resolve_without_forwarding(self.net_graph, Ok(txo_res));
108 UtxoResult::Async(future.clone())
111 let future = UtxoFuture::new();
112 future.resolve_without_forwarding(self.net_graph, Err(UtxoLookupError::UnknownTx));
113 UtxoResult::Async(future.clone())
116 UtxoResult::Async(UtxoFuture::new()) // the future will never resolve
118 &[..] => UtxoResult::Sync(Ok(txo_res)),
124 pub fn do_test<Out: test_logger::Output>(data: &[u8], out: Out) {
125 let input = Arc::new(InputData {
127 read_pos: AtomicUsize::new(0),
129 macro_rules! get_slice_nonadvancing {
131 match input.get_slice_nonadvancing($len as usize) {
132 Some(slice) => slice,
137 macro_rules! get_slice {
139 match input.get_slice($len as usize) {
140 Some(slice) => slice,
146 macro_rules! decode_msg {
147 ($MsgType: path, $len: expr) => {{
148 let mut reader = ::std::io::Cursor::new(get_slice!($len));
149 match <$MsgType>::read(&mut reader) {
151 assert_eq!(reader.position(), $len as u64);
155 msgs::DecodeError::UnknownVersion => return,
156 msgs::DecodeError::UnknownRequiredFeature => return,
157 msgs::DecodeError::InvalidValue => return,
158 msgs::DecodeError::BadLengthDescriptor => return,
159 msgs::DecodeError::ShortRead => panic!("We picked the length..."),
160 msgs::DecodeError::Io(e) => panic!("{:?}", e),
161 msgs::DecodeError::UnsupportedCompression => return,
162 msgs::DecodeError::DangerousValue => return,
168 macro_rules! decode_msg_with_len16 {
169 ($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)
177 macro_rules! get_pubkey_from_node_id {
178 ($node_id: expr ) => {
179 match PublicKey::from_slice($node_id.as_slice()) {
186 macro_rules! get_pubkey {
188 match PublicKey::from_slice(get_slice!(33)) {
195 let logger = test_logger::TestLogger::new("".to_owned(), out);
197 let our_pubkey = get_pubkey!();
198 let net_graph = NetworkGraph::new(Network::Bitcoin, &logger);
199 let chain_source = FuzzChainSource {
200 input: Arc::clone(&input),
201 net_graph: &net_graph,
204 let mut node_pks = new_hash_map();
207 macro_rules! first_hops {
208 ($first_hops_vec: expr) => {
209 match get_slice!(1)[0] {
215 node_pks.iter().skip(u16::from_be_bytes(get_slice!(2).try_into().unwrap()) as usize % node_pks.len()).next().unwrap();
216 let capacity = u64::from_be_bytes(get_slice!(8).try_into().unwrap());
217 $first_hops_vec.push(ChannelDetails {
218 channel_id: ChannelId::new_zero(),
219 counterparty: ChannelCounterparty {
221 features: channelmanager::provided_init_features(&UserConfig::default()),
222 unspendable_punishment_reserve: 0,
223 forwarding_info: None,
224 outbound_htlc_minimum_msat: None,
225 outbound_htlc_maximum_msat: None,
227 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
229 short_channel_id: Some(scid),
230 inbound_scid_alias: None,
231 outbound_scid_alias: None,
232 channel_value_satoshis: capacity,
233 user_channel_id: 0, inbound_capacity_msat: 0,
234 unspendable_punishment_reserve: None,
235 confirmations_required: None,
237 force_close_spend_delay: None,
238 is_outbound: true, is_channel_ready: true,
239 is_usable: true, is_public: true,
241 outbound_capacity_msat: capacity.saturating_mul(1000),
242 next_outbound_htlc_limit_msat: capacity.saturating_mul(1000),
243 next_outbound_htlc_minimum_msat: 0,
244 inbound_htlc_minimum_msat: None,
245 inbound_htlc_maximum_msat: None,
247 feerate_sat_per_1000_weight: None,
248 channel_shutdown_state: Some(ChannelShutdownState::NotShuttingDown),
249 pending_inbound_htlcs: Vec::new(),
250 pending_outbound_htlcs: Vec::new(),
253 Some(&$first_hops_vec[..])
259 macro_rules! last_hops {
260 ($last_hops: expr) => {
261 let count = get_slice!(1)[0];
265 node_pks.iter().skip(slice_to_be16(get_slice!(2)) as usize % node_pks.len()).next().unwrap();
266 $last_hops.push(RouteHint(vec![RouteHintHop {
268 short_channel_id: scid,
270 base_msat: slice_to_be32(get_slice!(4)),
271 proportional_millionths: slice_to_be32(get_slice!(4)),
273 cltv_expiry_delta: slice_to_be16(get_slice!(2)),
274 htlc_minimum_msat: Some(slice_to_be64(get_slice!(8))),
275 htlc_maximum_msat: None,
281 macro_rules! find_routes {
282 ($first_hops: expr, $node_pks: expr, $route_params: expr) => {
283 let scorer = ProbabilisticScorer::new(ProbabilisticScoringDecayParameters::default(), &net_graph, &logger);
284 let random_seed_bytes: [u8; 32] = [get_slice!(1)[0]; 32];
285 for (target, ()) in $node_pks {
286 let final_value_msat = slice_to_be64(get_slice!(8));
287 let final_cltv_expiry_delta = slice_to_be32(get_slice!(4));
288 let route_params = $route_params(final_value_msat, final_cltv_expiry_delta, target);
289 let _ = find_route(&our_pubkey, &route_params, &net_graph,
290 $first_hops.map(|c| c.iter().collect::<Vec<_>>()).as_ref().map(|a| a.as_slice()),
291 &logger, &scorer, &ProbabilisticScoringFeeParameters::default(), &random_seed_bytes);
297 match get_slice!(1)[0] {
299 let start_len = slice_to_be16(&get_slice_nonadvancing!(2)[0..2]) as usize;
300 let addr_len = slice_to_be16(&get_slice_nonadvancing!(start_len+2 + 74)[start_len+2 + 72..start_len+2 + 74]);
301 if addr_len > (37+1)*4 {
304 let msg = decode_msg_with_len16!(msgs::UnsignedNodeAnnouncement, 288);
305 node_pks.insert(get_pubkey_from_node_id!(msg.node_id), ());
306 let _ = net_graph.update_node_from_unsigned_announcement(&msg);
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::
313 <&FuzzChainSource<'_, '_, Out>>(&msg, &None);
316 let msg = decode_msg_with_len16!(msgs::UnsignedChannelAnnouncement, 32+8+33*4);
317 node_pks.insert(get_pubkey_from_node_id!(msg.node_id_1), ());
318 node_pks.insert(get_pubkey_from_node_id!(msg.node_id_2), ());
319 let _ = net_graph.update_channel_from_unsigned_announcement(&msg, &Some(&chain_source));
322 let _ = net_graph.update_channel_unsigned(&decode_msg!(msgs::UnsignedChannelUpdate, 72));
325 let short_channel_id = slice_to_be64(get_slice!(8));
326 net_graph.channel_failed_permanent(short_channel_id);
328 _ if node_pks.is_empty() => {},
330 let mut first_hops_vec = Vec::new();
331 // Use macros here and in the blinded match arm to ensure values are fetched from the fuzz
332 // input in the same order, for better coverage.
333 let first_hops = first_hops!(first_hops_vec);
334 let mut last_hops = Vec::new();
335 last_hops!(last_hops);
336 find_routes!(first_hops, node_pks.iter(), |final_amt, final_delta, target: &PublicKey| {
337 RouteParameters::from_payment_params_and_value(
338 PaymentParameters::from_node_id(*target, final_delta)
339 .with_route_hints(last_hops.clone()).unwrap(),
344 let mut first_hops_vec = Vec::new();
345 let first_hops = first_hops!(first_hops_vec);
346 let mut last_hops_unblinded = Vec::new();
347 last_hops!(last_hops_unblinded);
348 let dummy_pk = PublicKey::from_slice(&[2; 33]).unwrap();
349 let last_hops: Vec<(BlindedPayInfo, BlindedPath)> = last_hops_unblinded.into_iter().map(|hint| {
350 let hop = &hint.0[0];
351 let payinfo = BlindedPayInfo {
352 fee_base_msat: hop.fees.base_msat,
353 fee_proportional_millionths: hop.fees.proportional_millionths,
354 htlc_minimum_msat: hop.htlc_minimum_msat.unwrap(),
355 htlc_maximum_msat: hop.htlc_minimum_msat.unwrap().saturating_mul(100),
356 cltv_expiry_delta: hop.cltv_expiry_delta,
357 features: BlindedHopFeatures::empty(),
359 let num_blinded_hops = x % 250;
360 let mut blinded_hops = Vec::new();
361 for _ in 0..num_blinded_hops {
362 blinded_hops.push(BlindedHop {
363 blinded_node_id: dummy_pk,
364 encrypted_payload: Vec::new()
367 (payinfo, BlindedPath {
368 introduction_node: IntroductionNode::NodeId(hop.src_node_id),
369 blinding_point: dummy_pk,
373 let mut features = Bolt12InvoiceFeatures::empty();
374 features.set_basic_mpp_optional();
375 find_routes!(first_hops, [(dummy_pk, ())].iter(), |final_amt, _, _| {
376 RouteParameters::from_payment_params_and_value(PaymentParameters::blinded(last_hops.clone())
377 .with_bolt12_features(features.clone()).unwrap(),
385 pub fn router_test<Out: test_logger::Output>(data: &[u8], out: Out) {
390 pub extern "C" fn router_run(data: *const u8, datalen: usize) {
391 do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull {});