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::blockdata::script::Builder;
11 use bitcoin::blockdata::transaction::TxOut;
12 use bitcoin::hash_types::BlockHash;
15 use lightning::chain::transaction::OutPoint;
16 use lightning::ln::channelmanager::{ChannelDetails, ChannelCounterparty};
17 use lightning::ln::features::InitFeatures;
18 use lightning::ln::msgs;
19 use lightning::routing::router::{find_route, PaymentParameters, RouteHint, RouteHintHop, RouteParameters};
20 use lightning::routing::scoring::FixedPenaltyScorer;
21 use lightning::util::logger::Logger;
22 use lightning::util::ser::Readable;
23 use lightning::routing::network_graph::{NetworkGraph, RoutingFees};
25 use bitcoin::hashes::Hash;
26 use bitcoin::secp256k1::PublicKey;
27 use bitcoin::network::constants::Network;
28 use bitcoin::blockdata::constants::genesis_block;
30 use utils::test_logger;
32 use std::convert::TryInto;
33 use std::collections::HashSet;
35 use std::sync::atomic::{AtomicUsize, Ordering};
38 pub fn slice_to_be16(v: &[u8]) -> u16 {
39 ((v[0] as u16) << 8*1) |
40 ((v[1] as u16) << 8*0)
44 pub fn slice_to_be32(v: &[u8]) -> u32 {
45 ((v[0] as u32) << 8*3) |
46 ((v[1] as u32) << 8*2) |
47 ((v[2] as u32) << 8*1) |
48 ((v[3] as u32) << 8*0)
52 pub fn slice_to_be64(v: &[u8]) -> u64 {
53 ((v[0] as u64) << 8*7) |
54 ((v[1] as u64) << 8*6) |
55 ((v[2] as u64) << 8*5) |
56 ((v[3] as u64) << 8*4) |
57 ((v[4] as u64) << 8*3) |
58 ((v[5] as u64) << 8*2) |
59 ((v[6] as u64) << 8*1) |
60 ((v[7] as u64) << 8*0)
66 read_pos: AtomicUsize,
69 fn get_slice(&self, len: usize) -> Option<&[u8]> {
70 let old_pos = self.read_pos.fetch_add(len, Ordering::AcqRel);
71 if self.data.len() < old_pos + len {
74 Some(&self.data[old_pos..old_pos + len])
76 fn get_slice_nonadvancing(&self, len: usize) -> Option<&[u8]> {
77 let old_pos = self.read_pos.load(Ordering::Acquire);
78 if self.data.len() < old_pos + len {
81 Some(&self.data[old_pos..old_pos + len])
85 struct FuzzChainSource {
86 input: Arc<InputData>,
88 impl chain::Access for FuzzChainSource {
89 fn get_utxo(&self, _genesis_hash: &BlockHash, _short_channel_id: u64) -> Result<TxOut, chain::AccessError> {
90 match self.input.get_slice(2) {
91 Some(&[0, _]) => Err(chain::AccessError::UnknownChain),
92 Some(&[1, _]) => Err(chain::AccessError::UnknownTx),
93 Some(&[_, x]) => Ok(TxOut { value: 0, script_pubkey: Builder::new().push_int(x as i64).into_script().to_v0_p2wsh() }),
94 None => Err(chain::AccessError::UnknownTx),
101 pub fn do_test<Out: test_logger::Output>(data: &[u8], out: Out) {
102 let input = Arc::new(InputData {
104 read_pos: AtomicUsize::new(0),
106 macro_rules! get_slice_nonadvancing {
108 match input.get_slice_nonadvancing($len as usize) {
109 Some(slice) => slice,
114 macro_rules! get_slice {
116 match input.get_slice($len as usize) {
117 Some(slice) => slice,
123 macro_rules! decode_msg {
124 ($MsgType: path, $len: expr) => {{
125 let mut reader = ::std::io::Cursor::new(get_slice!($len));
126 match <$MsgType>::read(&mut reader) {
128 assert_eq!(reader.position(), $len as u64);
132 msgs::DecodeError::UnknownVersion => return,
133 msgs::DecodeError::UnknownRequiredFeature => return,
134 msgs::DecodeError::InvalidValue => return,
135 msgs::DecodeError::BadLengthDescriptor => return,
136 msgs::DecodeError::ShortRead => panic!("We picked the length..."),
137 msgs::DecodeError::Io(e) => panic!("{:?}", e),
138 msgs::DecodeError::UnsupportedCompression => return,
144 macro_rules! decode_msg_with_len16 {
145 ($MsgType: path, $excess: expr) => {
147 let extra_len = slice_to_be16(get_slice_nonadvancing!(2));
148 decode_msg!($MsgType, 2 + (extra_len as usize) + $excess)
153 macro_rules! get_pubkey {
155 match PublicKey::from_slice(get_slice!(33)) {
162 let logger: Arc<dyn Logger> = Arc::new(test_logger::TestLogger::new("".to_owned(), out));
164 let our_pubkey = get_pubkey!();
165 let net_graph = NetworkGraph::new(genesis_block(Network::Bitcoin).header.block_hash());
167 let mut node_pks = HashSet::new();
171 match get_slice!(1)[0] {
173 let start_len = slice_to_be16(&get_slice_nonadvancing!(2)[0..2]) as usize;
174 let addr_len = slice_to_be16(&get_slice_nonadvancing!(start_len+2 + 74)[start_len+2 + 72..start_len+2 + 74]);
175 if addr_len > (37+1)*4 {
178 let msg = decode_msg_with_len16!(msgs::UnsignedNodeAnnouncement, 288);
179 node_pks.insert(msg.node_id);
180 let _ = net_graph.update_node_from_unsigned_announcement(&msg);
183 let msg = decode_msg_with_len16!(msgs::UnsignedChannelAnnouncement, 32+8+33*4);
184 node_pks.insert(msg.node_id_1);
185 node_pks.insert(msg.node_id_2);
186 let _ = net_graph.update_channel_from_unsigned_announcement::<&FuzzChainSource>(&msg, &None);
189 let msg = decode_msg_with_len16!(msgs::UnsignedChannelAnnouncement, 32+8+33*4);
190 node_pks.insert(msg.node_id_1);
191 node_pks.insert(msg.node_id_2);
192 let _ = net_graph.update_channel_from_unsigned_announcement(&msg, &Some(&FuzzChainSource { input: Arc::clone(&input) }));
195 let _ = net_graph.update_channel_unsigned(&decode_msg!(msgs::UnsignedChannelUpdate, 72));
198 let short_channel_id = slice_to_be64(get_slice!(8));
199 net_graph.close_channel_from_update(short_channel_id, false);
201 _ if node_pks.is_empty() => {},
203 let mut first_hops_vec = Vec::new();
204 let first_hops = match get_slice!(1)[0] {
209 let rnid = node_pks.iter().skip(u16::from_be_bytes(get_slice!(2).try_into().unwrap()) as usize % node_pks.len()).next().unwrap();
210 let capacity = u64::from_be_bytes(get_slice!(8).try_into().unwrap());
211 first_hops_vec.push(ChannelDetails {
213 counterparty: ChannelCounterparty {
215 features: InitFeatures::known(),
216 unspendable_punishment_reserve: 0,
217 forwarding_info: None,
218 outbound_htlc_minimum_msat: None,
219 outbound_htlc_maximum_msat: None,
221 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
223 short_channel_id: Some(scid),
224 inbound_scid_alias: None,
225 outbound_scid_alias: None,
226 channel_value_satoshis: capacity,
227 user_channel_id: 0, inbound_capacity_msat: 0,
228 unspendable_punishment_reserve: None,
229 confirmations_required: None,
230 force_close_spend_delay: None,
231 is_outbound: true, is_funding_locked: true,
232 is_usable: true, is_public: true,
234 outbound_capacity_msat: capacity.saturating_mul(1000),
235 next_outbound_htlc_limit_msat: capacity.saturating_mul(1000),
236 inbound_htlc_minimum_msat: None,
237 inbound_htlc_maximum_msat: None,
240 Some(&first_hops_vec[..])
243 let mut last_hops = Vec::new();
245 let count = get_slice!(1)[0];
248 let rnid = node_pks.iter().skip(slice_to_be16(get_slice!(2))as usize % node_pks.len()).next().unwrap();
249 last_hops.push(RouteHint(vec![RouteHintHop {
251 short_channel_id: scid,
253 base_msat: slice_to_be32(get_slice!(4)),
254 proportional_millionths: slice_to_be32(get_slice!(4)),
256 cltv_expiry_delta: slice_to_be16(get_slice!(2)),
257 htlc_minimum_msat: Some(slice_to_be64(get_slice!(8))),
258 htlc_maximum_msat: None,
262 let scorer = FixedPenaltyScorer::with_penalty(0);
263 let random_seed_bytes: [u8; 32] = [get_slice!(1)[0]; 32];
264 for target in node_pks.iter() {
265 let route_params = RouteParameters {
266 payment_params: PaymentParameters::from_node_id(*target).with_route_hints(last_hops.clone()),
267 final_value_msat: slice_to_be64(get_slice!(8)),
268 final_cltv_expiry_delta: slice_to_be32(get_slice!(4)),
270 let _ = find_route(&our_pubkey, &route_params, &net_graph,
271 first_hops.map(|c| c.iter().collect::<Vec<_>>()).as_ref().map(|a| a.as_slice()),
272 Arc::clone(&logger), &scorer, &random_seed_bytes);
279 pub fn router_test<Out: test_logger::Output>(data: &[u8], out: Out) {
284 pub extern "C" fn router_run(data: *const u8, datalen: usize) {
285 do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull {});