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