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