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