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