Randomize initial onion packet data.
[rust-lightning] / fuzz / fuzz_targets / chanmon_fail_consistency.rs
1 //! Test that monitor update failures don't get our channel state out of sync.
2 //! One of the biggest concern with the monitor update failure handling code is that messages
3 //! resent after monitor updating is restored are delivered out-of-order, resulting in
4 //! commitment_signed messages having "invalid signatures".
5 //! To test this we stand up a network of three nodes and read bytes from the fuzz input to denote
6 //! actions such as sending payments, handling events, or changing monitor update return values on
7 //! a per-node basis. This should allow it to find any cases where the ordering of actions results
8 //! in us getting out of sync with ourselves, and, assuming at least one of our recieve- or
9 //! send-side handling is correct, other peers. We consider it a failure if any action results in a
10 //! channel being force-closed.
11
12 //Uncomment this for libfuzzer builds:
13 //#![no_main]
14
15 extern crate bitcoin;
16 extern crate bitcoin_hashes;
17 extern crate lightning;
18 extern crate secp256k1;
19
20 use bitcoin::BitcoinHash;
21 use bitcoin::blockdata::block::BlockHeader;
22 use bitcoin::blockdata::transaction::{Transaction, TxOut};
23 use bitcoin::blockdata::script::{Builder, Script};
24 use bitcoin::blockdata::opcodes;
25 use bitcoin::network::constants::Network;
26
27 use bitcoin_hashes::Hash as TraitImport;
28 use bitcoin_hashes::hash160::Hash as Hash160;
29 use bitcoin_hashes::sha256::Hash as Sha256;
30 use bitcoin_hashes::sha256d::Hash as Sha256d;
31
32 use lightning::chain::chaininterface;
33 use lightning::chain::transaction::OutPoint;
34 use lightning::chain::chaininterface::{BroadcasterInterface,ConfirmationTarget,ChainListener,FeeEstimator,ChainWatchInterfaceUtil};
35 use lightning::chain::keysinterface::{ChannelKeys, KeysInterface};
36 use lightning::ln::channelmonitor;
37 use lightning::ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, HTLCUpdate};
38 use lightning::ln::channelmanager::{ChannelManager, PaymentHash, PaymentPreimage, ChannelManagerReadArgs};
39 use lightning::ln::router::{Route, RouteHop};
40 use lightning::ln::msgs::{CommitmentUpdate, ChannelMessageHandler, ErrorAction, LightningError, UpdateAddHTLC, LocalFeatures};
41 use lightning::util::events;
42 use lightning::util::logger::Logger;
43 use lightning::util::config::UserConfig;
44 use lightning::util::events::{EventsProvider, MessageSendEventsProvider};
45 use lightning::util::ser::{Readable, ReadableArgs, Writeable, Writer};
46
47 mod utils;
48 use utils::test_logger;
49
50 use secp256k1::key::{PublicKey,SecretKey};
51 use secp256k1::Secp256k1;
52
53 use std::mem;
54 use std::cmp::Ordering;
55 use std::collections::{HashSet, hash_map, HashMap};
56 use std::sync::{Arc,Mutex};
57 use std::sync::atomic;
58 use std::io::Cursor;
59
60 struct FuzzEstimator {}
61 impl FeeEstimator for FuzzEstimator {
62         fn get_est_sat_per_1000_weight(&self, _: ConfirmationTarget) -> u64 {
63                 253
64         }
65 }
66
67 pub struct TestBroadcaster {}
68 impl BroadcasterInterface for TestBroadcaster {
69         fn broadcast_transaction(&self, _tx: &Transaction) { }
70 }
71
72 pub struct VecWriter(pub Vec<u8>);
73 impl Writer for VecWriter {
74         fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
75                 self.0.extend_from_slice(buf);
76                 Ok(())
77         }
78         fn size_hint(&mut self, size: usize) {
79                 self.0.reserve_exact(size);
80         }
81 }
82
83 static mut IN_RESTORE: bool = false;
84 pub struct TestChannelMonitor {
85         pub simple_monitor: Arc<channelmonitor::SimpleManyChannelMonitor<OutPoint>>,
86         pub update_ret: Mutex<Result<(), channelmonitor::ChannelMonitorUpdateErr>>,
87         pub latest_good_update: Mutex<HashMap<OutPoint, Vec<u8>>>,
88         pub latest_update_good: Mutex<HashMap<OutPoint, bool>>,
89         pub latest_updates_good_at_last_ser: Mutex<HashMap<OutPoint, bool>>,
90         pub should_update_manager: atomic::AtomicBool,
91 }
92 impl TestChannelMonitor {
93         pub fn new(chain_monitor: Arc<dyn chaininterface::ChainWatchInterface>, broadcaster: Arc<dyn chaininterface::BroadcasterInterface>, logger: Arc<dyn Logger>, feeest: Arc<dyn chaininterface::FeeEstimator>) -> Self {
94                 Self {
95                         simple_monitor: channelmonitor::SimpleManyChannelMonitor::new(chain_monitor, broadcaster, logger, feeest),
96                         update_ret: Mutex::new(Ok(())),
97                         latest_good_update: Mutex::new(HashMap::new()),
98                         latest_update_good: Mutex::new(HashMap::new()),
99                         latest_updates_good_at_last_ser: Mutex::new(HashMap::new()),
100                         should_update_manager: atomic::AtomicBool::new(false),
101                 }
102         }
103 }
104 impl channelmonitor::ManyChannelMonitor for TestChannelMonitor {
105         fn add_update_monitor(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
106                 let ret = self.update_ret.lock().unwrap().clone();
107                 if let Ok(()) = ret {
108                         let mut ser = VecWriter(Vec::new());
109                         monitor.write_for_disk(&mut ser).unwrap();
110                         self.latest_good_update.lock().unwrap().insert(funding_txo, ser.0);
111                         match self.latest_update_good.lock().unwrap().entry(funding_txo) {
112                                 hash_map::Entry::Vacant(e) => { e.insert(true); },
113                                 hash_map::Entry::Occupied(mut e) => {
114                                         if !e.get() && unsafe { IN_RESTORE } {
115                                                 // Technically we can't consider an update to be "good" unless we're doing
116                                                 // it in response to a test_restore_channel_monitor as the channel may
117                                                 // still be waiting on such a call, so only set us to good if we're in the
118                                                 // middle of a restore call.
119                                                 e.insert(true);
120                                         }
121                                 },
122                         }
123                         self.should_update_manager.store(true, atomic::Ordering::Relaxed);
124                 } else {
125                         self.latest_update_good.lock().unwrap().insert(funding_txo, false);
126                 }
127                 assert!(self.simple_monitor.add_update_monitor(funding_txo, monitor).is_ok());
128                 ret
129         }
130
131         fn fetch_pending_htlc_updated(&self) -> Vec<HTLCUpdate> {
132                 return self.simple_monitor.fetch_pending_htlc_updated();
133         }
134 }
135
136 struct KeyProvider {
137         node_id: u8,
138         session_id: atomic::AtomicU8,
139         channel_id: atomic::AtomicU8,
140 }
141 impl KeysInterface for KeyProvider {
142         fn get_node_secret(&self) -> SecretKey {
143                 SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, self.node_id]).unwrap()
144         }
145
146         fn get_destination_script(&self) -> Script {
147                 let secp_ctx = Secp256k1::signing_only();
148                 let channel_monitor_claim_key = SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, self.node_id]).unwrap();
149                 let our_channel_monitor_claim_key_hash = Hash160::hash(&PublicKey::from_secret_key(&secp_ctx, &channel_monitor_claim_key).serialize());
150                 Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&our_channel_monitor_claim_key_hash[..]).into_script()
151         }
152
153         fn get_shutdown_pubkey(&self) -> PublicKey {
154                 let secp_ctx = Secp256k1::signing_only();
155                 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, self.node_id]).unwrap())
156         }
157
158         fn get_channel_keys(&self, _inbound: bool) -> ChannelKeys {
159                 ChannelKeys {
160                         funding_key:               SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, self.node_id]).unwrap(),
161                         revocation_base_key:       SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, self.node_id]).unwrap(),
162                         payment_base_key:          SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, self.node_id]).unwrap(),
163                         delayed_payment_base_key:  SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, self.node_id]).unwrap(),
164                         htlc_base_key:             SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, self.node_id]).unwrap(),
165                         commitment_seed: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, self.node_id],
166                 }
167         }
168
169         fn get_onion_rand(&self) -> (SecretKey, [u8; 32]) {
170                 let id = self.session_id.fetch_add(1, atomic::Ordering::Relaxed);
171                 (SecretKey::from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, id, 10, self.node_id]).unwrap(),
172                 [0; 32])
173         }
174
175         fn get_channel_id(&self) -> [u8; 32] {
176                 let id = self.channel_id.fetch_add(1, atomic::Ordering::Relaxed);
177                 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, id, 11, self.node_id]
178         }
179 }
180
181 #[inline]
182 pub fn do_test(data: &[u8]) {
183         let fee_est = Arc::new(FuzzEstimator{});
184         let broadcast = Arc::new(TestBroadcaster{});
185
186         macro_rules! make_node {
187                 ($node_id: expr) => { {
188                         let logger: Arc<dyn Logger> = Arc::new(test_logger::TestLogger::new($node_id.to_string()));
189                         let watch = Arc::new(ChainWatchInterfaceUtil::new(Network::Bitcoin, Arc::clone(&logger)));
190                         let monitor = Arc::new(TestChannelMonitor::new(watch.clone(), broadcast.clone(), logger.clone(), fee_est.clone()));
191
192                         let keys_manager = Arc::new(KeyProvider { node_id: $node_id, session_id: atomic::AtomicU8::new(0), channel_id: atomic::AtomicU8::new(0) });
193                         let mut config = UserConfig::new();
194                         config.channel_options.fee_proportional_millionths = 0;
195                         config.channel_options.announced_channel = true;
196                         config.peer_channel_config_limits.min_dust_limit_satoshis = 0;
197                         (ChannelManager::new(Network::Bitcoin, fee_est.clone(), monitor.clone(), broadcast.clone(), Arc::clone(&logger), keys_manager.clone(), config, 0).unwrap(),
198                         monitor)
199                 } }
200         }
201
202         macro_rules! reload_node {
203                 ($ser: expr, $node_id: expr, $old_monitors: expr) => { {
204                         let logger: Arc<dyn Logger> = Arc::new(test_logger::TestLogger::new($node_id.to_string()));
205                         let watch = Arc::new(ChainWatchInterfaceUtil::new(Network::Bitcoin, Arc::clone(&logger)));
206                         let monitor = Arc::new(TestChannelMonitor::new(watch.clone(), broadcast.clone(), logger.clone(), fee_est.clone()));
207
208                         let keys_manager = Arc::new(KeyProvider { node_id: $node_id, session_id: atomic::AtomicU8::new(0), channel_id: atomic::AtomicU8::new(0) });
209                         let mut config = UserConfig::new();
210                         config.channel_options.fee_proportional_millionths = 0;
211                         config.channel_options.announced_channel = true;
212                         config.peer_channel_config_limits.min_dust_limit_satoshis = 0;
213
214                         let mut monitors = HashMap::new();
215                         let mut old_monitors = $old_monitors.latest_good_update.lock().unwrap();
216                         for (outpoint, monitor_ser) in old_monitors.drain() {
217                                 monitors.insert(outpoint, <(Sha256d, ChannelMonitor)>::read(&mut Cursor::new(&monitor_ser), Arc::clone(&logger)).expect("Failed to read monitor").1);
218                                 monitor.latest_good_update.lock().unwrap().insert(outpoint, monitor_ser);
219                         }
220                         let mut monitor_refs = HashMap::new();
221                         for (outpoint, monitor) in monitors.iter() {
222                                 monitor_refs.insert(*outpoint, monitor);
223                         }
224
225                         let read_args = ChannelManagerReadArgs {
226                                 keys_manager,
227                                 fee_estimator: fee_est.clone(),
228                                 monitor: monitor.clone(),
229                                 tx_broadcaster: broadcast.clone(),
230                                 logger,
231                                 default_config: config,
232                                 channel_monitors: &monitor_refs,
233                         };
234
235                         let res = (<(Sha256d, ChannelManager)>::read(&mut Cursor::new(&$ser.0), read_args).expect("Failed to read manager").1, monitor);
236                         for (_, was_good) in $old_monitors.latest_updates_good_at_last_ser.lock().unwrap().iter() {
237                                 if !was_good {
238                                         // If the last time we updated a monitor we didn't successfully update (and we
239                                         // have sense updated our serialized copy of the ChannelManager) we may
240                                         // force-close the channel on our counterparty cause we know we're missing
241                                         // something. Thus, we just return here since we can't continue to test.
242                                         return;
243                                 }
244                         }
245                         res
246                 } }
247         }
248
249         let mut channel_txn = Vec::new();
250         macro_rules! make_channel {
251                 ($source: expr, $dest: expr, $chan_id: expr) => { {
252                         $source.create_channel($dest.get_our_node_id(), 10000000, 42, 0).unwrap();
253                         let open_channel = {
254                                 let events = $source.get_and_clear_pending_msg_events();
255                                 assert_eq!(events.len(), 1);
256                                 if let events::MessageSendEvent::SendOpenChannel { ref msg, .. } = events[0] {
257                                         msg.clone()
258                                 } else { panic!("Wrong event type"); }
259                         };
260
261                         $dest.handle_open_channel(&$source.get_our_node_id(), LocalFeatures::new(), &open_channel).unwrap();
262                         let accept_channel = {
263                                 let events = $dest.get_and_clear_pending_msg_events();
264                                 assert_eq!(events.len(), 1);
265                                 if let events::MessageSendEvent::SendAcceptChannel { ref msg, .. } = events[0] {
266                                         msg.clone()
267                                 } else { panic!("Wrong event type"); }
268                         };
269
270                         $source.handle_accept_channel(&$dest.get_our_node_id(), LocalFeatures::new(), &accept_channel).unwrap();
271                         {
272                                 let events = $source.get_and_clear_pending_events();
273                                 assert_eq!(events.len(), 1);
274                                 if let events::Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, .. } = events[0] {
275                                         let tx = Transaction { version: $chan_id, lock_time: 0, input: Vec::new(), output: vec![TxOut {
276                                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
277                                         }]};
278                                         let funding_output = OutPoint::new(tx.txid(), 0);
279                                         $source.funding_transaction_generated(&temporary_channel_id, funding_output);
280                                         channel_txn.push(tx);
281                                 } else { panic!("Wrong event type"); }
282                         }
283
284                         let funding_created = {
285                                 let events = $source.get_and_clear_pending_msg_events();
286                                 assert_eq!(events.len(), 1);
287                                 if let events::MessageSendEvent::SendFundingCreated { ref msg, .. } = events[0] {
288                                         msg.clone()
289                                 } else { panic!("Wrong event type"); }
290                         };
291                         $dest.handle_funding_created(&$source.get_our_node_id(), &funding_created).unwrap();
292
293                         let funding_signed = {
294                                 let events = $dest.get_and_clear_pending_msg_events();
295                                 assert_eq!(events.len(), 1);
296                                 if let events::MessageSendEvent::SendFundingSigned { ref msg, .. } = events[0] {
297                                         msg.clone()
298                                 } else { panic!("Wrong event type"); }
299                         };
300                         $source.handle_funding_signed(&$dest.get_our_node_id(), &funding_signed).unwrap();
301
302                         {
303                                 let events = $source.get_and_clear_pending_events();
304                                 assert_eq!(events.len(), 1);
305                                 if let events::Event::FundingBroadcastSafe { .. } = events[0] {
306                                 } else { panic!("Wrong event type"); }
307                         }
308                 } }
309         }
310
311         macro_rules! confirm_txn {
312                 ($node: expr) => { {
313                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
314                         let mut txn = Vec::with_capacity(channel_txn.len());
315                         let mut posn = Vec::with_capacity(channel_txn.len());
316                         for i in 0..channel_txn.len() {
317                                 txn.push(&channel_txn[i]);
318                                 posn.push(i as u32 + 1);
319                         }
320                         $node.block_connected(&header, 1, &txn, &posn);
321                         for i in 2..100 {
322                                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
323                                 $node.block_connected(&header, i, &Vec::new(), &[0; 0]);
324                         }
325                 } }
326         }
327
328         macro_rules! lock_fundings {
329                 ($nodes: expr) => { {
330                         let mut node_events = Vec::new();
331                         for node in $nodes.iter() {
332                                 node_events.push(node.get_and_clear_pending_msg_events());
333                         }
334                         for (idx, node_event) in node_events.iter().enumerate() {
335                                 for event in node_event {
336                                         if let events::MessageSendEvent::SendFundingLocked { ref node_id, ref msg } = event {
337                                                 for node in $nodes.iter() {
338                                                         if node.get_our_node_id() == *node_id {
339                                                                 node.handle_funding_locked(&$nodes[idx].get_our_node_id(), msg).unwrap();
340                                                         }
341                                                 }
342                                         } else { panic!("Wrong event type"); }
343                                 }
344                         }
345
346                         for node in $nodes.iter() {
347                                 let events = node.get_and_clear_pending_msg_events();
348                                 for event in events {
349                                         if let events::MessageSendEvent::SendAnnouncementSignatures { .. } = event {
350                                         } else { panic!("Wrong event type"); }
351                                 }
352                         }
353                 } }
354         }
355
356         // 3 nodes is enough to hit all the possible cases, notably unknown-source-unknown-dest
357         // forwarding.
358         let (mut node_a, mut monitor_a) = make_node!(0);
359         let (mut node_b, mut monitor_b) = make_node!(1);
360         let (mut node_c, mut monitor_c) = make_node!(2);
361
362         let mut nodes = [node_a, node_b, node_c];
363
364         make_channel!(nodes[0], nodes[1], 0);
365         make_channel!(nodes[1], nodes[2], 1);
366
367         for node in nodes.iter() {
368                 confirm_txn!(node);
369         }
370
371         lock_fundings!(nodes);
372
373         let chan_a = nodes[0].list_usable_channels()[0].short_channel_id.unwrap();
374         let chan_b = nodes[2].list_usable_channels()[0].short_channel_id.unwrap();
375
376         let mut payment_id = 0;
377
378         let mut chan_a_disconnected = false;
379         let mut chan_b_disconnected = false;
380         let mut ba_events = Vec::new();
381         let mut bc_events = Vec::new();
382
383         let mut node_a_ser = VecWriter(Vec::new());
384         nodes[0].write(&mut node_a_ser).unwrap();
385         let mut node_b_ser = VecWriter(Vec::new());
386         nodes[1].write(&mut node_b_ser).unwrap();
387         let mut node_c_ser = VecWriter(Vec::new());
388         nodes[2].write(&mut node_c_ser).unwrap();
389
390         macro_rules! test_err {
391                 ($res: expr) => {
392                         match $res {
393                                 Ok(()) => {},
394                                 Err(LightningError { action: ErrorAction::IgnoreError, .. }) => { },
395                                 _ => { $res.unwrap() },
396                         }
397                 }
398         }
399
400         macro_rules! test_return {
401                 () => { {
402                         assert_eq!(nodes[0].list_channels().len(), 1);
403                         assert_eq!(nodes[1].list_channels().len(), 2);
404                         assert_eq!(nodes[2].list_channels().len(), 1);
405                         return;
406                 } }
407         }
408
409         let mut read_pos = 0;
410         macro_rules! get_slice {
411                 ($len: expr) => {
412                         {
413                                 let slice_len = $len as usize;
414                                 if data.len() < read_pos + slice_len {
415                                         test_return!();
416                                 }
417                                 read_pos += slice_len;
418                                 &data[read_pos - slice_len..read_pos]
419                         }
420                 }
421         }
422
423         loop {
424                 macro_rules! send_payment {
425                         ($source: expr, $dest: expr) => { {
426                                 let payment_hash = Sha256::hash(&[payment_id; 1]);
427                                 payment_id = payment_id.wrapping_add(1);
428                                 if let Err(_) = $source.send_payment(Route {
429                                         hops: vec![RouteHop {
430                                                 pubkey: $dest.0.get_our_node_id(),
431                                                 short_channel_id: $dest.1,
432                                                 fee_msat: 5000000,
433                                                 cltv_expiry_delta: 200,
434                                         }],
435                                 }, PaymentHash(payment_hash.into_inner())) {
436                                         // Probably ran out of funds
437                                         test_return!();
438                                 }
439                         } };
440                         ($source: expr, $middle: expr, $dest: expr) => { {
441                                 let payment_hash = Sha256::hash(&[payment_id; 1]);
442                                 payment_id = payment_id.wrapping_add(1);
443                                 if let Err(_) = $source.send_payment(Route {
444                                         hops: vec![RouteHop {
445                                                 pubkey: $middle.0.get_our_node_id(),
446                                                 short_channel_id: $middle.1,
447                                                 fee_msat: 50000,
448                                                 cltv_expiry_delta: 100,
449                                         },RouteHop {
450                                                 pubkey: $dest.0.get_our_node_id(),
451                                                 short_channel_id: $dest.1,
452                                                 fee_msat: 5000000,
453                                                 cltv_expiry_delta: 200,
454                                         }],
455                                 }, PaymentHash(payment_hash.into_inner())) {
456                                         // Probably ran out of funds
457                                         test_return!();
458                                 }
459                         } }
460                 }
461
462                 macro_rules! process_msg_events {
463                         ($node: expr, $corrupt_forward: expr) => { {
464                                 let events = if $node == 1 {
465                                         let mut new_events = Vec::new();
466                                         mem::swap(&mut new_events, &mut ba_events);
467                                         new_events.extend_from_slice(&bc_events[..]);
468                                         bc_events.clear();
469                                         new_events
470                                 } else { Vec::new() };
471                                 for event in events.iter().chain(nodes[$node].get_and_clear_pending_msg_events().iter()) {
472                                         match event {
473                                                 events::MessageSendEvent::UpdateHTLCs { ref node_id, updates: CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
474                                                         for dest in nodes.iter() {
475                                                                 if dest.get_our_node_id() == *node_id {
476                                                                         assert!(update_fee.is_none());
477                                                                         for update_add in update_add_htlcs {
478                                                                                 if !$corrupt_forward {
479                                                                                         test_err!(dest.handle_update_add_htlc(&nodes[$node].get_our_node_id(), &update_add));
480                                                                                 } else {
481                                                                                         // Corrupt the update_add_htlc message so that its HMAC
482                                                                                         // check will fail and we generate a
483                                                                                         // update_fail_malformed_htlc instead of an
484                                                                                         // update_fail_htlc as we do when we reject a payment.
485                                                                                         let mut msg_ser = update_add.encode();
486                                                                                         msg_ser[1000] ^= 0xff;
487                                                                                         let new_msg = UpdateAddHTLC::read(&mut Cursor::new(&msg_ser)).unwrap();
488                                                                                         test_err!(dest.handle_update_add_htlc(&nodes[$node].get_our_node_id(), &new_msg));
489                                                                                 }
490                                                                         }
491                                                                         for update_fulfill in update_fulfill_htlcs {
492                                                                                 test_err!(dest.handle_update_fulfill_htlc(&nodes[$node].get_our_node_id(), &update_fulfill));
493                                                                         }
494                                                                         for update_fail in update_fail_htlcs {
495                                                                                 test_err!(dest.handle_update_fail_htlc(&nodes[$node].get_our_node_id(), &update_fail));
496                                                                         }
497                                                                         for update_fail_malformed in update_fail_malformed_htlcs {
498                                                                                 test_err!(dest.handle_update_fail_malformed_htlc(&nodes[$node].get_our_node_id(), &update_fail_malformed));
499                                                                         }
500                                                                         test_err!(dest.handle_commitment_signed(&nodes[$node].get_our_node_id(), &commitment_signed));
501                                                                 }
502                                                         }
503                                                 },
504                                                 events::MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
505                                                         for dest in nodes.iter() {
506                                                                 if dest.get_our_node_id() == *node_id {
507                                                                         test_err!(dest.handle_revoke_and_ack(&nodes[$node].get_our_node_id(), msg));
508                                                                 }
509                                                         }
510                                                 },
511                                                 events::MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => {
512                                                         for dest in nodes.iter() {
513                                                                 if dest.get_our_node_id() == *node_id {
514                                                                         test_err!(dest.handle_channel_reestablish(&nodes[$node].get_our_node_id(), msg));
515                                                                 }
516                                                         }
517                                                 },
518                                                 events::MessageSendEvent::SendFundingLocked { .. } => {
519                                                         // Can be generated as a reestablish response
520                                                 },
521                                                 events::MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {
522                                                         // Can be generated due to a payment forward being rejected due to a
523                                                         // channel having previously failed a monitor update
524                                                 },
525                                                 _ => panic!("Unhandled message event"),
526                                         }
527                                 }
528                         } }
529                 }
530
531                 macro_rules! drain_msg_events_on_disconnect {
532                         ($counterparty_id: expr) => { {
533                                 if $counterparty_id == 0 {
534                                         for event in nodes[0].get_and_clear_pending_msg_events() {
535                                                 match event {
536                                                         events::MessageSendEvent::UpdateHTLCs { .. } => {},
537                                                         events::MessageSendEvent::SendRevokeAndACK { .. } => {},
538                                                         events::MessageSendEvent::SendChannelReestablish { .. } => {},
539                                                         events::MessageSendEvent::SendFundingLocked { .. } => {},
540                                                         events::MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
541                                                         _ => panic!("Unhandled message event"),
542                                                 }
543                                         }
544                                         ba_events.clear();
545                                 } else {
546                                         for event in nodes[2].get_and_clear_pending_msg_events() {
547                                                 match event {
548                                                         events::MessageSendEvent::UpdateHTLCs { .. } => {},
549                                                         events::MessageSendEvent::SendRevokeAndACK { .. } => {},
550                                                         events::MessageSendEvent::SendChannelReestablish { .. } => {},
551                                                         events::MessageSendEvent::SendFundingLocked { .. } => {},
552                                                         events::MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
553                                                         _ => panic!("Unhandled message event"),
554                                                 }
555                                         }
556                                         bc_events.clear();
557                                 }
558                                 let mut events = nodes[1].get_and_clear_pending_msg_events();
559                                 let drop_node_id = if $counterparty_id == 0 { nodes[0].get_our_node_id() } else { nodes[2].get_our_node_id() };
560                                 let msg_sink = if $counterparty_id == 0 { &mut bc_events } else { &mut ba_events };
561                                 for event in events.drain(..) {
562                                         let push = match event {
563                                                 events::MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
564                                                         if *node_id != drop_node_id { true } else { false }
565                                                 },
566                                                 events::MessageSendEvent::SendRevokeAndACK { ref node_id, .. } => {
567                                                         if *node_id != drop_node_id { true } else { false }
568                                                 },
569                                                 events::MessageSendEvent::SendChannelReestablish { ref node_id, .. } => {
570                                                         if *node_id != drop_node_id { true } else { false }
571                                                 },
572                                                 events::MessageSendEvent::SendFundingLocked { .. } => false,
573                                                 events::MessageSendEvent::PaymentFailureNetworkUpdate { .. } => false,
574                                                 _ => panic!("Unhandled message event"),
575                                         };
576                                         if push { msg_sink.push(event); }
577                                 }
578                         } }
579                 }
580
581                 macro_rules! process_events {
582                         ($node: expr, $fail: expr) => { {
583                                 // In case we get 256 payments we may have a hash collision, resulting in the
584                                 // second claim/fail call not finding the duplicate-hash HTLC, so we have to
585                                 // deduplicate the calls here.
586                                 let mut claim_set = HashSet::new();
587                                 let mut events = nodes[$node].get_and_clear_pending_events();
588                                 // Sort events so that PendingHTLCsForwardable get processed last. This avoids a
589                                 // case where we first process a PendingHTLCsForwardable, then claim/fail on a
590                                 // PaymentReceived, claiming/failing two HTLCs, but leaving a just-generated
591                                 // PaymentReceived event for the second HTLC in our pending_events (and breaking
592                                 // our claim_set deduplication).
593                                 events.sort_by(|a, b| {
594                                         if let events::Event::PaymentReceived { .. } = a {
595                                                 if let events::Event::PendingHTLCsForwardable { .. } = b {
596                                                         Ordering::Less
597                                                 } else { Ordering::Equal }
598                                         } else if let events::Event::PendingHTLCsForwardable { .. } = a {
599                                                 if let events::Event::PaymentReceived { .. } = b {
600                                                         Ordering::Greater
601                                                 } else { Ordering::Equal }
602                                         } else { Ordering::Equal }
603                                 });
604                                 for event in events.drain(..) {
605                                         match event {
606                                                 events::Event::PaymentReceived { payment_hash, .. } => {
607                                                         if claim_set.insert(payment_hash.0) {
608                                                                 if $fail {
609                                                                         assert!(nodes[$node].fail_htlc_backwards(&payment_hash));
610                                                                 } else {
611                                                                         assert!(nodes[$node].claim_funds(PaymentPreimage(payment_hash.0), 5_000_000));
612                                                                 }
613                                                         }
614                                                 },
615                                                 events::Event::PaymentSent { .. } => {},
616                                                 events::Event::PaymentFailed { .. } => {},
617                                                 events::Event::PendingHTLCsForwardable { .. } => {
618                                                         nodes[$node].process_pending_htlc_forwards();
619                                                 },
620                                                 _ => panic!("Unhandled event"),
621                                         }
622                                 }
623                         } }
624                 }
625
626                 match get_slice!(1)[0] {
627                         0x00 => *monitor_a.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure),
628                         0x01 => *monitor_b.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure),
629                         0x02 => *monitor_c.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure),
630                         0x03 => *monitor_a.update_ret.lock().unwrap() = Ok(()),
631                         0x04 => *monitor_b.update_ret.lock().unwrap() = Ok(()),
632                         0x05 => *monitor_c.update_ret.lock().unwrap() = Ok(()),
633                         0x06 => { unsafe { IN_RESTORE = true }; nodes[0].test_restore_channel_monitor(); unsafe { IN_RESTORE = false }; },
634                         0x07 => { unsafe { IN_RESTORE = true }; nodes[1].test_restore_channel_monitor(); unsafe { IN_RESTORE = false }; },
635                         0x08 => { unsafe { IN_RESTORE = true }; nodes[2].test_restore_channel_monitor(); unsafe { IN_RESTORE = false }; },
636                         0x09 => send_payment!(nodes[0], (&nodes[1], chan_a)),
637                         0x0a => send_payment!(nodes[1], (&nodes[0], chan_a)),
638                         0x0b => send_payment!(nodes[1], (&nodes[2], chan_b)),
639                         0x0c => send_payment!(nodes[2], (&nodes[1], chan_b)),
640                         0x0d => send_payment!(nodes[0], (&nodes[1], chan_a), (&nodes[2], chan_b)),
641                         0x0e => send_payment!(nodes[2], (&nodes[1], chan_b), (&nodes[0], chan_a)),
642                         0x0f => {
643                                 if !chan_a_disconnected {
644                                         nodes[0].peer_disconnected(&nodes[1].get_our_node_id(), false);
645                                         nodes[1].peer_disconnected(&nodes[0].get_our_node_id(), false);
646                                         chan_a_disconnected = true;
647                                         drain_msg_events_on_disconnect!(0);
648                                 }
649                         },
650                         0x10 => {
651                                 if !chan_b_disconnected {
652                                         nodes[1].peer_disconnected(&nodes[2].get_our_node_id(), false);
653                                         nodes[2].peer_disconnected(&nodes[1].get_our_node_id(), false);
654                                         chan_b_disconnected = true;
655                                         drain_msg_events_on_disconnect!(2);
656                                 }
657                         },
658                         0x11 => {
659                                 if chan_a_disconnected {
660                                         nodes[0].peer_connected(&nodes[1].get_our_node_id());
661                                         nodes[1].peer_connected(&nodes[0].get_our_node_id());
662                                         chan_a_disconnected = false;
663                                 }
664                         },
665                         0x12 => {
666                                 if chan_b_disconnected {
667                                         nodes[1].peer_connected(&nodes[2].get_our_node_id());
668                                         nodes[2].peer_connected(&nodes[1].get_our_node_id());
669                                         chan_b_disconnected = false;
670                                 }
671                         },
672                         0x13 => process_msg_events!(0, true),
673                         0x14 => process_msg_events!(0, false),
674                         0x15 => process_events!(0, true),
675                         0x16 => process_events!(0, false),
676                         0x17 => process_msg_events!(1, true),
677                         0x18 => process_msg_events!(1, false),
678                         0x19 => process_events!(1, true),
679                         0x1a => process_events!(1, false),
680                         0x1b => process_msg_events!(2, true),
681                         0x1c => process_msg_events!(2, false),
682                         0x1d => process_events!(2, true),
683                         0x1e => process_events!(2, false),
684                         0x1f => {
685                                 if !chan_a_disconnected {
686                                         nodes[1].peer_disconnected(&nodes[0].get_our_node_id(), false);
687                                         chan_a_disconnected = true;
688                                         drain_msg_events_on_disconnect!(0);
689                                 }
690                                 let (new_node_a, new_monitor_a) = reload_node!(node_a_ser, 0, monitor_a);
691                                 node_a = Arc::new(new_node_a);
692                                 nodes[0] = node_a.clone();
693                                 monitor_a = new_monitor_a;
694                         },
695                         0x20 => {
696                                 if !chan_a_disconnected {
697                                         nodes[0].peer_disconnected(&nodes[1].get_our_node_id(), false);
698                                         chan_a_disconnected = true;
699                                         nodes[0].get_and_clear_pending_msg_events();
700                                         ba_events.clear();
701                                 }
702                                 if !chan_b_disconnected {
703                                         nodes[2].peer_disconnected(&nodes[1].get_our_node_id(), false);
704                                         chan_b_disconnected = true;
705                                         nodes[2].get_and_clear_pending_msg_events();
706                                         bc_events.clear();
707                                 }
708                                 let (new_node_b, new_monitor_b) = reload_node!(node_b_ser, 1, monitor_b);
709                                 node_b = Arc::new(new_node_b);
710                                 nodes[1] = node_b.clone();
711                                 monitor_b = new_monitor_b;
712                         },
713                         0x21 => {
714                                 if !chan_b_disconnected {
715                                         nodes[1].peer_disconnected(&nodes[2].get_our_node_id(), false);
716                                         chan_b_disconnected = true;
717                                         drain_msg_events_on_disconnect!(2);
718                                 }
719                                 let (new_node_c, new_monitor_c) = reload_node!(node_c_ser, 2, monitor_c);
720                                 node_c = Arc::new(new_node_c);
721                                 nodes[2] = node_c.clone();
722                                 monitor_c = new_monitor_c;
723                         },
724                         _ => test_return!(),
725                 }
726
727                 if monitor_a.should_update_manager.load(atomic::Ordering::Relaxed) {
728                         node_a_ser.0.clear();
729                         nodes[0].write(&mut node_a_ser).unwrap();
730                         monitor_a.should_update_manager.store(false, atomic::Ordering::Relaxed);
731                         *monitor_a.latest_updates_good_at_last_ser.lock().unwrap() = monitor_a.latest_update_good.lock().unwrap().clone();
732                 }
733                 if monitor_b.should_update_manager.load(atomic::Ordering::Relaxed) {
734                         node_b_ser.0.clear();
735                         nodes[1].write(&mut node_b_ser).unwrap();
736                         monitor_b.should_update_manager.store(false, atomic::Ordering::Relaxed);
737                         *monitor_b.latest_updates_good_at_last_ser.lock().unwrap() = monitor_b.latest_update_good.lock().unwrap().clone();
738                 }
739                 if monitor_c.should_update_manager.load(atomic::Ordering::Relaxed) {
740                         node_c_ser.0.clear();
741                         nodes[2].write(&mut node_c_ser).unwrap();
742                         monitor_c.should_update_manager.store(false, atomic::Ordering::Relaxed);
743                         *monitor_c.latest_updates_good_at_last_ser.lock().unwrap() = monitor_c.latest_update_good.lock().unwrap().clone();
744                 }
745         }
746 }
747
748 #[cfg(feature = "afl")]
749 #[macro_use] extern crate afl;
750 #[cfg(feature = "afl")]
751 fn main() {
752         fuzz!(|data| {
753                 do_test(data);
754         });
755 }
756
757 #[cfg(feature = "honggfuzz")]
758 #[macro_use] extern crate honggfuzz;
759 #[cfg(feature = "honggfuzz")]
760 fn main() {
761         loop {
762                 fuzz!(|data| {
763                         do_test(data);
764                 });
765         }
766 }
767
768 #[cfg(feature = "libfuzzer_fuzz")]
769 #[macro_use] extern crate libfuzzer_sys;
770 #[cfg(feature = "libfuzzer_fuzz")]
771 fuzz_target!(|data: &[u8]| {
772         do_test(data);
773 });
774
775 extern crate hex;
776 #[cfg(test)]
777 mod tests {
778         #[test]
779         fn duplicate_crash() {
780                 super::do_test(&::hex::decode("00").unwrap());
781         }
782 }