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