Disable push_msat in full_stack_target temporarily
[rust-lightning] / fuzz / fuzz_targets / full_stack_target.rs
1 extern crate bitcoin;
2 extern crate crypto;
3 extern crate lightning;
4 extern crate secp256k1;
5
6 use bitcoin::blockdata::block::BlockHeader;
7 use bitcoin::blockdata::transaction::{Transaction, TxOut};
8 use bitcoin::blockdata::script::Script;
9 use bitcoin::network::constants::Network;
10 use bitcoin::network::serialize::{deserialize, serialize, BitcoinHash};
11 use bitcoin::util::hash::Sha256dHash;
12
13 use crypto::digest::Digest;
14
15 use lightning::chain::chaininterface::{BroadcasterInterface,ConfirmationTarget,ChainListener,FeeEstimator,ChainWatchInterfaceUtil};
16 use lightning::chain::transaction::OutPoint;
17 use lightning::ln::channelmonitor;
18 use lightning::ln::channelmanager::ChannelManager;
19 use lightning::ln::peer_handler::{MessageHandler,PeerManager,SocketDescriptor};
20 use lightning::ln::router::Router;
21 use lightning::util::events::{EventsProvider,Event};
22 use lightning::util::reset_rng_state;
23 use lightning::util::logger::Logger;
24 use lightning::util::sha2::Sha256;
25
26 mod utils;
27
28 use utils::test_logger;
29
30 use secp256k1::key::{PublicKey,SecretKey};
31 use secp256k1::Secp256k1;
32
33 use std::cell::RefCell;
34 use std::collections::HashMap;
35 use std::cmp;
36 use std::hash::Hash;
37 use std::sync::Arc;
38 use std::sync::atomic::{AtomicUsize,Ordering};
39
40 #[inline]
41 pub fn slice_to_be16(v: &[u8]) -> u16 {
42         ((v[0] as u16) << 8*1) |
43         ((v[1] as u16) << 8*0)
44 }
45
46 #[inline]
47 pub fn slice_to_be24(v: &[u8]) -> u32 {
48         ((v[0] as u32) << 8*2) |
49         ((v[1] as u32) << 8*1) |
50         ((v[2] as u32) << 8*0)
51 }
52
53 #[inline]
54 pub fn slice_to_be32(v: &[u8]) -> u32 {
55         ((v[0] as u32) << 8*3) |
56         ((v[1] as u32) << 8*2) |
57         ((v[2] as u32) << 8*1) |
58         ((v[3] as u32) << 8*0)
59 }
60
61 #[inline]
62 pub fn be64_to_array(u: u64) -> [u8; 8] {
63         let mut v = [0; 8];
64         v[0] = ((u >> 8*7) & 0xff) as u8;
65         v[1] = ((u >> 8*6) & 0xff) as u8;
66         v[2] = ((u >> 8*5) & 0xff) as u8;
67         v[3] = ((u >> 8*4) & 0xff) as u8;
68         v[4] = ((u >> 8*3) & 0xff) as u8;
69         v[5] = ((u >> 8*2) & 0xff) as u8;
70         v[6] = ((u >> 8*1) & 0xff) as u8;
71         v[7] = ((u >> 8*0) & 0xff) as u8;
72         v
73 }
74
75 struct InputData {
76         data: Vec<u8>,
77         read_pos: AtomicUsize,
78 }
79 impl InputData {
80         fn get_slice(&self, len: usize) -> Option<&[u8]> {
81                 let old_pos = self.read_pos.fetch_add(len, Ordering::AcqRel);
82                 if self.data.len() < old_pos + len {
83                         return None;
84                 }
85                 Some(&self.data[old_pos..old_pos + len])
86         }
87 }
88
89 struct FuzzEstimator {
90         input: Arc<InputData>,
91 }
92 impl FeeEstimator for FuzzEstimator {
93         fn get_est_sat_per_1000_weight(&self, _: ConfirmationTarget) -> u64 {
94                 //TODO: We should actually be testing at least much more than 64k...
95                 match self.input.get_slice(2) {
96                         Some(slice) => cmp::max(slice_to_be16(slice) as u64, 253),
97                         None => 0
98                 }
99         }
100 }
101
102 struct TestBroadcaster {}
103 impl BroadcasterInterface for TestBroadcaster {
104         fn broadcast_transaction(&self, _tx: &Transaction) {}
105 }
106
107 #[derive(Clone)]
108 struct Peer<'a> {
109         id: u8,
110         peers_connected: &'a RefCell<[bool; 256]>,
111 }
112 impl<'a> SocketDescriptor for Peer<'a> {
113         fn send_data(&mut self, data: &Vec<u8>, write_offset: usize, _resume_read: bool) -> usize {
114                 assert!(write_offset < data.len());
115                 data.len() - write_offset
116         }
117         fn disconnect_socket(&mut self) {
118                 assert!(self.peers_connected.borrow()[self.id as usize]);
119                 self.peers_connected.borrow_mut()[self.id as usize] = false;
120         }
121 }
122 impl<'a> PartialEq for Peer<'a> {
123         fn eq(&self, other: &Self) -> bool {
124                 self.id == other.id
125         }
126 }
127 impl<'a> Eq for Peer<'a> {}
128 impl<'a> Hash for Peer<'a> {
129         fn hash<H : std::hash::Hasher>(&self, h: &mut H) {
130                 self.id.hash(h)
131         }
132 }
133
134 struct MoneyLossDetector<'a> {
135         manager: Arc<ChannelManager>,
136         monitor: Arc<channelmonitor::SimpleManyChannelMonitor<OutPoint>>,
137         handler: PeerManager<Peer<'a>>,
138
139         peers: &'a RefCell<[bool; 256]>,
140         funding_txn: Vec<Transaction>,
141         header_hashes: Vec<Sha256dHash>,
142         height: usize,
143         max_height: usize,
144
145 }
146 impl<'a> MoneyLossDetector<'a> {
147         pub fn new(peers: &'a RefCell<[bool; 256]>, manager: Arc<ChannelManager>, monitor: Arc<channelmonitor::SimpleManyChannelMonitor<OutPoint>>, handler: PeerManager<Peer<'a>>) -> Self {
148                 MoneyLossDetector {
149                         manager,
150                         monitor,
151                         handler,
152
153                         peers,
154                         funding_txn: Vec::new(),
155                         header_hashes: vec![Default::default()],
156                         height: 0,
157                         max_height: 0,
158                 }
159         }
160
161         fn connect_block(&mut self, txn: &[&Transaction], txn_idxs: &[u32]) {
162                 let header = BlockHeader { version: 0x20000000, prev_blockhash: self.header_hashes[self.height], merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
163                 self.height += 1;
164                 self.manager.block_connected(&header, self.height as u32, txn, txn_idxs);
165                 (*self.monitor).block_connected(&header, self.height as u32, txn, txn_idxs);
166                 if self.header_hashes.len() > self.height {
167                         self.header_hashes[self.height] = header.bitcoin_hash();
168                 } else {
169                         assert_eq!(self.header_hashes.len(), self.height);
170                         self.header_hashes.push(header.bitcoin_hash());
171                 }
172                 self.max_height = cmp::max(self.height, self.max_height);
173         }
174
175         fn disconnect_block(&mut self) {
176                 if self.height > 0 && (self.max_height < 6 || self.height >= self.max_height - 6) {
177                         self.height -= 1;
178                         let header = BlockHeader { version: 0x20000000, prev_blockhash: self.header_hashes[self.height], merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
179                         self.manager.block_disconnected(&header);
180                         self.monitor.block_disconnected(&header);
181                 }
182         }
183 }
184
185 impl<'a> Drop for MoneyLossDetector<'a> {
186         fn drop(&mut self) {
187                 // Disconnect all peers
188                 for (idx, peer) in self.peers.borrow().iter().enumerate() {
189                         if *peer {
190                                 self.handler.disconnect_event(&Peer{id: idx as u8, peers_connected: &self.peers});
191                         }
192                 }
193
194                 // Force all channels onto the chain (and time out claim txn)
195                 self.manager.force_close_all_channels();
196         }
197 }
198
199 #[inline]
200 pub fn do_test(data: &[u8]) {
201         reset_rng_state();
202
203         let input = Arc::new(InputData {
204                 data: data.to_vec(),
205                 read_pos: AtomicUsize::new(0),
206         });
207         let fee_est = Arc::new(FuzzEstimator {
208                 input: input.clone(),
209         });
210
211         macro_rules! get_slice {
212                 ($len: expr) => {
213                         match input.get_slice($len as usize) {
214                                 Some(slice) => slice,
215                                 None => return,
216                         }
217                 }
218         }
219
220         let secp_ctx = Secp256k1::new();
221         macro_rules! get_pubkey {
222                 () => {
223                         match PublicKey::from_slice(&secp_ctx, get_slice!(33)) {
224                                 Ok(key) => key,
225                                 Err(_) => return,
226                         }
227                 }
228         }
229
230         let our_network_key = match SecretKey::from_slice(&secp_ctx, get_slice!(32)) {
231                 Ok(key) => key,
232                 Err(_) => return,
233         };
234
235         let logger: Arc<Logger> = Arc::new(test_logger::TestLogger{});
236         let watch = Arc::new(ChainWatchInterfaceUtil::new(Arc::clone(&logger)));
237         let broadcast = Arc::new(TestBroadcaster{});
238         let monitor = channelmonitor::SimpleManyChannelMonitor::new(watch.clone(), broadcast.clone());
239
240         let channelmanager = ChannelManager::new(our_network_key, slice_to_be32(get_slice!(4)), get_slice!(1)[0] != 0, Network::Bitcoin, fee_est.clone(), monitor.clone(), watch.clone(), broadcast.clone(), Arc::clone(&logger)).unwrap();
241         let router = Arc::new(Router::new(PublicKey::from_secret_key(&secp_ctx, &our_network_key).unwrap(), Arc::clone(&logger)));
242
243         let peers = RefCell::new([false; 256]);
244         let mut loss_detector = MoneyLossDetector::new(&peers, channelmanager.clone(), monitor.clone(), PeerManager::new(MessageHandler {
245                 chan_handler: channelmanager.clone(),
246                 route_handler: router.clone(),
247         }, our_network_key, Arc::clone(&logger)));
248
249         let mut should_forward = false;
250         let mut payments_received: Vec<[u8; 32]> = Vec::new();
251         let mut payments_sent = 0;
252         let mut pending_funding_generation: Vec<([u8; 32], u64, Script)> = Vec::new();
253         let mut pending_funding_signatures = HashMap::new();
254         let mut pending_funding_relay = Vec::new();
255
256         loop {
257                 match get_slice!(1)[0] {
258                         0 => {
259                                 let mut new_id = 0;
260                                 for i in 1..256 {
261                                         if !peers.borrow()[i-1] {
262                                                 new_id = i;
263                                                 break;
264                                         }
265                                 }
266                                 if new_id == 0 { return; }
267                                 loss_detector.handler.new_outbound_connection(get_pubkey!(), Peer{id: (new_id - 1) as u8, peers_connected: &peers}).unwrap();
268                                 peers.borrow_mut()[new_id - 1] = true;
269                         },
270                         1 => {
271                                 let mut new_id = 0;
272                                 for i in 1..256 {
273                                         if !peers.borrow()[i-1] {
274                                                 new_id = i;
275                                                 break;
276                                         }
277                                 }
278                                 if new_id == 0 { return; }
279                                 loss_detector.handler.new_inbound_connection(Peer{id: (new_id - 1) as u8, peers_connected: &peers}).unwrap();
280                                 peers.borrow_mut()[new_id - 1] = true;
281                         },
282                         2 => {
283                                 let peer_id = get_slice!(1)[0];
284                                 if !peers.borrow()[peer_id as usize] { return; }
285                                 loss_detector.handler.disconnect_event(&Peer{id: peer_id, peers_connected: &peers});
286                                 peers.borrow_mut()[peer_id as usize] = false;
287                         },
288                         3 => {
289                                 let peer_id = get_slice!(1)[0];
290                                 if !peers.borrow()[peer_id as usize] { return; }
291                                 match loss_detector.handler.read_event(&mut Peer{id: peer_id, peers_connected: &peers}, get_slice!(get_slice!(1)[0]).to_vec()) {
292                                         Ok(res) => assert!(!res),
293                                         Err(_) => { peers.borrow_mut()[peer_id as usize] = false; }
294                                 }
295                         },
296                         4 => {
297                                 let value = slice_to_be24(get_slice!(3)) as u64;
298                                 let route = match router.get_route(&get_pubkey!(), None, &Vec::new(), value, 42) {
299                                         Ok(route) => route,
300                                         Err(_) => return,
301                                 };
302                                 let mut payment_hash = [0; 32];
303                                 payment_hash[0..8].copy_from_slice(&be64_to_array(payments_sent));
304                                 let mut sha = Sha256::new();
305                                 sha.input(&payment_hash);
306                                 sha.result(&mut payment_hash);
307                                 payments_sent += 1;
308                                 match channelmanager.send_payment(route, payment_hash) {
309                                         Ok(_) => {},
310                                         Err(_) => return,
311                                 }
312                         },
313                         5 => {
314                                 let peer_id = get_slice!(1)[0];
315                                 if !peers.borrow()[peer_id as usize] { return; }
316                                 let their_key = get_pubkey!();
317                                 let chan_value = slice_to_be24(get_slice!(3)) as u64;
318                                 //let push_msat_value = slice_to_be24(get_slice!(3)) as u64;
319                                 // Temporarily don't read extra bytes to avoid breaking existing test-cases
320                                 let push_msat_value = 0;
321                                 if channelmanager.create_channel(their_key, chan_value, push_msat_value, 0).is_err() { return; }
322                         },
323                         6 => {
324                                 let mut channels = channelmanager.list_channels();
325                                 let channel_id = get_slice!(1)[0] as usize;
326                                 if channel_id >= channels.len() { return; }
327                                 channels.sort_by(|a, b| { a.channel_id.cmp(&b.channel_id) });
328                                 if channelmanager.close_channel(&channels[channel_id].channel_id).is_err() { return; }
329                         },
330                         7 => {
331                                 if should_forward {
332                                         channelmanager.process_pending_htlc_forwards();
333                                         should_forward = false;
334                                 }
335                         },
336                         8 => {
337                                 for payment in payments_received.drain(..) {
338                                         // SHA256 is defined as XOR of all input bytes placed in the first byte, and 0s
339                                         // for the remaining bytes. Thus, if not all remaining bytes are 0s we cannot
340                                         // fulfill this HTLC, but if they are, we can just take the first byte and
341                                         // place that anywhere in our preimage.
342                                         if &payment[1..] != &[0; 31] {
343                                                 channelmanager.fail_htlc_backwards(&payment);
344                                         } else {
345                                                 let mut payment_preimage = [0; 32];
346                                                 payment_preimage[0] = payment[0];
347                                                 channelmanager.claim_funds(payment_preimage);
348                                         }
349                                 }
350                         },
351                         9 => {
352                                 for payment in payments_received.drain(..) {
353                                         channelmanager.fail_htlc_backwards(&payment);
354                                 }
355                         },
356                         10 => {
357                                 for funding_generation in pending_funding_generation.drain(..) {
358                                         let mut tx = Transaction { version: 0, lock_time: 0, input: Vec::new(), output: vec![TxOut {
359                                                         value: funding_generation.1, script_pubkey: funding_generation.2,
360                                                 }] };
361                                         let funding_output = OutPoint::new(Sha256dHash::from_data(&serialize(&tx).unwrap()[..]), 0);
362                                         let mut found_duplicate_txo = false;
363                                         for chan in channelmanager.list_channels() {
364                                                 if chan.channel_id == funding_output.to_channel_id() {
365                                                         found_duplicate_txo = true;
366                                                 }
367                                         }
368                                         if !found_duplicate_txo {
369                                                 channelmanager.funding_transaction_generated(&funding_generation.0, funding_output.clone());
370                                                 pending_funding_signatures.insert(funding_output, tx);
371                                         }
372                                 }
373                         },
374                         11 => {
375                                 if !pending_funding_relay.is_empty() {
376                                         let mut txn = Vec::with_capacity(pending_funding_relay.len());
377                                         let mut txn_idxs = Vec::with_capacity(pending_funding_relay.len());
378                                         for (idx, tx) in pending_funding_relay.iter().enumerate() {
379                                                 txn.push(tx);
380                                                 txn_idxs.push(idx as u32 + 1);
381                                         }
382
383                                         loss_detector.connect_block(&txn[..], &txn_idxs[..]);
384                                         txn_idxs.clear();
385                                         for _ in 2..100 {
386                                                 loss_detector.connect_block(&txn[..], &txn_idxs[..]);
387                                         }
388                                 }
389                                 for tx in pending_funding_relay.drain(..) {
390                                         loss_detector.funding_txn.push(tx);
391                                 }
392                         },
393                         12 => {
394                                 let txlen = slice_to_be16(get_slice!(2));
395                                 if txlen == 0 {
396                                         loss_detector.connect_block(&[], &[]);
397                                 } else {
398                                         let txres: Result<Transaction, _> = deserialize(get_slice!(txlen));
399                                         if let Ok(tx) = txres {
400                                                 loss_detector.connect_block(&[&tx], &[1]);
401                                         } else {
402                                                 return;
403                                         }
404                                 }
405                         },
406                         13 => {
407                                 loss_detector.disconnect_block();
408                         },
409                         _ => return,
410                 }
411                 loss_detector.handler.process_events();
412                 for event in loss_detector.handler.get_and_clear_pending_events() {
413                         match event {
414                                 Event::FundingGenerationReady { temporary_channel_id, channel_value_satoshis, output_script, .. } => {
415                                         pending_funding_generation.push((temporary_channel_id, channel_value_satoshis, output_script));
416                                 },
417                                 Event::FundingBroadcastSafe { funding_txo, .. } => {
418                                         pending_funding_relay.push(pending_funding_signatures.remove(&funding_txo).unwrap());
419                                 },
420                                 Event::PaymentReceived { payment_hash, .. } => {
421                                         payments_received.push(payment_hash);
422                                 },
423                                 Event::PaymentSent {..} => {},
424                                 Event::PaymentFailed {..} => {},
425
426                                 Event::PendingHTLCsForwardable {..} => {
427                                         should_forward = true;
428                                 },
429                                 _ => panic!("Unknown event"),
430                         }
431                 }
432         }
433 }
434
435 #[cfg(feature = "afl")]
436 #[macro_use] extern crate afl;
437 #[cfg(feature = "afl")]
438 fn main() {
439         fuzz!(|data| {
440                 do_test(data);
441         });
442 }
443
444 #[cfg(feature = "honggfuzz")]
445 #[macro_use] extern crate honggfuzz;
446 #[cfg(feature = "honggfuzz")]
447 fn main() {
448         loop {
449                 fuzz!(|data| {
450                         do_test(data);
451                 });
452         }
453 }
454
455 extern crate hex;
456 #[cfg(test)]
457 mod tests {
458         #[test]
459         fn duplicate_crash() {
460                 super::do_test(&::hex::decode("00").unwrap());
461         }
462 }