]> git.bitcoin.ninja Git - rust-lightning/blob - fuzz/src/router.rs
80ea1f1bc73d6932e4ab3db1a2da8904b0f77f14
[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::script::Builder;
11 use bitcoin::blockdata::transaction::TxOut;
12 use bitcoin::hash_types::BlockHash;
13
14 use lightning::chain;
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};
24
25 use bitcoin::hashes::Hash;
26 use bitcoin::secp256k1::PublicKey;
27 use bitcoin::network::constants::Network;
28 use bitcoin::blockdata::constants::genesis_block;
29
30 use utils::test_logger;
31
32 use std::convert::TryInto;
33 use std::collections::HashSet;
34 use std::sync::Arc;
35 use std::sync::atomic::{AtomicUsize, Ordering};
36
37 #[inline]
38 pub fn slice_to_be16(v: &[u8]) -> u16 {
39         ((v[0] as u16) << 8*1) |
40         ((v[1] as u16) << 8*0)
41 }
42
43 #[inline]
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)
49 }
50
51 #[inline]
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)
61 }
62
63
64 struct InputData {
65         data: Vec<u8>,
66         read_pos: AtomicUsize,
67 }
68 impl InputData {
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 {
72                         return None;
73                 }
74                 Some(&self.data[old_pos..old_pos + len])
75         }
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 {
79                         return None;
80                 }
81                 Some(&self.data[old_pos..old_pos + len])
82         }
83 }
84
85 struct FuzzChainSource {
86         input: Arc<InputData>,
87 }
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),
95                         _ => unreachable!(),
96                 }
97         }
98 }
99
100 #[inline]
101 pub fn do_test<Out: test_logger::Output>(data: &[u8], out: Out) {
102         let input = Arc::new(InputData {
103                 data: data.to_vec(),
104                 read_pos: AtomicUsize::new(0),
105         });
106         macro_rules! get_slice_nonadvancing {
107                 ($len: expr) => {
108                         match input.get_slice_nonadvancing($len as usize) {
109                                 Some(slice) => slice,
110                                 None => return,
111                         }
112                 }
113         }
114         macro_rules! get_slice {
115                 ($len: expr) => {
116                         match input.get_slice($len as usize) {
117                                 Some(slice) => slice,
118                                 None => return,
119                         }
120                 }
121         }
122
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) {
127                                 Ok(msg) => {
128                                         assert_eq!(reader.position(), $len as u64);
129                                         msg
130                                 },
131                                 Err(e) => match e {
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,
139                                 }
140                         }
141                 }}
142         }
143
144         macro_rules! decode_msg_with_len16 {
145                 ($MsgType: path, $excess: expr) => {
146                         {
147                                 let extra_len = slice_to_be16(get_slice_nonadvancing!(2));
148                                 decode_msg!($MsgType, 2 + (extra_len as usize) + $excess)
149                         }
150                 }
151         }
152
153         macro_rules! get_pubkey {
154                 () => {
155                         match PublicKey::from_slice(get_slice!(33)) {
156                                 Ok(key) => key,
157                                 Err(_) => return,
158                         }
159                 }
160         }
161
162         let logger: Arc<dyn Logger> = Arc::new(test_logger::TestLogger::new("".to_owned(), out));
163
164         let our_pubkey = get_pubkey!();
165         let net_graph = NetworkGraph::new(genesis_block(Network::Bitcoin).header.block_hash());
166
167         let mut node_pks = HashSet::new();
168         let mut scid = 42;
169
170         loop {
171                 match get_slice!(1)[0] {
172                         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 {
176                                         return;
177                                 }
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);
181                         },
182                         1 => {
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);
187                         },
188                         2 => {
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) }));
193                         },
194                         3 => {
195                                 let _ = net_graph.update_channel_unsigned(&decode_msg!(msgs::UnsignedChannelUpdate, 72));
196                         },
197                         4 => {
198                                 let short_channel_id = slice_to_be64(get_slice!(8));
199                                 net_graph.close_channel_from_update(short_channel_id, false);
200                         },
201                         _ if node_pks.is_empty() => {},
202                         _ => {
203                                 let mut first_hops_vec = Vec::new();
204                                 let first_hops = match get_slice!(1)[0] {
205                                         0 => None,
206                                         count => {
207                                                 for _ in 0..count {
208                                                         scid += 1;
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 {
212                                                                 channel_id: [0; 32],
213                                                                 counterparty: ChannelCounterparty {
214                                                                         node_id: *rnid,
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,
220                                                                 },
221                                                                 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
222                                                                 channel_type: None,
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,
233                                                                 balance_msat: 0,
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,
238                                                         });
239                                                 }
240                                                 Some(&first_hops_vec[..])
241                                         },
242                                 };
243                                 let mut last_hops = Vec::new();
244                                 {
245                                         let count = get_slice!(1)[0];
246                                         for _ in 0..count {
247                                                 scid += 1;
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 {
250                                                         src_node_id: *rnid,
251                                                         short_channel_id: scid,
252                                                         fees: RoutingFees {
253                                                                 base_msat: slice_to_be32(get_slice!(4)),
254                                                                 proportional_millionths: slice_to_be32(get_slice!(4)),
255                                                         },
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,
259                                                 }]));
260                                         }
261                                 }
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)),
269                                         };
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);
273                                 }
274                         },
275                 }
276         }
277 }
278
279 pub fn router_test<Out: test_logger::Output>(data: &[u8], out: Out) {
280         do_test(data, out);
281 }
282
283 #[no_mangle]
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 {});
286 }