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