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