Swap `PublicKey` for `NodeId` in `UnsignedChannelAnnouncement`
[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::{self, ChannelDetails, ChannelCounterparty};
17 use lightning::ln::msgs;
18 use lightning::routing::gossip::{NetworkGraph, RoutingFees};
19 use lightning::routing::router::{find_route, PaymentParameters, RouteHint, RouteHintHop, RouteParameters};
20 use lightning::routing::scoring::FixedPenaltyScorer;
21 use lightning::util::config::UserConfig;
22 use lightning::util::ser::Readable;
23
24 use bitcoin::hashes::Hash;
25 use bitcoin::secp256k1::PublicKey;
26 use bitcoin::network::constants::Network;
27 use bitcoin::blockdata::constants::genesis_block;
28
29 use crate::utils::test_logger;
30
31 use std::convert::TryInto;
32 use hashbrown::HashSet;
33 use std::sync::Arc;
34 use std::sync::atomic::{AtomicUsize, Ordering};
35
36 #[inline]
37 pub fn slice_to_be16(v: &[u8]) -> u16 {
38         ((v[0] as u16) << 8*1) |
39         ((v[1] as u16) << 8*0)
40 }
41
42 #[inline]
43 pub fn slice_to_be32(v: &[u8]) -> u32 {
44         ((v[0] as u32) << 8*3) |
45         ((v[1] as u32) << 8*2) |
46         ((v[2] as u32) << 8*1) |
47         ((v[3] as u32) << 8*0)
48 }
49
50 #[inline]
51 pub fn slice_to_be64(v: &[u8]) -> u64 {
52         ((v[0] as u64) << 8*7) |
53         ((v[1] as u64) << 8*6) |
54         ((v[2] as u64) << 8*5) |
55         ((v[3] as u64) << 8*4) |
56         ((v[4] as u64) << 8*3) |
57         ((v[5] as u64) << 8*2) |
58         ((v[6] as u64) << 8*1) |
59         ((v[7] as u64) << 8*0)
60 }
61
62
63 struct InputData {
64         data: Vec<u8>,
65         read_pos: AtomicUsize,
66 }
67 impl InputData {
68         fn get_slice(&self, len: usize) -> Option<&[u8]> {
69                 let old_pos = self.read_pos.fetch_add(len, Ordering::AcqRel);
70                 if self.data.len() < old_pos + len {
71                         return None;
72                 }
73                 Some(&self.data[old_pos..old_pos + len])
74         }
75         fn get_slice_nonadvancing(&self, len: usize) -> Option<&[u8]> {
76                 let old_pos = self.read_pos.load(Ordering::Acquire);
77                 if self.data.len() < old_pos + len {
78                         return None;
79                 }
80                 Some(&self.data[old_pos..old_pos + len])
81         }
82 }
83
84 struct FuzzChainSource {
85         input: Arc<InputData>,
86 }
87 impl chain::Access for FuzzChainSource {
88         fn get_utxo(&self, _genesis_hash: &BlockHash, _short_channel_id: u64) -> Result<TxOut, chain::AccessError> {
89                 match self.input.get_slice(2) {
90                         Some(&[0, _]) => Err(chain::AccessError::UnknownChain),
91                         Some(&[1, _]) => Err(chain::AccessError::UnknownTx),
92                         Some(&[_, x]) => Ok(TxOut { value: 0, script_pubkey: Builder::new().push_int(x as i64).into_script().to_v0_p2wsh() }),
93                         None => Err(chain::AccessError::UnknownTx),
94                         _ => unreachable!(),
95                 }
96         }
97 }
98
99 #[inline]
100 pub fn do_test<Out: test_logger::Output>(data: &[u8], out: Out) {
101         let input = Arc::new(InputData {
102                 data: data.to_vec(),
103                 read_pos: AtomicUsize::new(0),
104         });
105         macro_rules! get_slice_nonadvancing {
106                 ($len: expr) => {
107                         match input.get_slice_nonadvancing($len as usize) {
108                                 Some(slice) => slice,
109                                 None => return,
110                         }
111                 }
112         }
113         macro_rules! get_slice {
114                 ($len: expr) => {
115                         match input.get_slice($len as usize) {
116                                 Some(slice) => slice,
117                                 None => return,
118                         }
119                 }
120         }
121
122         macro_rules! decode_msg {
123                 ($MsgType: path, $len: expr) => {{
124                         let mut reader = ::std::io::Cursor::new(get_slice!($len));
125                         match <$MsgType>::read(&mut reader) {
126                                 Ok(msg) => {
127                                         assert_eq!(reader.position(), $len as u64);
128                                         msg
129                                 },
130                                 Err(e) => match e {
131                                         msgs::DecodeError::UnknownVersion => return,
132                                         msgs::DecodeError::UnknownRequiredFeature => return,
133                                         msgs::DecodeError::InvalidValue => return,
134                                         msgs::DecodeError::BadLengthDescriptor => return,
135                                         msgs::DecodeError::ShortRead => panic!("We picked the length..."),
136                                         msgs::DecodeError::Io(e) => panic!("{:?}", e),
137                                         msgs::DecodeError::UnsupportedCompression => return,
138                                 }
139                         }
140                 }}
141         }
142
143         macro_rules! decode_msg_with_len16 {
144                 ($MsgType: path, $excess: expr) => {
145                         {
146                                 let extra_len = slice_to_be16(get_slice_nonadvancing!(2));
147                                 decode_msg!($MsgType, 2 + (extra_len as usize) + $excess)
148                         }
149                 }
150         }
151
152         macro_rules! get_pubkey_from_node_id {
153                 ($node_id: expr ) => {
154                         match PublicKey::from_slice($node_id.as_slice()) {
155                                 Ok(pk) => pk,
156                                 Err(_) => return,
157                         }
158                 }
159         }
160
161         macro_rules! get_pubkey {
162                 () => {
163                         match PublicKey::from_slice(get_slice!(33)) {
164                                 Ok(key) => key,
165                                 Err(_) => return,
166                         }
167                 }
168         }
169
170         let logger = test_logger::TestLogger::new("".to_owned(), out);
171
172         let our_pubkey = get_pubkey!();
173         let net_graph = NetworkGraph::new(genesis_block(Network::Bitcoin).header.block_hash(), &logger);
174
175         let mut node_pks = HashSet::new();
176         let mut scid = 42;
177
178         loop {
179                 match get_slice!(1)[0] {
180                         0 => {
181                                 let start_len = slice_to_be16(&get_slice_nonadvancing!(2)[0..2]) as usize;
182                                 let addr_len = slice_to_be16(&get_slice_nonadvancing!(start_len+2 + 74)[start_len+2 + 72..start_len+2 + 74]);
183                                 if addr_len > (37+1)*4 {
184                                         return;
185                                 }
186                                 let msg = decode_msg_with_len16!(msgs::UnsignedNodeAnnouncement, 288);
187                                 node_pks.insert(msg.node_id);
188                                 let _ = net_graph.update_node_from_unsigned_announcement(&msg);
189                         },
190                         1 => {
191                                 let msg = decode_msg_with_len16!(msgs::UnsignedChannelAnnouncement, 32+8+33*4);
192                                 node_pks.insert(get_pubkey_from_node_id!(msg.node_id_1));
193                                 node_pks.insert(get_pubkey_from_node_id!(msg.node_id_2));
194                                 let _ = net_graph.update_channel_from_unsigned_announcement::<&FuzzChainSource>(&msg, &None);
195                         },
196                         2 => {
197                                 let msg = decode_msg_with_len16!(msgs::UnsignedChannelAnnouncement, 32+8+33*4);
198                                 node_pks.insert(get_pubkey_from_node_id!(msg.node_id_1));
199                                 node_pks.insert(get_pubkey_from_node_id!(msg.node_id_2));
200                                 let _ = net_graph.update_channel_from_unsigned_announcement(&msg, &Some(&FuzzChainSource { input: Arc::clone(&input) }));
201                         },
202                         3 => {
203                                 let _ = net_graph.update_channel_unsigned(&decode_msg!(msgs::UnsignedChannelUpdate, 72));
204                         },
205                         4 => {
206                                 let short_channel_id = slice_to_be64(get_slice!(8));
207                                 net_graph.channel_failed(short_channel_id, false);
208                         },
209                         _ if node_pks.is_empty() => {},
210                         _ => {
211                                 let mut first_hops_vec = Vec::new();
212                                 let first_hops = match get_slice!(1)[0] {
213                                         0 => None,
214                                         count => {
215                                                 for _ in 0..count {
216                                                         scid += 1;
217                                                         let rnid = node_pks.iter().skip(u16::from_be_bytes(get_slice!(2).try_into().unwrap()) as usize % node_pks.len()).next().unwrap();
218                                                         let capacity = u64::from_be_bytes(get_slice!(8).try_into().unwrap());
219                                                         first_hops_vec.push(ChannelDetails {
220                                                                 channel_id: [0; 32],
221                                                                 counterparty: ChannelCounterparty {
222                                                                         node_id: *rnid,
223                                                                         features: channelmanager::provided_init_features(&UserConfig::default()),
224                                                                         unspendable_punishment_reserve: 0,
225                                                                         forwarding_info: None,
226                                                                         outbound_htlc_minimum_msat: None,
227                                                                         outbound_htlc_maximum_msat: None,
228                                                                 },
229                                                                 funding_txo: Some(OutPoint { txid: bitcoin::Txid::from_slice(&[0; 32]).unwrap(), index: 0 }),
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, inbound_capacity_msat: 0,
236                                                                 unspendable_punishment_reserve: None,
237                                                                 confirmations_required: None,
238                                                                 confirmations: None,
239                                                                 force_close_spend_delay: None,
240                                                                 is_outbound: true, is_channel_ready: true,
241                                                                 is_usable: true, is_public: true,
242                                                                 balance_msat: 0,
243                                                                 outbound_capacity_msat: capacity.saturating_mul(1000),
244                                                                 next_outbound_htlc_limit_msat: capacity.saturating_mul(1000),
245                                                                 inbound_htlc_minimum_msat: None,
246                                                                 inbound_htlc_maximum_msat: None,
247                                                                 config: None,
248                                                         });
249                                                 }
250                                                 Some(&first_hops_vec[..])
251                                         },
252                                 };
253                                 let mut last_hops = Vec::new();
254                                 {
255                                         let count = get_slice!(1)[0];
256                                         for _ in 0..count {
257                                                 scid += 1;
258                                                 let rnid = node_pks.iter().skip(slice_to_be16(get_slice!(2))as usize % node_pks.len()).next().unwrap();
259                                                 last_hops.push(RouteHint(vec![RouteHintHop {
260                                                         src_node_id: *rnid,
261                                                         short_channel_id: scid,
262                                                         fees: RoutingFees {
263                                                                 base_msat: slice_to_be32(get_slice!(4)),
264                                                                 proportional_millionths: slice_to_be32(get_slice!(4)),
265                                                         },
266                                                         cltv_expiry_delta: slice_to_be16(get_slice!(2)),
267                                                         htlc_minimum_msat: Some(slice_to_be64(get_slice!(8))),
268                                                         htlc_maximum_msat: None,
269                                                 }]));
270                                         }
271                                 }
272                                 let scorer = FixedPenaltyScorer::with_penalty(0);
273                                 let random_seed_bytes: [u8; 32] = [get_slice!(1)[0]; 32];
274                                 for target in node_pks.iter() {
275                                         let final_value_msat = slice_to_be64(get_slice!(8));
276                                         let final_cltv_expiry_delta = slice_to_be32(get_slice!(4));
277                                         let route_params = RouteParameters {
278                                                 payment_params: PaymentParameters::from_node_id(*target, final_cltv_expiry_delta)
279                                                         .with_route_hints(last_hops.clone()),
280                                                 final_value_msat,
281                                                 final_cltv_expiry_delta,
282                                         };
283                                         let _ = find_route(&our_pubkey, &route_params, &net_graph,
284                                                 first_hops.map(|c| c.iter().collect::<Vec<_>>()).as_ref().map(|a| a.as_slice()),
285                                                 &logger, &scorer, &random_seed_bytes);
286                                 }
287                         },
288                 }
289         }
290 }
291
292 pub fn router_test<Out: test_logger::Output>(data: &[u8], out: Out) {
293         do_test(data, out);
294 }
295
296 #[no_mangle]
297 pub extern "C" fn router_run(data: *const u8, datalen: usize) {
298         do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull {});
299 }