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