3191eb27308767c97a9d9e770873dbfd154618dc
[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::BitcoinHash;
22 use bitcoin::blockdata::block::BlockHeader;
23 use bitcoin::blockdata::transaction::{Transaction, TxOut};
24 use bitcoin::blockdata::script::{Builder, Script};
25 use bitcoin::blockdata::opcodes;
26 use bitcoin::network::constants::Network;
27
28 use bitcoin::hashes::Hash as TraitImport;
29 use bitcoin::hashes::sha256::Hash as Sha256;
30 use bitcoin::hash_types::{BlockHash, WPubkeyHash};
31
32 use lightning::chain::chaininterface;
33 use lightning::chain::transaction::OutPoint;
34 use lightning::chain::chaininterface::{BroadcasterInterface,ConfirmationTarget,ChainListener,FeeEstimator,ChainWatchInterfaceUtil,ChainWatchInterface};
35 use lightning::chain::keysinterface::{KeysInterface, InMemoryChannelKeys};
36 use lightning::ln::channelmonitor;
37 use lightning::ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, MonitorEvent};
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 TestChannelMonitor {
86         pub logger: Arc<dyn Logger>,
87         pub simple_monitor: Arc<channelmonitor::SimpleManyChannelMonitor<OutPoint, EnforcingChannelKeys, Arc<TestBroadcaster>, Arc<FuzzEstimator>, Arc<dyn Logger>, Arc<dyn ChainWatchInterface>>>,
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 TestChannelMonitor {
98         pub fn new(chain_monitor: Arc<dyn chaininterface::ChainWatchInterface>, broadcaster: Arc<TestBroadcaster>, logger: Arc<dyn Logger>, feeest: Arc<FuzzEstimator>) -> Self {
99                 Self {
100                         simple_monitor: Arc::new(channelmonitor::SimpleManyChannelMonitor::new(chain_monitor, 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 channelmonitor::ManyChannelMonitor for TestChannelMonitor {
109         type Keys = EnforcingChannelKeys;
110
111         fn add_monitor(&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-add_monitor");
116                 }
117                 self.should_update_manager.store(true, atomic::Ordering::Relaxed);
118                 assert!(self.simple_monitor.add_monitor(funding_txo, monitor).is_ok());
119                 self.update_ret.lock().unwrap().clone()
120         }
121
122         fn update_monitor(&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 get_and_clear_pending_monitor_events(&self) -> Vec<MonitorEvent> {
139                 return self.simple_monitor.get_and_clear_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 watch = Arc::new(ChainWatchInterfaceUtil::new(Network::Bitcoin));
196                         let monitor = Arc::new(TestChannelMonitor::new(watch.clone(), broadcast.clone(), logger.clone(), fee_est.clone()));
197
198                         let keys_manager = Arc::new(KeyProvider { node_id: $node_id, rand_bytes_id: atomic::AtomicU8::new(0) });
199                         let mut config = UserConfig::default();
200                         config.channel_options.fee_proportional_millionths = 0;
201                         config.channel_options.announced_channel = true;
202                         config.peer_channel_config_limits.min_dust_limit_satoshis = 0;
203                         (Arc::new(ChannelManager::new(Network::Bitcoin, fee_est.clone(), monitor.clone(), broadcast.clone(), Arc::clone(&logger), keys_manager.clone(), config, 0)),
204                         monitor)
205                 } }
206         }
207
208         macro_rules! reload_node {
209                 ($ser: expr, $node_id: expr, $old_monitors: expr) => { {
210                         let logger: Arc<dyn Logger> = Arc::new(test_logger::TestLogger::new($node_id.to_string(), out.clone()));
211                         let watch = Arc::new(ChainWatchInterfaceUtil::new(Network::Bitcoin));
212                         let monitor = Arc::new(TestChannelMonitor::new(watch.clone(), broadcast.clone(), logger.clone(), fee_est.clone()));
213
214                         let keys_manager = Arc::new(KeyProvider { node_id: $node_id, rand_bytes_id: atomic::AtomicU8::new(0) });
215                         let mut config = UserConfig::default();
216                         config.channel_options.fee_proportional_millionths = 0;
217                         config.channel_options.announced_channel = true;
218                         config.peer_channel_config_limits.min_dust_limit_satoshis = 0;
219
220                         let mut monitors = HashMap::new();
221                         let mut old_monitors = $old_monitors.latest_monitors.lock().unwrap();
222                         for (outpoint, (update_id, monitor_ser)) in old_monitors.drain() {
223                                 monitors.insert(outpoint, <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut Cursor::new(&monitor_ser)).expect("Failed to read monitor").1);
224                                 monitor.latest_monitors.lock().unwrap().insert(outpoint, (update_id, monitor_ser));
225                         }
226                         let mut monitor_refs = HashMap::new();
227                         for (outpoint, monitor) in monitors.iter_mut() {
228                                 monitor_refs.insert(*outpoint, monitor);
229                         }
230
231                         let read_args = ChannelManagerReadArgs {
232                                 keys_manager,
233                                 fee_estimator: fee_est.clone(),
234                                 monitor: monitor.clone(),
235                                 tx_broadcaster: broadcast.clone(),
236                                 logger,
237                                 default_config: config,
238                                 channel_monitors: monitor_refs,
239                         };
240
241                         (<(BlockHash, ChannelManager<EnforcingChannelKeys, Arc<TestChannelMonitor>, Arc<TestBroadcaster>, Arc<KeyProvider>, Arc<FuzzEstimator>, Arc<dyn Logger>>)>::read(&mut Cursor::new(&$ser.0), read_args).expect("Failed to read manager").1, monitor)
242                 } }
243         }
244
245         let mut channel_txn = Vec::new();
246         macro_rules! make_channel {
247                 ($source: expr, $dest: expr, $chan_id: expr) => { {
248                         $source.create_channel($dest.get_our_node_id(), 10000000, 42, 0, None).unwrap();
249                         let open_channel = {
250                                 let events = $source.get_and_clear_pending_msg_events();
251                                 assert_eq!(events.len(), 1);
252                                 if let events::MessageSendEvent::SendOpenChannel { ref msg, .. } = events[0] {
253                                         msg.clone()
254                                 } else { panic!("Wrong event type"); }
255                         };
256
257                         $dest.handle_open_channel(&$source.get_our_node_id(), InitFeatures::known(), &open_channel);
258                         let accept_channel = {
259                                 let events = $dest.get_and_clear_pending_msg_events();
260                                 assert_eq!(events.len(), 1);
261                                 if let events::MessageSendEvent::SendAcceptChannel { ref msg, .. } = events[0] {
262                                         msg.clone()
263                                 } else { panic!("Wrong event type"); }
264                         };
265
266                         $source.handle_accept_channel(&$dest.get_our_node_id(), InitFeatures::known(), &accept_channel);
267                         let funding_output;
268                         {
269                                 let events = $source.get_and_clear_pending_events();
270                                 assert_eq!(events.len(), 1);
271                                 if let events::Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, .. } = events[0] {
272                                         let tx = Transaction { version: $chan_id, lock_time: 0, input: Vec::new(), output: vec![TxOut {
273                                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
274                                         }]};
275                                         funding_output = OutPoint { txid: tx.txid(), index: 0 };
276                                         $source.funding_transaction_generated(&temporary_channel_id, funding_output);
277                                         channel_txn.push(tx);
278                                 } else { panic!("Wrong event type"); }
279                         }
280
281                         let funding_created = {
282                                 let events = $source.get_and_clear_pending_msg_events();
283                                 assert_eq!(events.len(), 1);
284                                 if let events::MessageSendEvent::SendFundingCreated { ref msg, .. } = events[0] {
285                                         msg.clone()
286                                 } else { panic!("Wrong event type"); }
287                         };
288                         $dest.handle_funding_created(&$source.get_our_node_id(), &funding_created);
289
290                         let funding_signed = {
291                                 let events = $dest.get_and_clear_pending_msg_events();
292                                 assert_eq!(events.len(), 1);
293                                 if let events::MessageSendEvent::SendFundingSigned { ref msg, .. } = events[0] {
294                                         msg.clone()
295                                 } else { panic!("Wrong event type"); }
296                         };
297                         $source.handle_funding_signed(&$dest.get_our_node_id(), &funding_signed);
298
299                         {
300                                 let events = $source.get_and_clear_pending_events();
301                                 assert_eq!(events.len(), 1);
302                                 if let events::Event::FundingBroadcastSafe { .. } = events[0] {
303                                 } else { panic!("Wrong event type"); }
304                         }
305                         funding_output
306                 } }
307         }
308
309         macro_rules! confirm_txn {
310                 ($node: expr) => { {
311                         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
312                         let mut txn = Vec::with_capacity(channel_txn.len());
313                         let mut posn = Vec::with_capacity(channel_txn.len());
314                         for i in 0..channel_txn.len() {
315                                 txn.push(&channel_txn[i]);
316                                 posn.push(i + 1);
317                         }
318                         $node.block_connected(&header, 1, &txn, &posn);
319                         for i in 2..100 {
320                                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
321                                 $node.block_connected(&header, i, &Vec::new(), &[0; 0]);
322                         }
323                 } }
324         }
325
326         macro_rules! lock_fundings {
327                 ($nodes: expr) => { {
328                         let mut node_events = Vec::new();
329                         for node in $nodes.iter() {
330                                 node_events.push(node.get_and_clear_pending_msg_events());
331                         }
332                         for (idx, node_event) in node_events.iter().enumerate() {
333                                 for event in node_event {
334                                         if let events::MessageSendEvent::SendFundingLocked { ref node_id, ref msg } = event {
335                                                 for node in $nodes.iter() {
336                                                         if node.get_our_node_id() == *node_id {
337                                                                 node.handle_funding_locked(&$nodes[idx].get_our_node_id(), msg);
338                                                         }
339                                                 }
340                                         } else { panic!("Wrong event type"); }
341                                 }
342                         }
343
344                         for node in $nodes.iter() {
345                                 let events = node.get_and_clear_pending_msg_events();
346                                 for event in events {
347                                         if let events::MessageSendEvent::SendAnnouncementSignatures { .. } = event {
348                                         } else { panic!("Wrong event type"); }
349                                 }
350                         }
351                 } }
352         }
353
354         // 3 nodes is enough to hit all the possible cases, notably unknown-source-unknown-dest
355         // forwarding.
356         let (mut node_a, mut monitor_a) = make_node!(0);
357         let (mut node_b, mut monitor_b) = make_node!(1);
358         let (mut node_c, mut monitor_c) = make_node!(2);
359
360         let mut nodes = [node_a, node_b, node_c];
361
362         let chan_1_funding = make_channel!(nodes[0], nodes[1], 0);
363         let chan_2_funding = make_channel!(nodes[1], nodes[2], 1);
364
365         for node in nodes.iter() {
366                 confirm_txn!(node);
367         }
368
369         lock_fundings!(nodes);
370
371         let chan_a = nodes[0].list_usable_channels()[0].short_channel_id.unwrap();
372         let chan_b = nodes[2].list_usable_channels()[0].short_channel_id.unwrap();
373
374         let mut payment_id = 0;
375
376         let mut chan_a_disconnected = false;
377         let mut chan_b_disconnected = false;
378         let mut ba_events = Vec::new();
379         let mut bc_events = Vec::new();
380
381         let mut node_a_ser = VecWriter(Vec::new());
382         nodes[0].write(&mut node_a_ser).unwrap();
383         let mut node_b_ser = VecWriter(Vec::new());
384         nodes[1].write(&mut node_b_ser).unwrap();
385         let mut node_c_ser = VecWriter(Vec::new());
386         nodes[2].write(&mut node_c_ser).unwrap();
387
388         macro_rules! test_return {
389                 () => { {
390                         assert_eq!(nodes[0].list_channels().len(), 1);
391                         assert_eq!(nodes[1].list_channels().len(), 2);
392                         assert_eq!(nodes[2].list_channels().len(), 1);
393                         return;
394                 } }
395         }
396
397         let mut read_pos = 0;
398         macro_rules! get_slice {
399                 ($len: expr) => {
400                         {
401                                 let slice_len = $len as usize;
402                                 if data.len() < read_pos + slice_len {
403                                         test_return!();
404                                 }
405                                 read_pos += slice_len;
406                                 &data[read_pos - slice_len..read_pos]
407                         }
408                 }
409         }
410
411         loop {
412                 macro_rules! send_payment {
413                         ($source: expr, $dest: expr, $amt: expr) => { {
414                                 let payment_hash = Sha256::hash(&[payment_id; 1]);
415                                 payment_id = payment_id.wrapping_add(1);
416                                 if let Err(_) = $source.send_payment(&Route {
417                                         paths: vec![vec![RouteHop {
418                                                 pubkey: $dest.0.get_our_node_id(),
419                                                 node_features: NodeFeatures::empty(),
420                                                 short_channel_id: $dest.1,
421                                                 channel_features: ChannelFeatures::empty(),
422                                                 fee_msat: $amt,
423                                                 cltv_expiry_delta: 200,
424                                         }]],
425                                 }, PaymentHash(payment_hash.into_inner()), &None) {
426                                         // Probably ran out of funds
427                                         test_return!();
428                                 }
429                         } };
430                         ($source: expr, $middle: expr, $dest: expr, $amt: expr) => { {
431                                 let payment_hash = Sha256::hash(&[payment_id; 1]);
432                                 payment_id = payment_id.wrapping_add(1);
433                                 if let Err(_) = $source.send_payment(&Route {
434                                         paths: vec![vec![RouteHop {
435                                                 pubkey: $middle.0.get_our_node_id(),
436                                                 node_features: NodeFeatures::empty(),
437                                                 short_channel_id: $middle.1,
438                                                 channel_features: ChannelFeatures::empty(),
439                                                 fee_msat: 50000,
440                                                 cltv_expiry_delta: 100,
441                                         },RouteHop {
442                                                 pubkey: $dest.0.get_our_node_id(),
443                                                 node_features: NodeFeatures::empty(),
444                                                 short_channel_id: $dest.1,
445                                                 channel_features: ChannelFeatures::empty(),
446                                                 fee_msat: $amt,
447                                                 cltv_expiry_delta: 200,
448                                         }]],
449                                 }, PaymentHash(payment_hash.into_inner()), &None) {
450                                         // Probably ran out of funds
451                                         test_return!();
452                                 }
453                         } }
454                 }
455                 macro_rules! send_payment_with_secret {
456                         ($source: expr, $middle: expr, $dest: expr) => { {
457                                 let payment_hash = Sha256::hash(&[payment_id; 1]);
458                                 payment_id = payment_id.wrapping_add(1);
459                                 let payment_secret = Sha256::hash(&[payment_id; 1]);
460                                 payment_id = payment_id.wrapping_add(1);
461                                 if let Err(_) = $source.send_payment(&Route {
462                                         paths: vec![vec![RouteHop {
463                                                 pubkey: $middle.0.get_our_node_id(),
464                                                 node_features: NodeFeatures::empty(),
465                                                 short_channel_id: $middle.1,
466                                                 channel_features: ChannelFeatures::empty(),
467                                                 fee_msat: 50000,
468                                                 cltv_expiry_delta: 100,
469                                         },RouteHop {
470                                                 pubkey: $dest.0.get_our_node_id(),
471                                                 node_features: NodeFeatures::empty(),
472                                                 short_channel_id: $dest.1,
473                                                 channel_features: ChannelFeatures::empty(),
474                                                 fee_msat: 5000000,
475                                                 cltv_expiry_delta: 200,
476                                         }],vec![RouteHop {
477                                                 pubkey: $middle.0.get_our_node_id(),
478                                                 node_features: NodeFeatures::empty(),
479                                                 short_channel_id: $middle.1,
480                                                 channel_features: ChannelFeatures::empty(),
481                                                 fee_msat: 50000,
482                                                 cltv_expiry_delta: 100,
483                                         },RouteHop {
484                                                 pubkey: $dest.0.get_our_node_id(),
485                                                 node_features: NodeFeatures::empty(),
486                                                 short_channel_id: $dest.1,
487                                                 channel_features: ChannelFeatures::empty(),
488                                                 fee_msat: 5000000,
489                                                 cltv_expiry_delta: 200,
490                                         }]],
491                                 }, PaymentHash(payment_hash.into_inner()), &Some(PaymentSecret(payment_secret.into_inner()))) {
492                                         // Probably ran out of funds
493                                         test_return!();
494                                 }
495                         } }
496                 }
497
498                 macro_rules! process_msg_events {
499                         ($node: expr, $corrupt_forward: expr) => { {
500                                 let events = if $node == 1 {
501                                         let mut new_events = Vec::new();
502                                         mem::swap(&mut new_events, &mut ba_events);
503                                         new_events.extend_from_slice(&bc_events[..]);
504                                         bc_events.clear();
505                                         new_events
506                                 } else { Vec::new() };
507                                 for event in events.iter().chain(nodes[$node].get_and_clear_pending_msg_events().iter()) {
508                                         match event {
509                                                 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 } } => {
510                                                         for dest in nodes.iter() {
511                                                                 if dest.get_our_node_id() == *node_id {
512                                                                         assert!(update_fee.is_none());
513                                                                         for update_add in update_add_htlcs {
514                                                                                 if !$corrupt_forward {
515                                                                                         dest.handle_update_add_htlc(&nodes[$node].get_our_node_id(), &update_add);
516                                                                                 } else {
517                                                                                         // Corrupt the update_add_htlc message so that its HMAC
518                                                                                         // check will fail and we generate a
519                                                                                         // update_fail_malformed_htlc instead of an
520                                                                                         // update_fail_htlc as we do when we reject a payment.
521                                                                                         let mut msg_ser = update_add.encode();
522                                                                                         msg_ser[1000] ^= 0xff;
523                                                                                         let new_msg = UpdateAddHTLC::read(&mut Cursor::new(&msg_ser)).unwrap();
524                                                                                         dest.handle_update_add_htlc(&nodes[$node].get_our_node_id(), &new_msg);
525                                                                                 }
526                                                                         }
527                                                                         for update_fulfill in update_fulfill_htlcs {
528                                                                                 dest.handle_update_fulfill_htlc(&nodes[$node].get_our_node_id(), &update_fulfill);
529                                                                         }
530                                                                         for update_fail in update_fail_htlcs {
531                                                                                 dest.handle_update_fail_htlc(&nodes[$node].get_our_node_id(), &update_fail);
532                                                                         }
533                                                                         for update_fail_malformed in update_fail_malformed_htlcs {
534                                                                                 dest.handle_update_fail_malformed_htlc(&nodes[$node].get_our_node_id(), &update_fail_malformed);
535                                                                         }
536                                                                         dest.handle_commitment_signed(&nodes[$node].get_our_node_id(), &commitment_signed);
537                                                                 }
538                                                         }
539                                                 },
540                                                 events::MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
541                                                         for dest in nodes.iter() {
542                                                                 if dest.get_our_node_id() == *node_id {
543                                                                         dest.handle_revoke_and_ack(&nodes[$node].get_our_node_id(), msg);
544                                                                 }
545                                                         }
546                                                 },
547                                                 events::MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => {
548                                                         for dest in nodes.iter() {
549                                                                 if dest.get_our_node_id() == *node_id {
550                                                                         dest.handle_channel_reestablish(&nodes[$node].get_our_node_id(), msg);
551                                                                 }
552                                                         }
553                                                 },
554                                                 events::MessageSendEvent::SendFundingLocked { .. } => {
555                                                         // Can be generated as a reestablish response
556                                                 },
557                                                 events::MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {
558                                                         // Can be generated due to a payment forward being rejected due to a
559                                                         // channel having previously failed a monitor update
560                                                 },
561                                                 events::MessageSendEvent::HandleError { action: ErrorAction::IgnoreError, .. } => {
562                                                         // Can be generated at any processing step to send back an error, disconnect
563                                                         // peer or just ignore
564                                                 },
565                                                 _ => panic!("Unhandled message event"),
566                                         }
567                                 }
568                         } }
569                 }
570
571                 macro_rules! drain_msg_events_on_disconnect {
572                         ($counterparty_id: expr) => { {
573                                 if $counterparty_id == 0 {
574                                         for event in nodes[0].get_and_clear_pending_msg_events() {
575                                                 match event {
576                                                         events::MessageSendEvent::UpdateHTLCs { .. } => {},
577                                                         events::MessageSendEvent::SendRevokeAndACK { .. } => {},
578                                                         events::MessageSendEvent::SendChannelReestablish { .. } => {},
579                                                         events::MessageSendEvent::SendFundingLocked { .. } => {},
580                                                         events::MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
581                                                         events::MessageSendEvent::HandleError { action: ErrorAction::IgnoreError, .. } => {},
582                                                         _ => panic!("Unhandled message event"),
583                                                 }
584                                         }
585                                         ba_events.clear();
586                                 } else {
587                                         for event in nodes[2].get_and_clear_pending_msg_events() {
588                                                 match event {
589                                                         events::MessageSendEvent::UpdateHTLCs { .. } => {},
590                                                         events::MessageSendEvent::SendRevokeAndACK { .. } => {},
591                                                         events::MessageSendEvent::SendChannelReestablish { .. } => {},
592                                                         events::MessageSendEvent::SendFundingLocked { .. } => {},
593                                                         events::MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
594                                                         events::MessageSendEvent::HandleError { action: ErrorAction::IgnoreError, .. } => {},
595                                                         _ => panic!("Unhandled message event"),
596                                                 }
597                                         }
598                                         bc_events.clear();
599                                 }
600                                 let mut events = nodes[1].get_and_clear_pending_msg_events();
601                                 let drop_node_id = if $counterparty_id == 0 { nodes[0].get_our_node_id() } else { nodes[2].get_our_node_id() };
602                                 let msg_sink = if $counterparty_id == 0 { &mut bc_events } else { &mut ba_events };
603                                 for event in events.drain(..) {
604                                         let push = match event {
605                                                 events::MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
606                                                         if *node_id != drop_node_id { true } else { false }
607                                                 },
608                                                 events::MessageSendEvent::SendRevokeAndACK { ref node_id, .. } => {
609                                                         if *node_id != drop_node_id { true } else { false }
610                                                 },
611                                                 events::MessageSendEvent::SendChannelReestablish { ref node_id, .. } => {
612                                                         if *node_id != drop_node_id { true } else { false }
613                                                 },
614                                                 events::MessageSendEvent::SendFundingLocked { .. } => false,
615                                                 events::MessageSendEvent::PaymentFailureNetworkUpdate { .. } => false,
616                                                 events::MessageSendEvent::HandleError { action: ErrorAction::IgnoreError, .. } => false,
617                                                 _ => panic!("Unhandled message event"),
618                                         };
619                                         if push { msg_sink.push(event); }
620                                 }
621                         } }
622                 }
623
624                 macro_rules! process_events {
625                         ($node: expr, $fail: expr) => { {
626                                 // In case we get 256 payments we may have a hash collision, resulting in the
627                                 // second claim/fail call not finding the duplicate-hash HTLC, so we have to
628                                 // deduplicate the calls here.
629                                 let mut claim_set = HashSet::new();
630                                 let mut events = nodes[$node].get_and_clear_pending_events();
631                                 // Sort events so that PendingHTLCsForwardable get processed last. This avoids a
632                                 // case where we first process a PendingHTLCsForwardable, then claim/fail on a
633                                 // PaymentReceived, claiming/failing two HTLCs, but leaving a just-generated
634                                 // PaymentReceived event for the second HTLC in our pending_events (and breaking
635                                 // our claim_set deduplication).
636                                 events.sort_by(|a, b| {
637                                         if let events::Event::PaymentReceived { .. } = a {
638                                                 if let events::Event::PendingHTLCsForwardable { .. } = b {
639                                                         Ordering::Less
640                                                 } else { Ordering::Equal }
641                                         } else if let events::Event::PendingHTLCsForwardable { .. } = a {
642                                                 if let events::Event::PaymentReceived { .. } = b {
643                                                         Ordering::Greater
644                                                 } else { Ordering::Equal }
645                                         } else { Ordering::Equal }
646                                 });
647                                 for event in events.drain(..) {
648                                         match event {
649                                                 events::Event::PaymentReceived { payment_hash, payment_secret, amt } => {
650                                                         if claim_set.insert(payment_hash.0) {
651                                                                 if $fail {
652                                                                         assert!(nodes[$node].fail_htlc_backwards(&payment_hash, &payment_secret));
653                                                                 } else {
654                                                                         assert!(nodes[$node].claim_funds(PaymentPreimage(payment_hash.0), &payment_secret, amt));
655                                                                 }
656                                                         }
657                                                 },
658                                                 events::Event::PaymentSent { .. } => {},
659                                                 events::Event::PaymentFailed { .. } => {},
660                                                 events::Event::PendingHTLCsForwardable { .. } => {
661                                                         nodes[$node].process_pending_htlc_forwards();
662                                                 },
663                                                 _ => panic!("Unhandled event"),
664                                         }
665                                 }
666                         } }
667                 }
668
669                 match get_slice!(1)[0] {
670                         0x00 => *monitor_a.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure),
671                         0x01 => *monitor_b.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure),
672                         0x02 => *monitor_c.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure),
673                         0x03 => *monitor_a.update_ret.lock().unwrap() = Ok(()),
674                         0x04 => *monitor_b.update_ret.lock().unwrap() = Ok(()),
675                         0x05 => *monitor_c.update_ret.lock().unwrap() = Ok(()),
676                         0x06 => {
677                                 if let Some((id, _)) = monitor_a.latest_monitors.lock().unwrap().get(&chan_1_funding) {
678                                         nodes[0].channel_monitor_updated(&chan_1_funding, *id);
679                                 }
680                         },
681                         0x07 => {
682                                 if let Some((id, _)) = monitor_b.latest_monitors.lock().unwrap().get(&chan_1_funding) {
683                                         nodes[1].channel_monitor_updated(&chan_1_funding, *id);
684                                 }
685                         },
686                         0x24 => {
687                                 if let Some((id, _)) = monitor_b.latest_monitors.lock().unwrap().get(&chan_2_funding) {
688                                         nodes[1].channel_monitor_updated(&chan_2_funding, *id);
689                                 }
690                         },
691                         0x08 => {
692                                 if let Some((id, _)) = monitor_c.latest_monitors.lock().unwrap().get(&chan_2_funding) {
693                                         nodes[2].channel_monitor_updated(&chan_2_funding, *id);
694                                 }
695                         },
696                         0x09 => send_payment!(nodes[0], (&nodes[1], chan_a), 5_000_000),
697                         0x0a => send_payment!(nodes[1], (&nodes[0], chan_a), 5_000_000),
698                         0x0b => send_payment!(nodes[1], (&nodes[2], chan_b), 5_000_000),
699                         0x0c => send_payment!(nodes[2], (&nodes[1], chan_b), 5_000_000),
700                         0x0d => send_payment!(nodes[0], (&nodes[1], chan_a), (&nodes[2], chan_b), 5_000_000),
701                         0x0e => send_payment!(nodes[2], (&nodes[1], chan_b), (&nodes[0], chan_a), 5_000_000),
702                         0x0f => {
703                                 if !chan_a_disconnected {
704                                         nodes[0].peer_disconnected(&nodes[1].get_our_node_id(), false);
705                                         nodes[1].peer_disconnected(&nodes[0].get_our_node_id(), false);
706                                         chan_a_disconnected = true;
707                                         drain_msg_events_on_disconnect!(0);
708                                 }
709                         },
710                         0x10 => {
711                                 if !chan_b_disconnected {
712                                         nodes[1].peer_disconnected(&nodes[2].get_our_node_id(), false);
713                                         nodes[2].peer_disconnected(&nodes[1].get_our_node_id(), false);
714                                         chan_b_disconnected = true;
715                                         drain_msg_events_on_disconnect!(2);
716                                 }
717                         },
718                         0x11 => {
719                                 if chan_a_disconnected {
720                                         nodes[0].peer_connected(&nodes[1].get_our_node_id(), &Init { features: InitFeatures::empty() });
721                                         nodes[1].peer_connected(&nodes[0].get_our_node_id(), &Init { features: InitFeatures::empty() });
722                                         chan_a_disconnected = false;
723                                 }
724                         },
725                         0x12 => {
726                                 if chan_b_disconnected {
727                                         nodes[1].peer_connected(&nodes[2].get_our_node_id(), &Init { features: InitFeatures::empty() });
728                                         nodes[2].peer_connected(&nodes[1].get_our_node_id(), &Init { features: InitFeatures::empty() });
729                                         chan_b_disconnected = false;
730                                 }
731                         },
732                         0x13 => process_msg_events!(0, true),
733                         0x14 => process_msg_events!(0, false),
734                         0x15 => process_events!(0, true),
735                         0x16 => process_events!(0, false),
736                         0x17 => process_msg_events!(1, true),
737                         0x18 => process_msg_events!(1, false),
738                         0x19 => process_events!(1, true),
739                         0x1a => process_events!(1, false),
740                         0x1b => process_msg_events!(2, true),
741                         0x1c => process_msg_events!(2, false),
742                         0x1d => process_events!(2, true),
743                         0x1e => process_events!(2, false),
744                         0x1f => {
745                                 if !chan_a_disconnected {
746                                         nodes[1].peer_disconnected(&nodes[0].get_our_node_id(), false);
747                                         chan_a_disconnected = true;
748                                         drain_msg_events_on_disconnect!(0);
749                                 }
750                                 let (new_node_a, new_monitor_a) = reload_node!(node_a_ser, 0, monitor_a);
751                                 node_a = Arc::new(new_node_a);
752                                 nodes[0] = node_a.clone();
753                                 monitor_a = new_monitor_a;
754                         },
755                         0x20 => {
756                                 if !chan_a_disconnected {
757                                         nodes[0].peer_disconnected(&nodes[1].get_our_node_id(), false);
758                                         chan_a_disconnected = true;
759                                         nodes[0].get_and_clear_pending_msg_events();
760                                         ba_events.clear();
761                                 }
762                                 if !chan_b_disconnected {
763                                         nodes[2].peer_disconnected(&nodes[1].get_our_node_id(), false);
764                                         chan_b_disconnected = true;
765                                         nodes[2].get_and_clear_pending_msg_events();
766                                         bc_events.clear();
767                                 }
768                                 let (new_node_b, new_monitor_b) = reload_node!(node_b_ser, 1, monitor_b);
769                                 node_b = Arc::new(new_node_b);
770                                 nodes[1] = node_b.clone();
771                                 monitor_b = new_monitor_b;
772                         },
773                         0x21 => {
774                                 if !chan_b_disconnected {
775                                         nodes[1].peer_disconnected(&nodes[2].get_our_node_id(), false);
776                                         chan_b_disconnected = true;
777                                         drain_msg_events_on_disconnect!(2);
778                                 }
779                                 let (new_node_c, new_monitor_c) = reload_node!(node_c_ser, 2, monitor_c);
780                                 node_c = Arc::new(new_node_c);
781                                 nodes[2] = node_c.clone();
782                                 monitor_c = new_monitor_c;
783                         },
784                         0x22 => send_payment_with_secret!(nodes[0], (&nodes[1], chan_a), (&nodes[2], chan_b)),
785                         0x23 => send_payment_with_secret!(nodes[2], (&nodes[1], chan_b), (&nodes[0], chan_a)),
786                         0x25 => send_payment!(nodes[0], (&nodes[1], chan_a), 10),
787                         0x26 => send_payment!(nodes[1], (&nodes[0], chan_a), 10),
788                         0x27 => send_payment!(nodes[1], (&nodes[2], chan_b), 10),
789                         0x28 => send_payment!(nodes[2], (&nodes[1], chan_b), 10),
790                         0x29 => send_payment!(nodes[0], (&nodes[1], chan_a), (&nodes[2], chan_b), 10),
791                         0x2a => send_payment!(nodes[2], (&nodes[1], chan_b), (&nodes[0], chan_a), 10),
792                         0x2b => send_payment!(nodes[0], (&nodes[1], chan_a), 1_000),
793                         0x2c => send_payment!(nodes[1], (&nodes[0], chan_a), 1_000),
794                         0x2d => send_payment!(nodes[1], (&nodes[2], chan_b), 1_000),
795                         0x2e => send_payment!(nodes[2], (&nodes[1], chan_b), 1_000),
796                         0x2f => send_payment!(nodes[0], (&nodes[1], chan_a), (&nodes[2], chan_b), 1_000),
797                         0x30 => send_payment!(nodes[2], (&nodes[1], chan_b), (&nodes[0], chan_a), 1_000),
798                         0x31 => send_payment!(nodes[0], (&nodes[1], chan_a), 100_000),
799                         0x32 => send_payment!(nodes[1], (&nodes[0], chan_a), 100_000),
800                         0x33 => send_payment!(nodes[1], (&nodes[2], chan_b), 100_000),
801                         0x34 => send_payment!(nodes[2], (&nodes[1], chan_b), 100_000),
802                         0x35 => send_payment!(nodes[0], (&nodes[1], chan_a), (&nodes[2], chan_b), 100_000),
803                         0x36 => send_payment!(nodes[2], (&nodes[1], chan_b), (&nodes[0], chan_a), 100_000),
804                         // 0x24 defined above
805                         _ => test_return!(),
806                 }
807
808                 node_a_ser.0.clear();
809                 nodes[0].write(&mut node_a_ser).unwrap();
810                 monitor_a.should_update_manager.store(false, atomic::Ordering::Relaxed);
811                 node_b_ser.0.clear();
812                 nodes[1].write(&mut node_b_ser).unwrap();
813                 monitor_b.should_update_manager.store(false, atomic::Ordering::Relaxed);
814                 node_c_ser.0.clear();
815                 nodes[2].write(&mut node_c_ser).unwrap();
816                 monitor_c.should_update_manager.store(false, atomic::Ordering::Relaxed);
817         }
818 }
819
820 pub fn chanmon_consistency_test<Out: test_logger::Output>(data: &[u8], out: Out) {
821         do_test(data, out);
822 }
823
824 #[no_mangle]
825 pub extern "C" fn chanmon_consistency_run(data: *const u8, datalen: usize) {
826         do_test(unsafe { std::slice::from_raw_parts(data, datalen) }, test_logger::DevNull{});
827 }