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