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