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