]> git.bitcoin.ninja Git - rust-lightning/blob - fuzz/src/router.rs
Extend update_monitor logging
[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::ln::channelmanager::ChannelDetails;
16 use lightning::ln::features::InitFeatures;
17 use lightning::ln::msgs;
18 use lightning::ln::msgs::RoutingMessageHandler;
19 use lightning::routing::router::{get_route, RouteHint};
20 use lightning::util::logger::Logger;
21 use lightning::util::ser::Readable;
22 use lightning::routing::network_graph::{NetGraphMsgHandler, RoutingFees};
23
24 use bitcoin::secp256k1::key::PublicKey;
25
26 use utils::test_logger;
27
28 use std::sync::Arc;
29 use std::sync::atomic::{AtomicUsize, Ordering};
30
31 #[inline]
32 pub fn slice_to_be16(v: &[u8]) -> u16 {
33         ((v[0] as u16) << 8*1) |
34         ((v[1] as u16) << 8*0)
35 }
36
37 #[inline]
38 pub fn slice_to_be32(v: &[u8]) -> u32 {
39         ((v[0] as u32) << 8*3) |
40         ((v[1] as u32) << 8*2) |
41         ((v[2] as u32) << 8*1) |
42         ((v[3] as u32) << 8*0)
43 }
44
45 #[inline]
46 pub fn slice_to_be64(v: &[u8]) -> u64 {
47         ((v[0] as u64) << 8*7) |
48         ((v[1] as u64) << 8*6) |
49         ((v[2] as u64) << 8*5) |
50         ((v[3] as u64) << 8*4) |
51         ((v[4] as u64) << 8*3) |
52         ((v[5] as u64) << 8*2) |
53         ((v[6] as u64) << 8*1) |
54         ((v[7] as u64) << 8*0)
55 }
56
57
58 struct InputData {
59         data: Vec<u8>,
60         read_pos: AtomicUsize,
61 }
62 impl InputData {
63         fn get_slice(&self, len: usize) -> Option<&[u8]> {
64                 let old_pos = self.read_pos.fetch_add(len, Ordering::AcqRel);
65                 if self.data.len() < old_pos + len {
66                         return None;
67                 }
68                 Some(&self.data[old_pos..old_pos + len])
69         }
70         fn get_slice_nonadvancing(&self, len: usize) -> Option<&[u8]> {
71                 let old_pos = self.read_pos.load(Ordering::Acquire);
72                 if self.data.len() < old_pos + len {
73                         return None;
74                 }
75                 Some(&self.data[old_pos..old_pos + len])
76         }
77 }
78
79 struct FuzzChainSource {
80         input: Arc<InputData>,
81 }
82 impl chain::Access for FuzzChainSource {
83         fn get_utxo(&self, _genesis_hash: &BlockHash, _short_channel_id: u64) -> Result<TxOut, chain::AccessError> {
84                 match self.input.get_slice(2) {
85                         Some(&[0, _]) => Err(chain::AccessError::UnknownChain),
86                         Some(&[1, _]) => Err(chain::AccessError::UnknownTx),
87                         Some(&[_, x]) => Ok(TxOut { value: 0, script_pubkey: Builder::new().push_int(x as i64).into_script().to_v0_p2wsh() }),
88                         None => Err(chain::AccessError::UnknownTx),
89                         _ => unreachable!(),
90                 }
91         }
92 }
93
94 #[inline]
95 pub fn do_test<Out: test_logger::Output>(data: &[u8], out: Out) {
96         let input = Arc::new(InputData {
97                 data: data.to_vec(),
98                 read_pos: AtomicUsize::new(0),
99         });
100         macro_rules! get_slice_nonadvancing {
101                 ($len: expr) => {
102                         match input.get_slice_nonadvancing($len as usize) {
103                                 Some(slice) => slice,
104                                 None => return,
105                         }
106                 }
107         }
108         macro_rules! get_slice {
109                 ($len: expr) => {
110                         match input.get_slice($len as usize) {
111                                 Some(slice) => slice,
112                                 None => return,
113                         }
114                 }
115         }
116
117         macro_rules! decode_msg {
118                 ($MsgType: path, $len: expr) => {{
119                         let mut reader = ::std::io::Cursor::new(get_slice!($len));
120                         match <$MsgType>::read(&mut reader) {
121                                 Ok(msg) => msg,
122                                 Err(e) => match e {
123                                         msgs::DecodeError::UnknownVersion => return,
124                                         msgs::DecodeError::UnknownRequiredFeature => return,
125                                         msgs::DecodeError::InvalidValue => return,
126                                         msgs::DecodeError::BadLengthDescriptor => return,
127                                         msgs::DecodeError::ShortRead => panic!("We picked the length..."),
128                                         msgs::DecodeError::Io(e) => panic!(format!("{}", e)),
129                                 }
130                         }
131                 }}
132         }
133
134         macro_rules! decode_msg_with_len16 {
135                 ($MsgType: path, $begin_len: expr, $excess: expr) => {
136                         {
137                                 let extra_len = slice_to_be16(&get_slice_nonadvancing!($begin_len as usize + 2)[$begin_len..$begin_len + 2]);
138                                 decode_msg!($MsgType, $begin_len as usize + 2 + (extra_len as usize) + $excess)
139                         }
140                 }
141         }
142
143         macro_rules! get_pubkey {
144                 () => {
145                         match PublicKey::from_slice(get_slice!(33)) {
146                                 Ok(key) => key,
147                                 Err(_) => return,
148                         }
149                 }
150         }
151
152         let logger: Arc<dyn Logger> = Arc::new(test_logger::TestLogger::new("".to_owned(), out));
153         let chain_source = if get_slice!(1)[0] % 2 == 0 {
154                 None
155         } else {
156                 Some(Arc::new(FuzzChainSource {
157                         input: Arc::clone(&input),
158                 }))
159         };
160
161         let our_pubkey = get_pubkey!();
162         let net_graph_msg_handler = NetGraphMsgHandler::new(chain_source, Arc::clone(&logger));
163
164         loop {
165                 match get_slice!(1)[0] {
166                         0 => {
167                                 let start_len = slice_to_be16(&get_slice_nonadvancing!(64 + 2)[64..64 + 2]) as usize;
168                                 let addr_len = slice_to_be16(&get_slice_nonadvancing!(64+start_len+2 + 74)[64+start_len+2 + 72..64+start_len+2 + 74]);
169                                 if addr_len > (37+1)*4 {
170                                         return;
171                                 }
172                                 let _ = net_graph_msg_handler.handle_node_announcement(&decode_msg_with_len16!(msgs::NodeAnnouncement, 64, 288));
173                         },
174                         1 => {
175                                 let _ = net_graph_msg_handler.handle_channel_announcement(&decode_msg_with_len16!(msgs::ChannelAnnouncement, 64*4, 32+8+33*4));
176                         },
177                         2 => {
178                                 let _ = net_graph_msg_handler.handle_channel_update(&decode_msg!(msgs::ChannelUpdate, 136));
179                         },
180                         3 => {
181                                 match get_slice!(1)[0] {
182                                         0 => {
183                                                 net_graph_msg_handler.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelUpdateMessage {msg: decode_msg!(msgs::ChannelUpdate, 136)});
184                                         },
185                                         1 => {
186                                                 let short_channel_id = slice_to_be64(get_slice!(8));
187                                                 net_graph_msg_handler.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed {short_channel_id, is_permanent: false});
188                                         },
189                                         _ => return,
190                                 }
191                         },
192                         4 => {
193                                 let target = get_pubkey!();
194                                 let mut first_hops_vec = Vec::new();
195                                 let first_hops = match get_slice!(1)[0] {
196                                         0 => None,
197                                         1 => {
198                                                 let count = slice_to_be16(get_slice!(2));
199                                                 for _ in 0..count {
200                                                         first_hops_vec.push(ChannelDetails {
201                                                                 channel_id: [0; 32],
202                                                                 short_channel_id: Some(slice_to_be64(get_slice!(8))),
203                                                                 remote_network_id: get_pubkey!(),
204                                                                 counterparty_features: InitFeatures::empty(),
205                                                                 channel_value_satoshis: slice_to_be64(get_slice!(8)),
206                                                                 user_id: 0,
207                                                                 inbound_capacity_msat: 0,
208                                                                 is_live: true,
209                                                                 outbound_capacity_msat: 0,
210                                                         });
211                                                 }
212                                                 Some(&first_hops_vec[..])
213                                         },
214                                         _ => return,
215                                 };
216                                 let mut last_hops_vec = Vec::new();
217                                 let last_hops = {
218                                         let count = slice_to_be16(get_slice!(2));
219                                         for _ in 0..count {
220                                                 last_hops_vec.push(RouteHint {
221                                                         src_node_id: get_pubkey!(),
222                                                         short_channel_id: slice_to_be64(get_slice!(8)),
223                                                         fees: RoutingFees {
224                                                                 base_msat: slice_to_be32(get_slice!(4)),
225                                                                 proportional_millionths: slice_to_be32(get_slice!(4)),
226                                                         },
227                                                         cltv_expiry_delta: slice_to_be16(get_slice!(2)),
228                                                         htlc_minimum_msat: slice_to_be64(get_slice!(8)),
229                                                 });
230                                         }
231                                         &last_hops_vec[..]
232                                 };
233                                 let _ = get_route(&our_pubkey, &net_graph_msg_handler.network_graph.read().unwrap(), &target,
234                                         first_hops.map(|c| c.iter().collect::<Vec<_>>()).as_ref().map(|a| a.as_slice()),
235                                         &last_hops.iter().collect::<Vec<_>>(),
236                                         slice_to_be64(get_slice!(8)), slice_to_be32(get_slice!(4)), Arc::clone(&logger));
237                         },
238                         _ => return,
239                 }
240         }
241 }
242
243 pub fn router_test<Out: test_logger::Output>(data: &[u8], out: Out) {
244         do_test(data, out);
245 }
246
247 #[no_mangle]
248 pub extern "C" fn router_run(data: *const u8, datalen: usize) {
249         do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull {});
250 }