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