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