Fix crash in chanmon_fail_consistency due to fuzz hash collisions
[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
31 use lightning::chain::chaininterface;
32 use lightning::chain::transaction::OutPoint;
33 use lightning::chain::chaininterface::{BroadcasterInterface,ConfirmationTarget,ChainListener,FeeEstimator,ChainWatchInterfaceUtil};
34 use lightning::chain::keysinterface::{ChannelKeys, KeysInterface};
35 use lightning::ln::channelmonitor;
36 use lightning::ln::channelmonitor::{ChannelMonitorUpdateErr, HTLCUpdate};
37 use lightning::ln::channelmanager::{ChannelManager, PaymentHash, PaymentPreimage};
38 use lightning::ln::router::{Route, RouteHop};
39 use lightning::ln::msgs::{CommitmentUpdate, ChannelMessageHandler, ErrorAction, HandleError, UpdateAddHTLC};
40 use lightning::util::{reset_rng_state, fill_bytes, events};
41 use lightning::util::logger::Logger;
42 use lightning::util::config::UserConfig;
43 use lightning::util::events::{EventsProvider, MessageSendEventsProvider};
44 use lightning::util::ser::{Readable, Writeable};
45
46 mod utils;
47 use utils::test_logger;
48
49 use secp256k1::key::{PublicKey,SecretKey};
50 use secp256k1::Secp256k1;
51
52 use std::cmp::Ordering;
53 use std::collections::HashSet;
54 use std::sync::{Arc,Mutex};
55 use std::io::Cursor;
56
57 struct FuzzEstimator {}
58 impl FeeEstimator for FuzzEstimator {
59         fn get_est_sat_per_1000_weight(&self, _: ConfirmationTarget) -> u64 {
60                 253
61         }
62 }
63
64 pub struct TestBroadcaster {}
65 impl BroadcasterInterface for TestBroadcaster {
66         fn broadcast_transaction(&self, _tx: &Transaction) { }
67 }
68
69 pub struct TestChannelMonitor {
70         pub simple_monitor: Arc<channelmonitor::SimpleManyChannelMonitor<OutPoint>>,
71         pub update_ret: Mutex<Result<(), channelmonitor::ChannelMonitorUpdateErr>>,
72 }
73 impl TestChannelMonitor {
74         pub fn new(chain_monitor: Arc<chaininterface::ChainWatchInterface>, broadcaster: Arc<chaininterface::BroadcasterInterface>, logger: Arc<Logger>) -> Self {
75                 Self {
76                         simple_monitor: channelmonitor::SimpleManyChannelMonitor::new(chain_monitor, broadcaster, logger),
77                         update_ret: Mutex::new(Ok(())),
78                 }
79         }
80 }
81 impl channelmonitor::ManyChannelMonitor for TestChannelMonitor {
82         fn add_update_monitor(&self, funding_txo: OutPoint, monitor: channelmonitor::ChannelMonitor) -> Result<(), channelmonitor::ChannelMonitorUpdateErr> {
83                 assert!(self.simple_monitor.add_update_monitor(funding_txo, monitor).is_ok());
84                 self.update_ret.lock().unwrap().clone()
85         }
86
87         fn fetch_pending_htlc_updated(&self) -> Vec<HTLCUpdate> {
88                 return self.simple_monitor.fetch_pending_htlc_updated();
89         }
90 }
91
92 struct KeyProvider {
93         node_id: u8,
94 }
95 impl KeysInterface for KeyProvider {
96         fn get_node_secret(&self) -> SecretKey {
97                 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()
98         }
99
100         fn get_destination_script(&self) -> Script {
101                 let secp_ctx = Secp256k1::signing_only();
102                 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();
103                 let our_channel_monitor_claim_key_hash = Hash160::hash(&PublicKey::from_secret_key(&secp_ctx, &channel_monitor_claim_key).serialize());
104                 Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0).push_slice(&our_channel_monitor_claim_key_hash[..]).into_script()
105         }
106
107         fn get_shutdown_pubkey(&self) -> PublicKey {
108                 let secp_ctx = Secp256k1::signing_only();
109                 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())
110         }
111
112         fn get_channel_keys(&self, _inbound: bool) -> ChannelKeys {
113                 ChannelKeys {
114                         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(),
115                         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(),
116                         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(),
117                         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(),
118                         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(),
119                         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],
120                 }
121         }
122
123         fn get_session_key(&self) -> SecretKey {
124                 let mut session_key = [0; 32];
125                 fill_bytes(&mut session_key);
126                 SecretKey::from_slice(&session_key).unwrap()
127         }
128
129         fn get_channel_id(&self) -> [u8; 32] {
130                 let mut channel_id = [0; 32];
131                 fill_bytes(&mut channel_id);
132                 channel_id
133         }
134 }
135
136 #[inline]
137 pub fn do_test(data: &[u8]) {
138         reset_rng_state();
139
140         let fee_est = Arc::new(FuzzEstimator{});
141         let broadcast = Arc::new(TestBroadcaster{});
142
143         macro_rules! make_node {
144                 ($node_id: expr) => { {
145                         let logger: Arc<Logger> = Arc::new(test_logger::TestLogger::new($node_id.to_string()));
146                         let watch = Arc::new(ChainWatchInterfaceUtil::new(Network::Bitcoin, Arc::clone(&logger)));
147                         let monitor = Arc::new(TestChannelMonitor::new(watch.clone(), broadcast.clone(), logger.clone()));
148
149                         let keys_manager = Arc::new(KeyProvider { node_id: $node_id });
150                         let mut config = UserConfig::new();
151                         config.channel_options.fee_proportional_millionths = 0;
152                         config.channel_options.announced_channel = true;
153                         config.channel_limits.min_dust_limit_satoshis = 0;
154                         (ChannelManager::new(Network::Bitcoin, fee_est.clone(), monitor.clone(), watch.clone(), broadcast.clone(), Arc::clone(&logger), keys_manager.clone(), config).unwrap(),
155                         monitor)
156                 } }
157         }
158
159         let mut channel_txn = Vec::new();
160         macro_rules! make_channel {
161                 ($source: expr, $dest: expr, $chan_id: expr) => { {
162                         $source.create_channel($dest.get_our_node_id(), 10000000, 42, 0).unwrap();
163                         let open_channel = {
164                                 let events = $source.get_and_clear_pending_msg_events();
165                                 assert_eq!(events.len(), 1);
166                                 if let events::MessageSendEvent::SendOpenChannel { ref msg, .. } = events[0] {
167                                         msg.clone()
168                                 } else { panic!("Wrong event type"); }
169                         };
170
171                         $dest.handle_open_channel(&$source.get_our_node_id(), &open_channel).unwrap();
172                         let accept_channel = {
173                                 let events = $dest.get_and_clear_pending_msg_events();
174                                 assert_eq!(events.len(), 1);
175                                 if let events::MessageSendEvent::SendAcceptChannel { ref msg, .. } = events[0] {
176                                         msg.clone()
177                                 } else { panic!("Wrong event type"); }
178                         };
179
180                         $source.handle_accept_channel(&$dest.get_our_node_id(), &accept_channel).unwrap();
181                         {
182                                 let events = $source.get_and_clear_pending_events();
183                                 assert_eq!(events.len(), 1);
184                                 if let events::Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, .. } = events[0] {
185                                         let tx = Transaction { version: $chan_id, lock_time: 0, input: Vec::new(), output: vec![TxOut {
186                                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
187                                         }]};
188                                         let funding_output = OutPoint::new(tx.txid(), 0);
189                                         $source.funding_transaction_generated(&temporary_channel_id, funding_output);
190                                         channel_txn.push(tx);
191                                 } else { panic!("Wrong event type"); }
192                         }
193
194                         let funding_created = {
195                                 let events = $source.get_and_clear_pending_msg_events();
196                                 assert_eq!(events.len(), 1);
197                                 if let events::MessageSendEvent::SendFundingCreated { ref msg, .. } = events[0] {
198                                         msg.clone()
199                                 } else { panic!("Wrong event type"); }
200                         };
201                         $dest.handle_funding_created(&$source.get_our_node_id(), &funding_created).unwrap();
202
203                         let funding_signed = {
204                                 let events = $dest.get_and_clear_pending_msg_events();
205                                 assert_eq!(events.len(), 1);
206                                 if let events::MessageSendEvent::SendFundingSigned { ref msg, .. } = events[0] {
207                                         msg.clone()
208                                 } else { panic!("Wrong event type"); }
209                         };
210                         $source.handle_funding_signed(&$dest.get_our_node_id(), &funding_signed).unwrap();
211
212                         {
213                                 let events = $source.get_and_clear_pending_events();
214                                 assert_eq!(events.len(), 1);
215                                 if let events::Event::FundingBroadcastSafe { .. } = events[0] {
216                                 } else { panic!("Wrong event type"); }
217                         }
218                 } }
219         }
220
221         macro_rules! confirm_txn {
222                 ($node: expr) => { {
223                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
224                         let mut txn = Vec::with_capacity(channel_txn.len());
225                         let mut posn = Vec::with_capacity(channel_txn.len());
226                         for i in 0..channel_txn.len() {
227                                 txn.push(&channel_txn[i]);
228                                 posn.push(i as u32 + 1);
229                         }
230                         $node.block_connected(&header, 1, &txn, &posn);
231                         for i in 2..100 {
232                                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
233                                 $node.block_connected(&header, i, &Vec::new(), &[0; 0]);
234                         }
235                 } }
236         }
237
238         macro_rules! lock_fundings {
239                 ($nodes: expr) => { {
240                         let mut node_events = Vec::new();
241                         for node in $nodes.iter() {
242                                 node_events.push(node.get_and_clear_pending_msg_events());
243                         }
244                         for (idx, node_event) in node_events.iter().enumerate() {
245                                 for event in node_event {
246                                         if let events::MessageSendEvent::SendFundingLocked { ref node_id, ref msg } = event {
247                                                 for node in $nodes.iter() {
248                                                         if node.get_our_node_id() == *node_id {
249                                                                 node.handle_funding_locked(&$nodes[idx].get_our_node_id(), msg).unwrap();
250                                                         }
251                                                 }
252                                         } else { panic!("Wrong event type"); }
253                                 }
254                         }
255
256                         for node in $nodes.iter() {
257                                 let events = node.get_and_clear_pending_msg_events();
258                                 for event in events {
259                                         if let events::MessageSendEvent::SendAnnouncementSignatures { .. } = event {
260                                         } else { panic!("Wrong event type"); }
261                                 }
262                         }
263                 } }
264         }
265
266         // 3 nodes is enough to hit all the possible cases, notably unknown-source-unknown-dest
267         // forwarding.
268         let (node_a, monitor_a) = make_node!(0);
269         let (node_b, monitor_b) = make_node!(1);
270         let (node_c, monitor_c) = make_node!(2);
271
272         let nodes = [node_a, node_b, node_c];
273
274         make_channel!(nodes[0], nodes[1], 0);
275         make_channel!(nodes[1], nodes[2], 1);
276
277         for node in nodes.iter() {
278                 confirm_txn!(node);
279         }
280
281         lock_fundings!(nodes);
282
283         let chan_a = nodes[0].list_usable_channels()[0].short_channel_id.unwrap();
284         let chan_b = nodes[2].list_usable_channels()[0].short_channel_id.unwrap();
285
286         let mut payment_id = 0;
287
288         let mut chan_a_disconnected = false;
289         let mut chan_b_disconnected = false;
290         let mut chan_a_reconnecting = false;
291         let mut chan_b_reconnecting = false;
292
293         macro_rules! test_err {
294                 ($res: expr) => {
295                         match $res {
296                                 Ok(()) => {},
297                                 Err(HandleError { action: Some(ErrorAction::IgnoreError), .. }) => { },
298                                 _ => { $res.unwrap() },
299                         }
300                 }
301         }
302
303         macro_rules! test_return {
304                 () => { {
305                         assert_eq!(nodes[0].list_channels().len(), 1);
306                         assert_eq!(nodes[1].list_channels().len(), 2);
307                         assert_eq!(nodes[2].list_channels().len(), 1);
308                         return;
309                 } }
310         }
311
312         let mut read_pos = 0;
313         macro_rules! get_slice {
314                 ($len: expr) => {
315                         {
316                                 let slice_len = $len as usize;
317                                 if data.len() < read_pos + slice_len {
318                                         test_return!();
319                                 }
320                                 read_pos += slice_len;
321                                 &data[read_pos - slice_len..read_pos]
322                         }
323                 }
324         }
325
326         loop {
327                 macro_rules! send_payment {
328                         ($source: expr, $dest: expr) => { {
329                                 let payment_hash = Sha256::hash(&[payment_id; 1]);
330                                 payment_id = payment_id.wrapping_add(1);
331                                 if let Err(_) = $source.send_payment(Route {
332                                         hops: vec![RouteHop {
333                                                 pubkey: $dest.0.get_our_node_id(),
334                                                 short_channel_id: $dest.1,
335                                                 fee_msat: 5000000,
336                                                 cltv_expiry_delta: 200,
337                                         }],
338                                 }, PaymentHash(payment_hash.into_inner())) {
339                                         // Probably ran out of funds
340                                         test_return!();
341                                 }
342                         } };
343                         ($source: expr, $middle: expr, $dest: expr) => { {
344                                 let payment_hash = Sha256::hash(&[payment_id; 1]);
345                                 payment_id = payment_id.wrapping_add(1);
346                                 if let Err(_) = $source.send_payment(Route {
347                                         hops: vec![RouteHop {
348                                                 pubkey: $middle.0.get_our_node_id(),
349                                                 short_channel_id: $middle.1,
350                                                 fee_msat: 50000,
351                                                 cltv_expiry_delta: 100,
352                                         },RouteHop {
353                                                 pubkey: $dest.0.get_our_node_id(),
354                                                 short_channel_id: $dest.1,
355                                                 fee_msat: 5000000,
356                                                 cltv_expiry_delta: 200,
357                                         }],
358                                 }, PaymentHash(payment_hash.into_inner())) {
359                                         // Probably ran out of funds
360                                         test_return!();
361                                 }
362                         } }
363                 }
364
365                 macro_rules! process_msg_events {
366                         ($node: expr, $corrupt_forward: expr) => { {
367                                 for event in nodes[$node].get_and_clear_pending_msg_events() {
368                                         match event {
369                                                 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 } } => {
370                                                         for (idx, dest) in nodes.iter().enumerate() {
371                                                                 if dest.get_our_node_id() == *node_id &&
372                                                                                 (($node != 0 && idx != 0) || !chan_a_disconnected) &&
373                                                                                 (($node != 2 && idx != 2) || !chan_b_disconnected) {
374                                                                         assert!(update_fee.is_none());
375                                                                         for update_add in update_add_htlcs {
376                                                                                 if !$corrupt_forward {
377                                                                                         test_err!(dest.handle_update_add_htlc(&nodes[$node].get_our_node_id(), &update_add));
378                                                                                 } else {
379                                                                                         // Corrupt the update_add_htlc message so that its HMAC
380                                                                                         // check will fail and we generate a
381                                                                                         // update_fail_malformed_htlc instead of an
382                                                                                         // update_fail_htlc as we do when we reject a payment.
383                                                                                         let mut msg_ser = update_add.encode();
384                                                                                         msg_ser[1000] ^= 0xff;
385                                                                                         let new_msg = UpdateAddHTLC::read(&mut Cursor::new(&msg_ser)).unwrap();
386                                                                                         test_err!(dest.handle_update_add_htlc(&nodes[$node].get_our_node_id(), &new_msg));
387                                                                                 }
388                                                                         }
389                                                                         for update_fulfill in update_fulfill_htlcs {
390                                                                                 test_err!(dest.handle_update_fulfill_htlc(&nodes[$node].get_our_node_id(), &update_fulfill));
391                                                                         }
392                                                                         for update_fail in update_fail_htlcs {
393                                                                                 test_err!(dest.handle_update_fail_htlc(&nodes[$node].get_our_node_id(), &update_fail));
394                                                                         }
395                                                                         for update_fail_malformed in update_fail_malformed_htlcs {
396                                                                                 test_err!(dest.handle_update_fail_malformed_htlc(&nodes[$node].get_our_node_id(), &update_fail_malformed));
397                                                                         }
398                                                                         test_err!(dest.handle_commitment_signed(&nodes[$node].get_our_node_id(), &commitment_signed));
399                                                                 }
400                                                         }
401                                                 },
402                                                 events::MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
403                                                         for (idx, dest) in nodes.iter().enumerate() {
404                                                                 if dest.get_our_node_id() == *node_id &&
405                                                                                 (($node != 0 && idx != 0) || !chan_a_disconnected) &&
406                                                                                 (($node != 2 && idx != 2) || !chan_b_disconnected) {
407                                                                         test_err!(dest.handle_revoke_and_ack(&nodes[$node].get_our_node_id(), msg));
408                                                                 }
409                                                         }
410                                                 },
411                                                 events::MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => {
412                                                         for (idx, dest) in nodes.iter().enumerate() {
413                                                                 if dest.get_our_node_id() == *node_id {
414                                                                         test_err!(dest.handle_channel_reestablish(&nodes[$node].get_our_node_id(), msg));
415                                                                         if $node == 0 || idx == 0 {
416                                                                                 chan_a_reconnecting = false;
417                                                                                 chan_a_disconnected = false;
418                                                                         } else {
419                                                                                 chan_b_reconnecting = false;
420                                                                                 chan_b_disconnected = false;
421                                                                         }
422                                                                 }
423                                                         }
424                                                 },
425                                                 events::MessageSendEvent::SendFundingLocked { .. } => {
426                                                         // Can be generated as a reestablish response
427                                                 },
428                                                 events::MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {
429                                                         // Can be generated due to a payment forward being rejected due to a
430                                                         // channel having previously failed a monitor update
431                                                 },
432                                                 _ => panic!("Unhandled message event"),
433                                         }
434                                 }
435                         } }
436                 }
437
438                 macro_rules! process_events {
439                         ($node: expr, $fail: expr) => { {
440                                 // In case we get 256 payments we may have a hash collision, resulting in the
441                                 // second claim/fail call not finding the duplicate-hash HTLC, so we have to
442                                 // deduplicate the calls here.
443                                 let mut claim_set = HashSet::new();
444                                 let mut events = nodes[$node].get_and_clear_pending_events();
445                                 // Sort events so that PendingHTLCsForwardable get processed last. This avoids a
446                                 // case where we first process a PendingHTLCsForwardable, then claim/fail on a
447                                 // PaymentReceived, claiming/failing two HTLCs, but leaving a just-generated
448                                 // PaymentReceived event for the second HTLC in our pending_events (and breaking
449                                 // our claim_set deduplication).
450                                 events.sort_by(|a, b| {
451                                         if let events::Event::PaymentReceived { .. } = a {
452                                                 if let events::Event::PendingHTLCsForwardable { .. } = b {
453                                                         Ordering::Less
454                                                 } else { Ordering::Equal }
455                                         } else if let events::Event::PendingHTLCsForwardable { .. } = a {
456                                                 if let events::Event::PaymentReceived { .. } = b {
457                                                         Ordering::Greater
458                                                 } else { Ordering::Equal }
459                                         } else { Ordering::Equal }
460                                 });
461                                 for event in events.drain(..) {
462                                         match event {
463                                                 events::Event::PaymentReceived { payment_hash, .. } => {
464                                                         if claim_set.insert(payment_hash.0) {
465                                                                 if $fail {
466                                                                         assert!(nodes[$node].fail_htlc_backwards(&payment_hash));
467                                                                 } else {
468                                                                         assert!(nodes[$node].claim_funds(PaymentPreimage(payment_hash.0)));
469                                                                 }
470                                                         }
471                                                 },
472                                                 events::Event::PaymentSent { .. } => {},
473                                                 events::Event::PaymentFailed { .. } => {},
474                                                 events::Event::PendingHTLCsForwardable { .. } => {
475                                                         nodes[$node].process_pending_htlc_forwards();
476                                                 },
477                                                 _ => panic!("Unhandled event"),
478                                         }
479                                 }
480                         } }
481                 }
482
483                 match get_slice!(1)[0] {
484                         0x00 => *monitor_a.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure),
485                         0x01 => *monitor_b.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure),
486                         0x02 => *monitor_c.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure),
487                         0x03 => *monitor_a.update_ret.lock().unwrap() = Ok(()),
488                         0x04 => *monitor_b.update_ret.lock().unwrap() = Ok(()),
489                         0x05 => *monitor_c.update_ret.lock().unwrap() = Ok(()),
490                         0x06 => nodes[0].test_restore_channel_monitor(),
491                         0x07 => nodes[1].test_restore_channel_monitor(),
492                         0x08 => nodes[2].test_restore_channel_monitor(),
493                         0x09 => send_payment!(nodes[0], (&nodes[1], chan_a)),
494                         0x0a => send_payment!(nodes[1], (&nodes[0], chan_a)),
495                         0x0b => send_payment!(nodes[1], (&nodes[2], chan_b)),
496                         0x0c => send_payment!(nodes[2], (&nodes[1], chan_b)),
497                         0x0d => send_payment!(nodes[0], (&nodes[1], chan_a), (&nodes[2], chan_b)),
498                         0x0e => send_payment!(nodes[2], (&nodes[1], chan_b), (&nodes[0], chan_a)),
499                         0x0f => {
500                                 if !chan_a_disconnected {
501                                         nodes[0].peer_disconnected(&nodes[1].get_our_node_id(), false);
502                                         nodes[1].peer_disconnected(&nodes[0].get_our_node_id(), false);
503                                         chan_a_disconnected = true;
504                                 }
505                         },
506                         0x10 => {
507                                 if !chan_b_disconnected {
508                                         nodes[1].peer_disconnected(&nodes[2].get_our_node_id(), false);
509                                         nodes[2].peer_disconnected(&nodes[1].get_our_node_id(), false);
510                                         chan_b_disconnected = true;
511                                 }
512                         },
513                         0x11 => {
514                                 if chan_a_disconnected && !chan_a_reconnecting {
515                                         nodes[0].peer_connected(&nodes[1].get_our_node_id());
516                                         nodes[1].peer_connected(&nodes[0].get_our_node_id());
517                                         chan_a_reconnecting = true;
518                                 }
519                         },
520                         0x12 => {
521                                 if chan_b_disconnected && !chan_b_reconnecting {
522                                         nodes[1].peer_connected(&nodes[2].get_our_node_id());
523                                         nodes[2].peer_connected(&nodes[1].get_our_node_id());
524                                         chan_b_reconnecting = true;
525                                 }
526                         },
527                         0x13 => process_msg_events!(0, true),
528                         0x14 => process_msg_events!(0, false),
529                         0x15 => process_events!(0, true),
530                         0x16 => process_events!(0, false),
531                         0x17 => process_msg_events!(1, true),
532                         0x18 => process_msg_events!(1, false),
533                         0x19 => process_events!(1, true),
534                         0x1a => process_events!(1, false),
535                         0x1b => process_msg_events!(2, true),
536                         0x1c => process_msg_events!(2, false),
537                         0x1d => process_events!(2, true),
538                         0x1e => process_events!(2, false),
539                         _ => test_return!(),
540                 }
541         }
542 }
543
544 #[cfg(feature = "afl")]
545 #[macro_use] extern crate afl;
546 #[cfg(feature = "afl")]
547 fn main() {
548         fuzz!(|data| {
549                 do_test(data);
550         });
551 }
552
553 #[cfg(feature = "honggfuzz")]
554 #[macro_use] extern crate honggfuzz;
555 #[cfg(feature = "honggfuzz")]
556 fn main() {
557         loop {
558                 fuzz!(|data| {
559                         do_test(data);
560                 });
561         }
562 }
563
564 #[cfg(feature = "libfuzzer_fuzz")]
565 #[macro_use] extern crate libfuzzer_sys;
566 #[cfg(feature = "libfuzzer_fuzz")]
567 fuzz_target!(|data: &[u8]| {
568         do_test(data);
569 });
570
571 extern crate hex;
572 #[cfg(test)]
573 mod tests {
574         #[test]
575         fn duplicate_crash() {
576                 super::do_test(&::hex::decode("00").unwrap());
577         }
578 }