Merge pull request #1401 from TheBlueMatt/2022-02-0conf-round-two
[rust-lightning] / lightning / src / ln / functional_test_utils.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 //! A bunch of useful utilities for building networks of nodes and exchanging messages between
11 //! nodes for functional tests.
12
13 use chain::{BestBlock, Confirm, Listen, Watch, keysinterface::KeysInterface};
14 use chain::channelmonitor::ChannelMonitor;
15 use chain::transaction::OutPoint;
16 use ln::{PaymentPreimage, PaymentHash, PaymentSecret};
17 use ln::channelmanager::{ChainParameters, ChannelManager, ChannelManagerReadArgs, RAACommitmentOrder, PaymentSendFailure, PaymentId, MIN_CLTV_EXPIRY_DELTA};
18 use routing::network_graph::{NetGraphMsgHandler, NetworkGraph};
19 use routing::router::{PaymentParameters, Route, get_route};
20 use ln::features::{InitFeatures, InvoiceFeatures};
21 use ln::msgs;
22 use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler};
23 use util::enforcing_trait_impls::EnforcingSigner;
24 use util::scid_utils;
25 use util::test_utils;
26 use util::test_utils::{panicking, TestChainMonitor};
27 use util::events::{Event, MessageSendEvent, MessageSendEventsProvider, PaymentPurpose};
28 use util::errors::APIError;
29 use util::config::UserConfig;
30 use util::ser::{ReadableArgs, Writeable, Readable};
31
32 use bitcoin::blockdata::block::{Block, BlockHeader};
33 use bitcoin::blockdata::constants::genesis_block;
34 use bitcoin::blockdata::transaction::{Transaction, TxOut};
35 use bitcoin::network::constants::Network;
36
37 use bitcoin::hash_types::BlockHash;
38
39 use bitcoin::secp256k1::PublicKey;
40
41 use io;
42 use prelude::*;
43 use core::cell::RefCell;
44 use alloc::rc::Rc;
45 use sync::{Arc, Mutex};
46 use core::mem;
47
48 pub const CHAN_CONFIRM_DEPTH: u32 = 10;
49
50 /// Mine the given transaction in the next block and then mine CHAN_CONFIRM_DEPTH - 1 blocks on
51 /// top, giving the given transaction CHAN_CONFIRM_DEPTH confirmations.
52 ///
53 /// Returns the SCID a channel confirmed in the given transaction will have, assuming the funding
54 /// output is the 1st output in the transaction.
55 pub fn confirm_transaction<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, tx: &Transaction) -> u64 {
56         let scid = confirm_transaction_at(node, tx, node.best_block_info().1 + 1);
57         connect_blocks(node, CHAN_CONFIRM_DEPTH - 1);
58         scid
59 }
60 /// Mine a signle block containing the given transaction
61 pub fn mine_transaction<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, tx: &Transaction) {
62         let height = node.best_block_info().1 + 1;
63         confirm_transaction_at(node, tx, height);
64 }
65 /// Mine the given transaction at the given height, mining blocks as required to build to that
66 /// height
67 ///
68 /// Returns the SCID a channel confirmed in the given transaction will have, assuming the funding
69 /// output is the 1st output in the transaction.
70 pub fn confirm_transaction_at<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, tx: &Transaction, conf_height: u32) -> u64 {
71         let first_connect_height = node.best_block_info().1 + 1;
72         assert!(first_connect_height <= conf_height);
73         if conf_height > first_connect_height {
74                 connect_blocks(node, conf_height - first_connect_height);
75         }
76         let mut block = Block {
77                 header: BlockHeader { version: 0x20000000, prev_blockhash: node.best_block_hash(), merkle_root: Default::default(), time: conf_height, bits: 42, nonce: 42 },
78                 txdata: Vec::new(),
79         };
80         for _ in 0..*node.network_chan_count.borrow() { // Make sure we don't end up with channels at the same short id by offsetting by chan_count
81                 block.txdata.push(Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() });
82         }
83         block.txdata.push(tx.clone());
84         connect_block(node, &block);
85         scid_utils::scid_from_parts(conf_height as u64, block.txdata.len() as u64 - 1, 0).unwrap()
86 }
87
88 /// The possible ways we may notify a ChannelManager of a new block
89 #[derive(Clone, Copy, Debug, PartialEq)]
90 pub enum ConnectStyle {
91         /// Calls `best_block_updated` first, detecting transactions in the block only after receiving
92         /// the header and height information.
93         BestBlockFirst,
94         /// The same as `BestBlockFirst`, however when we have multiple blocks to connect, we only
95         /// make a single `best_block_updated` call.
96         BestBlockFirstSkippingBlocks,
97         /// The same as `BestBlockFirst` when connecting blocks. During disconnection only
98         /// `transaction_unconfirmed` is called.
99         BestBlockFirstReorgsOnlyTip,
100         /// Calls `transactions_confirmed` first, detecting transactions in the block before updating
101         /// the header and height information.
102         TransactionsFirst,
103         /// The same as `TransactionsFirst`, however when we have multiple blocks to connect, we only
104         /// make a single `best_block_updated` call.
105         TransactionsFirstSkippingBlocks,
106         /// The same as `TransactionsFirst` when connecting blocks. During disconnection only
107         /// `transaction_unconfirmed` is called.
108         TransactionsFirstReorgsOnlyTip,
109         /// Provides the full block via the `chain::Listen` interface. In the current code this is
110         /// equivalent to `TransactionsFirst` with some additional assertions.
111         FullBlockViaListen,
112 }
113
114 impl ConnectStyle {
115         fn random_style() -> ConnectStyle {
116                 #[cfg(feature = "std")] {
117                         use core::hash::{BuildHasher, Hasher};
118                         // Get a random value using the only std API to do so - the DefaultHasher
119                         let rand_val = std::collections::hash_map::RandomState::new().build_hasher().finish();
120                         let res = match rand_val % 7 {
121                                 0 => ConnectStyle::BestBlockFirst,
122                                 1 => ConnectStyle::BestBlockFirstSkippingBlocks,
123                                 2 => ConnectStyle::BestBlockFirstReorgsOnlyTip,
124                                 3 => ConnectStyle::TransactionsFirst,
125                                 4 => ConnectStyle::TransactionsFirstSkippingBlocks,
126                                 5 => ConnectStyle::TransactionsFirstReorgsOnlyTip,
127                                 6 => ConnectStyle::FullBlockViaListen,
128                                 _ => unreachable!(),
129                         };
130                         eprintln!("Using Block Connection Style: {:?}", res);
131                         res
132                 }
133                 #[cfg(not(feature = "std"))] {
134                         ConnectStyle::FullBlockViaListen
135                 }
136         }
137 }
138
139 pub fn connect_blocks<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, depth: u32) -> BlockHash {
140         let skip_intermediaries = match *node.connect_style.borrow() {
141                 ConnectStyle::BestBlockFirstSkippingBlocks|ConnectStyle::TransactionsFirstSkippingBlocks|
142                         ConnectStyle::BestBlockFirstReorgsOnlyTip|ConnectStyle::TransactionsFirstReorgsOnlyTip => true,
143                 _ => false,
144         };
145
146         let height = node.best_block_info().1 + 1;
147         let mut block = Block {
148                 header: BlockHeader { version: 0x2000000, prev_blockhash: node.best_block_hash(), merkle_root: Default::default(), time: height, bits: 42, nonce: 42 },
149                 txdata: vec![],
150         };
151         assert!(depth >= 1);
152         for i in 1..depth {
153                 let prev_blockhash = block.header.block_hash();
154                 do_connect_block(node, block, skip_intermediaries);
155                 block = Block {
156                         header: BlockHeader { version: 0x20000000, prev_blockhash, merkle_root: Default::default(), time: height + i, bits: 42, nonce: 42 },
157                         txdata: vec![],
158                 };
159         }
160         let hash = block.header.block_hash();
161         do_connect_block(node, block, false);
162         hash
163 }
164
165 pub fn connect_block<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, block: &Block) {
166         do_connect_block(node, block.clone(), false);
167 }
168
169 fn call_claimable_balances<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>) {
170         // Ensure `get_claimable_balances`' self-tests never panic
171         for funding_outpoint in node.chain_monitor.chain_monitor.list_monitors() {
172                 node.chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances();
173         }
174 }
175
176 fn do_connect_block<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, block: Block, skip_intermediaries: bool) {
177         call_claimable_balances(node);
178         let height = node.best_block_info().1 + 1;
179         #[cfg(feature = "std")] {
180                 eprintln!("Connecting block using Block Connection Style: {:?}", *node.connect_style.borrow());
181         }
182         if !skip_intermediaries {
183                 let txdata: Vec<_> = block.txdata.iter().enumerate().collect();
184                 match *node.connect_style.borrow() {
185                         ConnectStyle::BestBlockFirst|ConnectStyle::BestBlockFirstSkippingBlocks|ConnectStyle::BestBlockFirstReorgsOnlyTip => {
186                                 node.chain_monitor.chain_monitor.best_block_updated(&block.header, height);
187                                 call_claimable_balances(node);
188                                 node.chain_monitor.chain_monitor.transactions_confirmed(&block.header, &txdata, height);
189                                 node.node.best_block_updated(&block.header, height);
190                                 node.node.transactions_confirmed(&block.header, &txdata, height);
191                         },
192                         ConnectStyle::TransactionsFirst|ConnectStyle::TransactionsFirstSkippingBlocks|ConnectStyle::TransactionsFirstReorgsOnlyTip => {
193                                 node.chain_monitor.chain_monitor.transactions_confirmed(&block.header, &txdata, height);
194                                 call_claimable_balances(node);
195                                 node.chain_monitor.chain_monitor.best_block_updated(&block.header, height);
196                                 node.node.transactions_confirmed(&block.header, &txdata, height);
197                                 node.node.best_block_updated(&block.header, height);
198                         },
199                         ConnectStyle::FullBlockViaListen => {
200                                 node.chain_monitor.chain_monitor.block_connected(&block, height);
201                                 node.node.block_connected(&block, height);
202                         }
203                 }
204         }
205         call_claimable_balances(node);
206         node.node.test_process_background_events();
207         node.blocks.lock().unwrap().push((block, height));
208 }
209
210 pub fn disconnect_blocks<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, count: u32) {
211         call_claimable_balances(node);
212         #[cfg(feature = "std")] {
213                 eprintln!("Disconnecting {} blocks using Block Connection Style: {:?}", count, *node.connect_style.borrow());
214         }
215         for i in 0..count {
216                 let orig = node.blocks.lock().unwrap().pop().unwrap();
217                 assert!(orig.1 > 0); // Cannot disconnect genesis
218                 let prev = node.blocks.lock().unwrap().last().unwrap().clone();
219
220                 match *node.connect_style.borrow() {
221                         ConnectStyle::FullBlockViaListen => {
222                                 node.chain_monitor.chain_monitor.block_disconnected(&orig.0.header, orig.1);
223                                 Listen::block_disconnected(node.node, &orig.0.header, orig.1);
224                         },
225                         ConnectStyle::BestBlockFirstSkippingBlocks|ConnectStyle::TransactionsFirstSkippingBlocks => {
226                                 if i == count - 1 {
227                                         node.chain_monitor.chain_monitor.best_block_updated(&prev.0.header, prev.1);
228                                         node.node.best_block_updated(&prev.0.header, prev.1);
229                                 }
230                         },
231                         ConnectStyle::BestBlockFirstReorgsOnlyTip|ConnectStyle::TransactionsFirstReorgsOnlyTip => {
232                                 for tx in orig.0.txdata {
233                                         node.chain_monitor.chain_monitor.transaction_unconfirmed(&tx.txid());
234                                         node.node.transaction_unconfirmed(&tx.txid());
235                                 }
236                         },
237                         _ => {
238                                 node.chain_monitor.chain_monitor.best_block_updated(&prev.0.header, prev.1);
239                                 node.node.best_block_updated(&prev.0.header, prev.1);
240                         },
241                 }
242                 call_claimable_balances(node);
243         }
244 }
245
246 pub fn disconnect_all_blocks<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>) {
247         let count = node.blocks.lock().unwrap().len() as u32 - 1;
248         disconnect_blocks(node, count);
249 }
250
251 pub struct TestChanMonCfg {
252         pub tx_broadcaster: test_utils::TestBroadcaster,
253         pub fee_estimator: test_utils::TestFeeEstimator,
254         pub chain_source: test_utils::TestChainSource,
255         pub persister: test_utils::TestPersister,
256         pub logger: test_utils::TestLogger,
257         pub keys_manager: test_utils::TestKeysInterface,
258         pub network_graph: NetworkGraph,
259 }
260
261 pub struct NodeCfg<'a> {
262         pub chain_source: &'a test_utils::TestChainSource,
263         pub tx_broadcaster: &'a test_utils::TestBroadcaster,
264         pub fee_estimator: &'a test_utils::TestFeeEstimator,
265         pub chain_monitor: test_utils::TestChainMonitor<'a>,
266         pub keys_manager: &'a test_utils::TestKeysInterface,
267         pub logger: &'a test_utils::TestLogger,
268         pub network_graph: &'a NetworkGraph,
269         pub node_seed: [u8; 32],
270         pub features: InitFeatures,
271 }
272
273 pub struct Node<'a, 'b: 'a, 'c: 'b> {
274         pub chain_source: &'c test_utils::TestChainSource,
275         pub tx_broadcaster: &'c test_utils::TestBroadcaster,
276         pub chain_monitor: &'b test_utils::TestChainMonitor<'c>,
277         pub keys_manager: &'b test_utils::TestKeysInterface,
278         pub node: &'a ChannelManager<EnforcingSigner, &'b TestChainMonitor<'c>, &'c test_utils::TestBroadcaster, &'b test_utils::TestKeysInterface, &'c test_utils::TestFeeEstimator, &'c test_utils::TestLogger>,
279         pub network_graph: &'c NetworkGraph,
280         pub net_graph_msg_handler: NetGraphMsgHandler<&'c NetworkGraph, &'c test_utils::TestChainSource, &'c test_utils::TestLogger>,
281         pub node_seed: [u8; 32],
282         pub network_payment_count: Rc<RefCell<u8>>,
283         pub network_chan_count: Rc<RefCell<u32>>,
284         pub logger: &'c test_utils::TestLogger,
285         pub blocks: Arc<Mutex<Vec<(Block, u32)>>>,
286         pub connect_style: Rc<RefCell<ConnectStyle>>,
287 }
288 impl<'a, 'b, 'c> Node<'a, 'b, 'c> {
289         pub fn best_block_hash(&self) -> BlockHash {
290                 self.blocks.lock().unwrap().last().unwrap().0.block_hash()
291         }
292         pub fn best_block_info(&self) -> (BlockHash, u32) {
293                 self.blocks.lock().unwrap().last().map(|(a, b)| (a.block_hash(), *b)).unwrap()
294         }
295         pub fn get_block_header(&self, height: u32) -> BlockHeader {
296                 self.blocks.lock().unwrap()[height as usize].0.header
297         }
298 }
299
300 impl<'a, 'b, 'c> Drop for Node<'a, 'b, 'c> {
301         fn drop(&mut self) {
302                 if !panicking() {
303                         // Check that we processed all pending events
304                         assert!(self.node.get_and_clear_pending_msg_events().is_empty());
305                         assert!(self.node.get_and_clear_pending_events().is_empty());
306                         assert!(self.chain_monitor.added_monitors.lock().unwrap().is_empty());
307
308                         // Check that if we serialize the Router, we can deserialize it again.
309                         {
310                                 let mut w = test_utils::TestVecWriter(Vec::new());
311                                 self.network_graph.write(&mut w).unwrap();
312                                 let network_graph_deser = <NetworkGraph>::read(&mut io::Cursor::new(&w.0)).unwrap();
313                                 assert!(network_graph_deser == *self.network_graph);
314                                 let net_graph_msg_handler = NetGraphMsgHandler::new(
315                                         &network_graph_deser, Some(self.chain_source), self.logger
316                                 );
317                                 let mut chan_progress = 0;
318                                 loop {
319                                         let orig_announcements = self.net_graph_msg_handler.get_next_channel_announcements(chan_progress, 255);
320                                         let deserialized_announcements = net_graph_msg_handler.get_next_channel_announcements(chan_progress, 255);
321                                         assert!(orig_announcements == deserialized_announcements);
322                                         chan_progress = match orig_announcements.last() {
323                                                 Some(announcement) => announcement.0.contents.short_channel_id + 1,
324                                                 None => break,
325                                         };
326                                 }
327                                 let mut node_progress = None;
328                                 loop {
329                                         let orig_announcements = self.net_graph_msg_handler.get_next_node_announcements(node_progress.as_ref(), 255);
330                                         let deserialized_announcements = net_graph_msg_handler.get_next_node_announcements(node_progress.as_ref(), 255);
331                                         assert!(orig_announcements == deserialized_announcements);
332                                         node_progress = match orig_announcements.last() {
333                                                 Some(announcement) => Some(announcement.contents.node_id),
334                                                 None => break,
335                                         };
336                                 }
337                         }
338
339                         // Check that if we serialize and then deserialize all our channel monitors we get the
340                         // same set of outputs to watch for on chain as we have now. Note that if we write
341                         // tests that fully close channels and remove the monitors at some point this may break.
342                         let feeest = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
343                         let mut deserialized_monitors = Vec::new();
344                         {
345                                 for outpoint in self.chain_monitor.chain_monitor.list_monitors() {
346                                         let mut w = test_utils::TestVecWriter(Vec::new());
347                                         self.chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut w).unwrap();
348                                         let (_, deserialized_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
349                                                 &mut io::Cursor::new(&w.0), self.keys_manager).unwrap();
350                                         deserialized_monitors.push(deserialized_monitor);
351                                 }
352                         }
353
354                         // Before using all the new monitors to check the watch outpoints, use the full set of
355                         // them to ensure we can write and reload our ChannelManager.
356                         {
357                                 let mut channel_monitors = HashMap::new();
358                                 for monitor in deserialized_monitors.iter_mut() {
359                                         channel_monitors.insert(monitor.get_funding_txo().0, monitor);
360                                 }
361
362                                 let mut w = test_utils::TestVecWriter(Vec::new());
363                                 self.node.write(&mut w).unwrap();
364                                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut io::Cursor::new(w.0), ChannelManagerReadArgs {
365                                         default_config: *self.node.get_current_default_configuration(),
366                                         keys_manager: self.keys_manager,
367                                         fee_estimator: &test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
368                                         chain_monitor: self.chain_monitor,
369                                         tx_broadcaster: &test_utils::TestBroadcaster {
370                                                 txn_broadcasted: Mutex::new(self.tx_broadcaster.txn_broadcasted.lock().unwrap().clone()),
371                                                 blocks: Arc::new(Mutex::new(self.tx_broadcaster.blocks.lock().unwrap().clone())),
372                                         },
373                                         logger: &self.logger,
374                                         channel_monitors,
375                                 }).unwrap();
376                         }
377
378                         let persister = test_utils::TestPersister::new();
379                         let broadcaster = test_utils::TestBroadcaster {
380                                 txn_broadcasted: Mutex::new(self.tx_broadcaster.txn_broadcasted.lock().unwrap().clone()),
381                                 blocks: Arc::new(Mutex::new(self.tx_broadcaster.blocks.lock().unwrap().clone())),
382                         };
383                         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
384                         let chain_monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &broadcaster, &self.logger, &feeest, &persister, &self.keys_manager);
385                         for deserialized_monitor in deserialized_monitors.drain(..) {
386                                 if let Err(_) = chain_monitor.watch_channel(deserialized_monitor.get_funding_txo().0, deserialized_monitor) {
387                                         panic!();
388                                 }
389                         }
390                         assert_eq!(*chain_source.watched_txn.lock().unwrap(), *self.chain_source.watched_txn.lock().unwrap());
391                         assert_eq!(*chain_source.watched_outputs.lock().unwrap(), *self.chain_source.watched_outputs.lock().unwrap());
392                 }
393         }
394 }
395
396 pub fn create_chan_between_nodes<'a, 'b, 'c, 'd>(node_a: &'a Node<'b, 'c, 'd>, node_b: &'a Node<'b, 'c, 'd>, a_flags: InitFeatures, b_flags: InitFeatures) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
397         create_chan_between_nodes_with_value(node_a, node_b, 100000, 10001, a_flags, b_flags)
398 }
399
400 pub fn create_chan_between_nodes_with_value<'a, 'b, 'c, 'd>(node_a: &'a Node<'b, 'c, 'd>, node_b: &'a Node<'b, 'c, 'd>, channel_value: u64, push_msat: u64, a_flags: InitFeatures, b_flags: InitFeatures) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
401         let (funding_locked, channel_id, tx) = create_chan_between_nodes_with_value_a(node_a, node_b, channel_value, push_msat, a_flags, b_flags);
402         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(node_a, node_b, &funding_locked);
403         (announcement, as_update, bs_update, channel_id, tx)
404 }
405
406 #[macro_export]
407 /// Gets an RAA and CS which were sent in response to a commitment update
408 macro_rules! get_revoke_commit_msgs {
409         ($node: expr, $node_id: expr) => {
410                 {
411                         use $crate::util::events::MessageSendEvent;
412                         let events = $node.node.get_and_clear_pending_msg_events();
413                         assert_eq!(events.len(), 2);
414                         (match events[0] {
415                                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
416                                         assert_eq!(*node_id, $node_id);
417                                         (*msg).clone()
418                                 },
419                                 _ => panic!("Unexpected event"),
420                         }, match events[1] {
421                                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
422                                         assert_eq!(*node_id, $node_id);
423                                         assert!(updates.update_add_htlcs.is_empty());
424                                         assert!(updates.update_fulfill_htlcs.is_empty());
425                                         assert!(updates.update_fail_htlcs.is_empty());
426                                         assert!(updates.update_fail_malformed_htlcs.is_empty());
427                                         assert!(updates.update_fee.is_none());
428                                         updates.commitment_signed.clone()
429                                 },
430                                 _ => panic!("Unexpected event"),
431                         })
432                 }
433         }
434 }
435
436 /// Get an specific event message from the pending events queue.
437 #[macro_export]
438 macro_rules! get_event_msg {
439         ($node: expr, $event_type: path, $node_id: expr) => {
440                 {
441                         let events = $node.node.get_and_clear_pending_msg_events();
442                         assert_eq!(events.len(), 1);
443                         match events[0] {
444                                 $event_type { ref node_id, ref msg } => {
445                                         assert_eq!(*node_id, $node_id);
446                                         (*msg).clone()
447                                 },
448                                 _ => panic!("Unexpected event"),
449                         }
450                 }
451         }
452 }
453
454 /// Get an error message from the pending events queue.
455 #[macro_export]
456 macro_rules! get_err_msg {
457         ($node: expr, $node_id: expr) => {
458                 {
459                         let events = $node.node.get_and_clear_pending_msg_events();
460                         assert_eq!(events.len(), 1);
461                         match events[0] {
462                                 $crate::util::events::MessageSendEvent::HandleError {
463                                         action: $crate::ln::msgs::ErrorAction::SendErrorMessage { ref msg }, ref node_id
464                                 } => {
465                                         assert_eq!(*node_id, $node_id);
466                                         (*msg).clone()
467                                 },
468                                 _ => panic!("Unexpected event"),
469                         }
470                 }
471         }
472 }
473
474 /// Get a specific event from the pending events queue.
475 #[macro_export]
476 macro_rules! get_event {
477         ($node: expr, $event_type: path) => {
478                 {
479                         let mut events = $node.node.get_and_clear_pending_events();
480                         assert_eq!(events.len(), 1);
481                         let ev = events.pop().unwrap();
482                         match ev {
483                                 $event_type { .. } => {
484                                         ev
485                                 },
486                                 _ => panic!("Unexpected event"),
487                         }
488                 }
489         }
490 }
491
492 #[macro_export]
493 /// Gets an UpdateHTLCs MessageSendEvent
494 macro_rules! get_htlc_update_msgs {
495         ($node: expr, $node_id: expr) => {
496                 {
497                         let events = $node.node.get_and_clear_pending_msg_events();
498                         assert_eq!(events.len(), 1);
499                         match events[0] {
500                                 $crate::util::events::MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
501                                         assert_eq!(*node_id, $node_id);
502                                         (*updates).clone()
503                                 },
504                                 _ => panic!("Unexpected event"),
505                         }
506                 }
507         }
508 }
509
510 #[cfg(test)]
511 macro_rules! get_channel_ref {
512         ($node: expr, $lock: ident, $channel_id: expr) => {
513                 {
514                         $lock = $node.node.channel_state.lock().unwrap();
515                         $lock.by_id.get_mut(&$channel_id).unwrap()
516                 }
517         }
518 }
519
520 #[cfg(test)]
521 macro_rules! get_feerate {
522         ($node: expr, $channel_id: expr) => {
523                 {
524                         let mut lock;
525                         let chan = get_channel_ref!($node, lock, $channel_id);
526                         chan.get_feerate()
527                 }
528         }
529 }
530
531 #[cfg(test)]
532 macro_rules! get_opt_anchors {
533         ($node: expr, $channel_id: expr) => {
534                 {
535                         let mut lock;
536                         let chan = get_channel_ref!($node, lock, $channel_id);
537                         chan.opt_anchors()
538                 }
539         }
540 }
541
542 /// Returns a channel monitor given a channel id, making some naive assumptions
543 #[macro_export]
544 macro_rules! get_monitor {
545         ($node: expr, $channel_id: expr) => {
546                 {
547                         use bitcoin::hashes::Hash;
548                         let mut monitor = None;
549                         // Assume funding vout is either 0 or 1 blindly
550                         for index in 0..2 {
551                                 if let Ok(mon) = $node.chain_monitor.chain_monitor.get_monitor(
552                                         $crate::chain::transaction::OutPoint {
553                                                 txid: bitcoin::Txid::from_slice(&$channel_id[..]).unwrap(), index
554                                         })
555                                 {
556                                         monitor = Some(mon);
557                                         break;
558                                 }
559                         }
560                         monitor.unwrap()
561                 }
562         }
563 }
564
565 /// Returns any local commitment transactions for the channel.
566 #[macro_export]
567 macro_rules! get_local_commitment_txn {
568         ($node: expr, $channel_id: expr) => {
569                 {
570                         $crate::get_monitor!($node, $channel_id).unsafe_get_latest_holder_commitment_txn(&$node.logger)
571                 }
572         }
573 }
574
575 /// Check the error from attempting a payment.
576 #[macro_export]
577 macro_rules! unwrap_send_err {
578         ($res: expr, $all_failed: expr, $type: pat, $check: expr) => {
579                 match &$res {
580                         &Err(PaymentSendFailure::AllFailedRetrySafe(ref fails)) if $all_failed => {
581                                 assert_eq!(fails.len(), 1);
582                                 match fails[0] {
583                                         $type => { $check },
584                                         _ => panic!(),
585                                 }
586                         },
587                         &Err(PaymentSendFailure::PartialFailure { ref results, .. }) if !$all_failed => {
588                                 assert_eq!(results.len(), 1);
589                                 match results[0] {
590                                         Err($type) => { $check },
591                                         _ => panic!(),
592                                 }
593                         },
594                         _ => panic!(),
595                 }
596         }
597 }
598
599 /// Check whether N channel monitor(s) have been added.
600 #[macro_export]
601 macro_rules! check_added_monitors {
602         ($node: expr, $count: expr) => {
603                 {
604                         let mut added_monitors = $node.chain_monitor.added_monitors.lock().unwrap();
605                         assert_eq!(added_monitors.len(), $count);
606                         added_monitors.clear();
607                 }
608         }
609 }
610
611 pub fn create_funding_transaction<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, expected_counterparty_node_id: &PublicKey, expected_chan_value: u64, expected_user_chan_id: u64) -> ([u8; 32], Transaction, OutPoint) {
612         let chan_id = *node.network_chan_count.borrow();
613
614         let events = node.node.get_and_clear_pending_events();
615         assert_eq!(events.len(), 1);
616         match events[0] {
617                 Event::FundingGenerationReady { ref temporary_channel_id, ref counterparty_node_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
618                         assert_eq!(counterparty_node_id, expected_counterparty_node_id);
619                         assert_eq!(*channel_value_satoshis, expected_chan_value);
620                         assert_eq!(user_channel_id, expected_user_chan_id);
621
622                         let tx = Transaction { version: chan_id as i32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
623                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
624                         }]};
625                         let funding_outpoint = OutPoint { txid: tx.txid(), index: 0 };
626                         (*temporary_channel_id, tx, funding_outpoint)
627                 },
628                 _ => panic!("Unexpected event"),
629         }
630 }
631 pub fn sign_funding_transaction<'a, 'b, 'c>(node_a: &Node<'a, 'b, 'c>, node_b: &Node<'a, 'b, 'c>, channel_value: u64, expected_temporary_channel_id: [u8; 32]) -> Transaction {
632         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(node_a, &node_b.node.get_our_node_id(), channel_value, 42);
633         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
634
635         assert!(node_a.node.funding_transaction_generated(&temporary_channel_id, &node_b.node.get_our_node_id(), tx.clone()).is_ok());
636         check_added_monitors!(node_a, 0);
637
638         let funding_created_msg = get_event_msg!(node_a, MessageSendEvent::SendFundingCreated, node_b.node.get_our_node_id());
639         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
640         node_b.node.handle_funding_created(&node_a.node.get_our_node_id(), &funding_created_msg);
641         {
642                 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
643                 assert_eq!(added_monitors.len(), 1);
644                 assert_eq!(added_monitors[0].0, funding_output);
645                 added_monitors.clear();
646         }
647
648         node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id()));
649         {
650                 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
651                 assert_eq!(added_monitors.len(), 1);
652                 assert_eq!(added_monitors[0].0, funding_output);
653                 added_monitors.clear();
654         }
655
656         let events_4 = node_a.node.get_and_clear_pending_events();
657         assert_eq!(events_4.len(), 0);
658
659         assert_eq!(node_a.tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
660         assert_eq!(node_a.tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
661         node_a.tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
662
663         // Ensure that funding_transaction_generated is idempotent.
664         assert!(node_a.node.funding_transaction_generated(&temporary_channel_id, &node_b.node.get_our_node_id(), tx.clone()).is_err());
665         assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
666         check_added_monitors!(node_a, 0);
667
668         tx
669 }
670
671 pub fn create_chan_between_nodes_with_value_init<'a, 'b, 'c>(node_a: &Node<'a, 'b, 'c>, node_b: &Node<'a, 'b, 'c>, channel_value: u64, push_msat: u64, a_flags: InitFeatures, b_flags: InitFeatures) -> Transaction {
672         let create_chan_id = node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
673         let open_channel_msg = get_event_msg!(node_a, MessageSendEvent::SendOpenChannel, node_b.node.get_our_node_id());
674         assert_eq!(open_channel_msg.temporary_channel_id, create_chan_id);
675         node_b.node.handle_open_channel(&node_a.node.get_our_node_id(), a_flags, &open_channel_msg);
676         let accept_channel_msg = get_event_msg!(node_b, MessageSendEvent::SendAcceptChannel, node_a.node.get_our_node_id());
677         assert_eq!(accept_channel_msg.temporary_channel_id, create_chan_id);
678         node_a.node.handle_accept_channel(&node_b.node.get_our_node_id(), b_flags, &accept_channel_msg);
679
680         sign_funding_transaction(node_a, node_b, channel_value, create_chan_id)
681 }
682
683 pub fn create_chan_between_nodes_with_value_confirm_first<'a, 'b, 'c, 'd>(node_recv: &'a Node<'b, 'c, 'c>, node_conf: &'a Node<'b, 'c, 'd>, tx: &Transaction, conf_height: u32) {
684         confirm_transaction_at(node_conf, tx, conf_height);
685         connect_blocks(node_conf, CHAN_CONFIRM_DEPTH - 1);
686         node_recv.node.handle_funding_locked(&node_conf.node.get_our_node_id(), &get_event_msg!(node_conf, MessageSendEvent::SendFundingLocked, node_recv.node.get_our_node_id()));
687 }
688
689 pub fn create_chan_between_nodes_with_value_confirm_second<'a, 'b, 'c>(node_recv: &Node<'a, 'b, 'c>, node_conf: &Node<'a, 'b, 'c>) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32]) {
690         let channel_id;
691         let events_6 = node_conf.node.get_and_clear_pending_msg_events();
692         assert_eq!(events_6.len(), 3);
693         let announcement_sigs_idx = if let MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } = events_6[1] {
694                 assert_eq!(*node_id, node_recv.node.get_our_node_id());
695                 2
696         } else if let MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } = events_6[2] {
697                 assert_eq!(*node_id, node_recv.node.get_our_node_id());
698                 1
699         } else { panic!("Unexpected event: {:?}", events_6[1]); };
700         ((match events_6[0] {
701                 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
702                         channel_id = msg.channel_id.clone();
703                         assert_eq!(*node_id, node_recv.node.get_our_node_id());
704                         msg.clone()
705                 },
706                 _ => panic!("Unexpected event"),
707         }, match events_6[announcement_sigs_idx] {
708                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
709                         assert_eq!(*node_id, node_recv.node.get_our_node_id());
710                         msg.clone()
711                 },
712                 _ => panic!("Unexpected event"),
713         }), channel_id)
714 }
715
716 pub fn create_chan_between_nodes_with_value_confirm<'a, 'b, 'c, 'd>(node_a: &'a Node<'b, 'c, 'd>, node_b: &'a Node<'b, 'c, 'd>, tx: &Transaction) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32]) {
717         let conf_height = core::cmp::max(node_a.best_block_info().1 + 1, node_b.best_block_info().1 + 1);
718         create_chan_between_nodes_with_value_confirm_first(node_a, node_b, tx, conf_height);
719         confirm_transaction_at(node_a, tx, conf_height);
720         connect_blocks(node_a, CHAN_CONFIRM_DEPTH - 1);
721         create_chan_between_nodes_with_value_confirm_second(node_b, node_a)
722 }
723
724 pub fn create_chan_between_nodes_with_value_a<'a, 'b, 'c, 'd>(node_a: &'a Node<'b, 'c, 'd>, node_b: &'a Node<'b, 'c, 'd>, channel_value: u64, push_msat: u64, a_flags: InitFeatures, b_flags: InitFeatures) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32], Transaction) {
725         let tx = create_chan_between_nodes_with_value_init(node_a, node_b, channel_value, push_msat, a_flags, b_flags);
726         let (msgs, chan_id) = create_chan_between_nodes_with_value_confirm(node_a, node_b, &tx);
727         (msgs, chan_id, tx)
728 }
729
730 pub fn create_chan_between_nodes_with_value_b<'a, 'b, 'c>(node_a: &Node<'a, 'b, 'c>, node_b: &Node<'a, 'b, 'c>, as_funding_msgs: &(msgs::FundingLocked, msgs::AnnouncementSignatures)) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate) {
731         node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &as_funding_msgs.0);
732         let bs_announcement_sigs = get_event_msg!(node_b, MessageSendEvent::SendAnnouncementSignatures, node_a.node.get_our_node_id());
733         node_b.node.handle_announcement_signatures(&node_a.node.get_our_node_id(), &as_funding_msgs.1);
734
735         let events_7 = node_b.node.get_and_clear_pending_msg_events();
736         assert_eq!(events_7.len(), 1);
737         let (announcement, bs_update) = match events_7[0] {
738                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
739                         (msg, update_msg)
740                 },
741                 _ => panic!("Unexpected event"),
742         };
743
744         node_a.node.handle_announcement_signatures(&node_b.node.get_our_node_id(), &bs_announcement_sigs);
745         let events_8 = node_a.node.get_and_clear_pending_msg_events();
746         assert_eq!(events_8.len(), 1);
747         let as_update = match events_8[0] {
748                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
749                         assert!(*announcement == *msg);
750                         assert_eq!(update_msg.contents.short_channel_id, announcement.contents.short_channel_id);
751                         assert_eq!(update_msg.contents.short_channel_id, bs_update.contents.short_channel_id);
752                         update_msg
753                 },
754                 _ => panic!("Unexpected event"),
755         };
756
757         *node_a.network_chan_count.borrow_mut() += 1;
758
759         ((*announcement).clone(), (*as_update).clone(), (*bs_update).clone())
760 }
761
762 pub fn create_announced_chan_between_nodes<'a, 'b, 'c, 'd>(nodes: &'a Vec<Node<'b, 'c, 'd>>, a: usize, b: usize, a_flags: InitFeatures, b_flags: InitFeatures) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
763         create_announced_chan_between_nodes_with_value(nodes, a, b, 100000, 10001, a_flags, b_flags)
764 }
765
766 pub fn create_announced_chan_between_nodes_with_value<'a, 'b, 'c, 'd>(nodes: &'a Vec<Node<'b, 'c, 'd>>, a: usize, b: usize, channel_value: u64, push_msat: u64, a_flags: InitFeatures, b_flags: InitFeatures) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
767         let chan_announcement = create_chan_between_nodes_with_value(&nodes[a], &nodes[b], channel_value, push_msat, a_flags, b_flags);
768         update_nodes_with_chan_announce(nodes, a, b, &chan_announcement.0, &chan_announcement.1, &chan_announcement.2);
769         (chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
770 }
771
772 pub fn create_unannounced_chan_between_nodes_with_value<'a, 'b, 'c, 'd>(nodes: &'a Vec<Node<'b, 'c, 'd>>, a: usize, b: usize, channel_value: u64, push_msat: u64, a_flags: InitFeatures, b_flags: InitFeatures) -> (msgs::FundingLocked, Transaction) {
773         let mut no_announce_cfg = test_default_channel_config();
774         no_announce_cfg.channel_options.announced_channel = false;
775         nodes[a].node.create_channel(nodes[b].node.get_our_node_id(), channel_value, push_msat, 42, Some(no_announce_cfg)).unwrap();
776         let open_channel = get_event_msg!(nodes[a], MessageSendEvent::SendOpenChannel, nodes[b].node.get_our_node_id());
777         nodes[b].node.handle_open_channel(&nodes[a].node.get_our_node_id(), a_flags, &open_channel);
778         let accept_channel = get_event_msg!(nodes[b], MessageSendEvent::SendAcceptChannel, nodes[a].node.get_our_node_id());
779         nodes[a].node.handle_accept_channel(&nodes[b].node.get_our_node_id(), b_flags, &accept_channel);
780
781         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[a], &nodes[b].node.get_our_node_id(), channel_value, 42);
782         nodes[a].node.funding_transaction_generated(&temporary_channel_id, &nodes[b].node.get_our_node_id(), tx.clone()).unwrap();
783         nodes[b].node.handle_funding_created(&nodes[a].node.get_our_node_id(), &get_event_msg!(nodes[a], MessageSendEvent::SendFundingCreated, nodes[b].node.get_our_node_id()));
784         check_added_monitors!(nodes[b], 1);
785
786         let cs_funding_signed = get_event_msg!(nodes[b], MessageSendEvent::SendFundingSigned, nodes[a].node.get_our_node_id());
787         nodes[a].node.handle_funding_signed(&nodes[b].node.get_our_node_id(), &cs_funding_signed);
788         check_added_monitors!(nodes[a], 1);
789
790         let conf_height = core::cmp::max(nodes[a].best_block_info().1 + 1, nodes[b].best_block_info().1 + 1);
791         confirm_transaction_at(&nodes[a], &tx, conf_height);
792         connect_blocks(&nodes[a], CHAN_CONFIRM_DEPTH - 1);
793         confirm_transaction_at(&nodes[b], &tx, conf_height);
794         connect_blocks(&nodes[b], CHAN_CONFIRM_DEPTH - 1);
795         let as_funding_locked = get_event_msg!(nodes[a], MessageSendEvent::SendFundingLocked, nodes[b].node.get_our_node_id());
796         nodes[a].node.handle_funding_locked(&nodes[b].node.get_our_node_id(), &get_event_msg!(nodes[b], MessageSendEvent::SendFundingLocked, nodes[a].node.get_our_node_id()));
797         let as_update = get_event_msg!(nodes[a], MessageSendEvent::SendChannelUpdate, nodes[b].node.get_our_node_id());
798         nodes[b].node.handle_funding_locked(&nodes[a].node.get_our_node_id(), &as_funding_locked);
799         let bs_update = get_event_msg!(nodes[b], MessageSendEvent::SendChannelUpdate, nodes[a].node.get_our_node_id());
800
801         nodes[a].node.handle_channel_update(&nodes[b].node.get_our_node_id(), &bs_update);
802         nodes[b].node.handle_channel_update(&nodes[a].node.get_our_node_id(), &as_update);
803
804         let mut found_a = false;
805         for chan in nodes[a].node.list_usable_channels() {
806                 if chan.channel_id == as_funding_locked.channel_id {
807                         assert!(!found_a);
808                         found_a = true;
809                         assert!(!chan.is_public);
810                 }
811         }
812         assert!(found_a);
813
814         let mut found_b = false;
815         for chan in nodes[b].node.list_usable_channels() {
816                 if chan.channel_id == as_funding_locked.channel_id {
817                         assert!(!found_b);
818                         found_b = true;
819                         assert!(!chan.is_public);
820                 }
821         }
822         assert!(found_b);
823
824         (as_funding_locked, tx)
825 }
826
827 pub fn update_nodes_with_chan_announce<'a, 'b, 'c, 'd>(nodes: &'a Vec<Node<'b, 'c, 'd>>, a: usize, b: usize, ann: &msgs::ChannelAnnouncement, upd_1: &msgs::ChannelUpdate, upd_2: &msgs::ChannelUpdate) {
828         nodes[a].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
829         let a_events = nodes[a].node.get_and_clear_pending_msg_events();
830         assert!(a_events.len() >= 2);
831
832         // ann should be re-generated by broadcast_node_announcement - check that we have it.
833         let mut found_ann_1 = false;
834         for event in a_events.iter() {
835                 match event {
836                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
837                                 if msg == ann { found_ann_1 = true; }
838                         },
839                         MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
840                         _ => panic!("Unexpected event {:?}", event),
841                 }
842         }
843         assert!(found_ann_1);
844
845         let a_node_announcement = match a_events.last().unwrap() {
846                 MessageSendEvent::BroadcastNodeAnnouncement { ref msg } => {
847                         (*msg).clone()
848                 },
849                 _ => panic!("Unexpected event"),
850         };
851
852         nodes[b].node.broadcast_node_announcement([1, 1, 1], [1; 32], Vec::new());
853         let b_events = nodes[b].node.get_and_clear_pending_msg_events();
854         assert!(b_events.len() >= 2);
855
856         // ann should be re-generated by broadcast_node_announcement - check that we have it.
857         let mut found_ann_2 = false;
858         for event in b_events.iter() {
859                 match event {
860                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
861                                 if msg == ann { found_ann_2 = true; }
862                         },
863                         MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
864                         _ => panic!("Unexpected event"),
865                 }
866         }
867         assert!(found_ann_2);
868
869         let b_node_announcement = match b_events.last().unwrap() {
870                 MessageSendEvent::BroadcastNodeAnnouncement { ref msg } => {
871                         (*msg).clone()
872                 },
873                 _ => panic!("Unexpected event"),
874         };
875
876         for node in nodes {
877                 assert!(node.net_graph_msg_handler.handle_channel_announcement(ann).unwrap());
878                 node.net_graph_msg_handler.handle_channel_update(upd_1).unwrap();
879                 node.net_graph_msg_handler.handle_channel_update(upd_2).unwrap();
880                 node.net_graph_msg_handler.handle_node_announcement(&a_node_announcement).unwrap();
881                 node.net_graph_msg_handler.handle_node_announcement(&b_node_announcement).unwrap();
882
883                 // Note that channel_updates are also delivered to ChannelManagers to ensure we have
884                 // forwarding info for local channels even if its not accepted in the network graph.
885                 node.node.handle_channel_update(&nodes[a].node.get_our_node_id(), &upd_1);
886                 node.node.handle_channel_update(&nodes[b].node.get_our_node_id(), &upd_2);
887         }
888 }
889
890 #[macro_export]
891 macro_rules! check_spends {
892         ($tx: expr, $($spends_txn: expr),*) => {
893                 {
894                         $(
895                         for outp in $spends_txn.output.iter() {
896                                 assert!(outp.value >= outp.script_pubkey.dust_value().as_sat(), "Input tx output didn't meet dust limit");
897                         }
898                         )*
899                         for outp in $tx.output.iter() {
900                                 assert!(outp.value >= outp.script_pubkey.dust_value().as_sat(), "Spending tx output didn't meet dust limit");
901                         }
902                         let get_output = |out_point: &bitcoin::blockdata::transaction::OutPoint| {
903                                 $(
904                                         if out_point.txid == $spends_txn.txid() {
905                                                 return $spends_txn.output.get(out_point.vout as usize).cloned()
906                                         }
907                                 )*
908                                 None
909                         };
910                         let mut total_value_in = 0;
911                         for input in $tx.input.iter() {
912                                 total_value_in += get_output(&input.previous_output).unwrap().value;
913                         }
914                         let mut total_value_out = 0;
915                         for output in $tx.output.iter() {
916                                 total_value_out += output.value;
917                         }
918                         let min_fee = ($tx.weight() as u64 + 3) / 4; // One sat per vbyte (ie per weight/4, rounded up)
919                         // Input amount - output amount = fee, so check that out + min_fee is smaller than input
920                         assert!(total_value_out + min_fee <= total_value_in);
921                         $tx.verify(get_output).unwrap();
922                 }
923         }
924 }
925
926 macro_rules! get_closing_signed_broadcast {
927         ($node: expr, $dest_pubkey: expr) => {
928                 {
929                         let events = $node.get_and_clear_pending_msg_events();
930                         assert!(events.len() == 1 || events.len() == 2);
931                         (match events[events.len() - 1] {
932                                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
933                                         assert_eq!(msg.contents.flags & 2, 2);
934                                         msg.clone()
935                                 },
936                                 _ => panic!("Unexpected event"),
937                         }, if events.len() == 2 {
938                                 match events[0] {
939                                         MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
940                                                 assert_eq!(*node_id, $dest_pubkey);
941                                                 Some(msg.clone())
942                                         },
943                                         _ => panic!("Unexpected event"),
944                                 }
945                         } else { None })
946                 }
947         }
948 }
949
950 #[cfg(test)]
951 macro_rules! check_warn_msg {
952         ($node: expr, $recipient_node_id: expr, $chan_id: expr) => {{
953                 let msg_events = $node.node.get_and_clear_pending_msg_events();
954                 assert_eq!(msg_events.len(), 1);
955                 match msg_events[0] {
956                         MessageSendEvent::HandleError { action: ErrorAction::SendWarningMessage { ref msg, log_level: _ }, node_id } => {
957                                 assert_eq!(node_id, $recipient_node_id);
958                                 assert_eq!(msg.channel_id, $chan_id);
959                                 msg.data.clone()
960                         },
961                         _ => panic!("Unexpected event"),
962                 }
963         }}
964 }
965
966 /// Check that a channel's closing channel update has been broadcasted, and optionally
967 /// check whether an error message event has occurred.
968 #[macro_export]
969 macro_rules! check_closed_broadcast {
970         ($node: expr, $with_error_msg: expr) => {{
971                 use $crate::util::events::MessageSendEvent;
972                 use $crate::ln::msgs::ErrorAction;
973
974                 let msg_events = $node.node.get_and_clear_pending_msg_events();
975                 assert_eq!(msg_events.len(), if $with_error_msg { 2 } else { 1 });
976                 match msg_events[0] {
977                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
978                                 assert_eq!(msg.contents.flags & 2, 2);
979                         },
980                         _ => panic!("Unexpected event"),
981                 }
982                 if $with_error_msg {
983                         match msg_events[1] {
984                                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
985                                         // TODO: Check node_id
986                                         Some(msg.clone())
987                                 },
988                                 _ => panic!("Unexpected event"),
989                         }
990                 } else { None }
991         }}
992 }
993
994 /// Check that a channel's closing channel events has been issued
995 #[macro_export]
996 macro_rules! check_closed_event {
997         ($node: expr, $events: expr, $reason: expr) => {
998                 check_closed_event!($node, $events, $reason, false);
999         };
1000         ($node: expr, $events: expr, $reason: expr, $is_check_discard_funding: expr) => {{
1001                 use $crate::util::events::Event;
1002
1003                 let events = $node.node.get_and_clear_pending_events();
1004                 assert_eq!(events.len(), $events);
1005                 let expected_reason = $reason;
1006                 let mut issues_discard_funding = false;
1007                 for event in events {
1008                         match event {
1009                                 Event::ChannelClosed { ref reason, .. } => {
1010                                         assert_eq!(*reason, expected_reason);
1011                                 },
1012                                 Event::DiscardFunding { .. } => {
1013                                         issues_discard_funding = true;
1014                                 }
1015                                 _ => panic!("Unexpected event"),
1016                         }
1017                 }
1018                 assert_eq!($is_check_discard_funding, issues_discard_funding);
1019         }}
1020 }
1021
1022 pub fn close_channel<'a, 'b, 'c>(outbound_node: &Node<'a, 'b, 'c>, inbound_node: &Node<'a, 'b, 'c>, channel_id: &[u8; 32], funding_tx: Transaction, close_inbound_first: bool) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, Transaction) {
1023         let (node_a, broadcaster_a, struct_a) = if close_inbound_first { (&inbound_node.node, &inbound_node.tx_broadcaster, inbound_node) } else { (&outbound_node.node, &outbound_node.tx_broadcaster, outbound_node) };
1024         let (node_b, broadcaster_b, struct_b) = if close_inbound_first { (&outbound_node.node, &outbound_node.tx_broadcaster, outbound_node) } else { (&inbound_node.node, &inbound_node.tx_broadcaster, inbound_node) };
1025         let (tx_a, tx_b);
1026
1027         node_a.close_channel(channel_id, &node_b.get_our_node_id()).unwrap();
1028         node_b.handle_shutdown(&node_a.get_our_node_id(), &InitFeatures::known(), &get_event_msg!(struct_a, MessageSendEvent::SendShutdown, node_b.get_our_node_id()));
1029
1030         let events_1 = node_b.get_and_clear_pending_msg_events();
1031         assert!(events_1.len() >= 1);
1032         let shutdown_b = match events_1[0] {
1033                 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
1034                         assert_eq!(node_id, &node_a.get_our_node_id());
1035                         msg.clone()
1036                 },
1037                 _ => panic!("Unexpected event"),
1038         };
1039
1040         let closing_signed_b = if !close_inbound_first {
1041                 assert_eq!(events_1.len(), 1);
1042                 None
1043         } else {
1044                 Some(match events_1[1] {
1045                         MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
1046                                 assert_eq!(node_id, &node_a.get_our_node_id());
1047                                 msg.clone()
1048                         },
1049                         _ => panic!("Unexpected event"),
1050                 })
1051         };
1052
1053         node_a.handle_shutdown(&node_b.get_our_node_id(), &InitFeatures::known(), &shutdown_b);
1054         let (as_update, bs_update) = if close_inbound_first {
1055                 assert!(node_a.get_and_clear_pending_msg_events().is_empty());
1056                 node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap());
1057
1058                 node_b.handle_closing_signed(&node_a.get_our_node_id(), &get_event_msg!(struct_a, MessageSendEvent::SendClosingSigned, node_b.get_our_node_id()));
1059                 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
1060                 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
1061                 let (bs_update, closing_signed_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
1062
1063                 node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap());
1064                 let (as_update, none_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
1065                 assert!(none_a.is_none());
1066                 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
1067                 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
1068                 (as_update, bs_update)
1069         } else {
1070                 let closing_signed_a = get_event_msg!(struct_a, MessageSendEvent::SendClosingSigned, node_b.get_our_node_id());
1071
1072                 node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a);
1073                 node_a.handle_closing_signed(&node_b.get_our_node_id(), &get_event_msg!(struct_b, MessageSendEvent::SendClosingSigned, node_a.get_our_node_id()));
1074
1075                 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
1076                 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
1077                 let (as_update, closing_signed_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
1078
1079                 node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap());
1080                 let (bs_update, none_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
1081                 assert!(none_b.is_none());
1082                 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
1083                 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
1084                 (as_update, bs_update)
1085         };
1086         assert_eq!(tx_a, tx_b);
1087         check_spends!(tx_a, funding_tx);
1088
1089         (as_update, bs_update, tx_a)
1090 }
1091
1092 pub struct SendEvent {
1093         pub node_id: PublicKey,
1094         pub msgs: Vec<msgs::UpdateAddHTLC>,
1095         pub commitment_msg: msgs::CommitmentSigned,
1096 }
1097 impl SendEvent {
1098         pub fn from_commitment_update(node_id: PublicKey, updates: msgs::CommitmentUpdate) -> SendEvent {
1099                 assert!(updates.update_fulfill_htlcs.is_empty());
1100                 assert!(updates.update_fail_htlcs.is_empty());
1101                 assert!(updates.update_fail_malformed_htlcs.is_empty());
1102                 assert!(updates.update_fee.is_none());
1103                 SendEvent { node_id: node_id, msgs: updates.update_add_htlcs, commitment_msg: updates.commitment_signed }
1104         }
1105
1106         pub fn from_event(event: MessageSendEvent) -> SendEvent {
1107                 match event {
1108                         MessageSendEvent::UpdateHTLCs { node_id, updates } => SendEvent::from_commitment_update(node_id, updates),
1109                         _ => panic!("Unexpected event type!"),
1110                 }
1111         }
1112
1113         pub fn from_node<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>) -> SendEvent {
1114                 let mut events = node.node.get_and_clear_pending_msg_events();
1115                 assert_eq!(events.len(), 1);
1116                 SendEvent::from_event(events.pop().unwrap())
1117         }
1118 }
1119
1120 #[macro_export]
1121 /// Performs the "commitment signed dance" - the series of message exchanges which occur after a
1122 /// commitment update.
1123 macro_rules! commitment_signed_dance {
1124         ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */) => {
1125                 {
1126                         check_added_monitors!($node_a, 0);
1127                         assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
1128                         $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed);
1129                         check_added_monitors!($node_a, 1);
1130                         commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, false);
1131                 }
1132         };
1133         ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */, true /* return last RAA */) => {
1134                 {
1135                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!($node_a, $node_b.node.get_our_node_id());
1136                         check_added_monitors!($node_b, 0);
1137                         assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
1138                         $node_b.node.handle_revoke_and_ack(&$node_a.node.get_our_node_id(), &as_revoke_and_ack);
1139                         assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
1140                         check_added_monitors!($node_b, 1);
1141                         $node_b.node.handle_commitment_signed(&$node_a.node.get_our_node_id(), &as_commitment_signed);
1142                         let (bs_revoke_and_ack, extra_msg_option) = {
1143                                 let events = $node_b.node.get_and_clear_pending_msg_events();
1144                                 assert!(events.len() <= 2);
1145                                 (match events[0] {
1146                                         MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
1147                                                 assert_eq!(*node_id, $node_a.node.get_our_node_id());
1148                                                 (*msg).clone()
1149                                         },
1150                                         _ => panic!("Unexpected event"),
1151                                 }, events.get(1).map(|e| e.clone()))
1152                         };
1153                         check_added_monitors!($node_b, 1);
1154                         if $fail_backwards {
1155                                 assert!($node_a.node.get_and_clear_pending_events().is_empty());
1156                                 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
1157                         }
1158                         (extra_msg_option, bs_revoke_and_ack)
1159                 }
1160         };
1161         ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */, false /* return extra message */, true /* return last RAA */) => {
1162                 {
1163                         check_added_monitors!($node_a, 0);
1164                         assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
1165                         $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed);
1166                         check_added_monitors!($node_a, 1);
1167                         let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
1168                         assert!(extra_msg_option.is_none());
1169                         bs_revoke_and_ack
1170                 }
1171         };
1172         ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */) => {
1173                 {
1174                         let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
1175                         $node_a.node.handle_revoke_and_ack(&$node_b.node.get_our_node_id(), &bs_revoke_and_ack);
1176                         check_added_monitors!($node_a, 1);
1177                         extra_msg_option
1178                 }
1179         };
1180         ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, false /* no extra message */) => {
1181                 {
1182                         assert!(commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true).is_none());
1183                 }
1184         };
1185         ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr) => {
1186                 {
1187                         commitment_signed_dance!($node_a, $node_b, $commitment_signed, $fail_backwards, true);
1188                         if $fail_backwards {
1189                                 $crate::expect_pending_htlcs_forwardable!($node_a);
1190                                 check_added_monitors!($node_a, 1);
1191
1192                                 let channel_state = $node_a.node.channel_state.lock().unwrap();
1193                                 assert_eq!(channel_state.pending_msg_events.len(), 1);
1194                                 if let MessageSendEvent::UpdateHTLCs { ref node_id, .. } = channel_state.pending_msg_events[0] {
1195                                         assert_ne!(*node_id, $node_b.node.get_our_node_id());
1196                                 } else { panic!("Unexpected event"); }
1197                         } else {
1198                                 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
1199                         }
1200                 }
1201         }
1202 }
1203
1204 /// Get a payment preimage and hash.
1205 #[macro_export]
1206 macro_rules! get_payment_preimage_hash {
1207         ($dest_node: expr) => {
1208                 {
1209                         get_payment_preimage_hash!($dest_node, None)
1210                 }
1211         };
1212         ($dest_node: expr, $min_value_msat: expr) => {
1213                 {
1214                         use bitcoin::hashes::Hash as _;
1215                         let mut payment_count = $dest_node.network_payment_count.borrow_mut();
1216                         let payment_preimage = $crate::ln::PaymentPreimage([*payment_count; 32]);
1217                         *payment_count += 1;
1218                         let payment_hash = $crate::ln::PaymentHash(
1219                                 bitcoin::hashes::sha256::Hash::hash(&payment_preimage.0[..]).into_inner());
1220                         let payment_secret = $dest_node.node.create_inbound_payment_for_hash(payment_hash, $min_value_msat, 7200).unwrap();
1221                         (payment_preimage, payment_hash, payment_secret)
1222                 }
1223         }
1224 }
1225
1226 #[macro_export]
1227 macro_rules! get_route {
1228         ($send_node: expr, $payment_params: expr, $recv_value: expr, $cltv: expr) => {{
1229                 use $crate::chain::keysinterface::KeysInterface;
1230                 let scorer = $crate::util::test_utils::TestScorer::with_penalty(0);
1231                 let keys_manager = $crate::util::test_utils::TestKeysInterface::new(&[0u8; 32], bitcoin::network::constants::Network::Testnet);
1232                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
1233                 $crate::routing::router::get_route(
1234                         &$send_node.node.get_our_node_id(), &$payment_params, &$send_node.network_graph.read_only(),
1235                         Some(&$send_node.node.list_usable_channels().iter().collect::<Vec<_>>()),
1236                         $recv_value, $cltv, $send_node.logger, &scorer, &random_seed_bytes
1237                 )
1238         }}
1239 }
1240
1241 #[cfg(test)]
1242 #[macro_export]
1243 macro_rules! get_route_and_payment_hash {
1244         ($send_node: expr, $recv_node: expr, $recv_value: expr) => {{
1245                 let payment_params = $crate::routing::router::PaymentParameters::from_node_id($recv_node.node.get_our_node_id())
1246                         .with_features($crate::ln::features::InvoiceFeatures::known());
1247                 $crate::get_route_and_payment_hash!($send_node, $recv_node, payment_params, $recv_value, TEST_FINAL_CLTV)
1248         }};
1249         ($send_node: expr, $recv_node: expr, $payment_params: expr, $recv_value: expr, $cltv: expr) => {{
1250                 let (payment_preimage, payment_hash, payment_secret) = $crate::get_payment_preimage_hash!($recv_node, Some($recv_value));
1251                 let route = $crate::get_route!($send_node, $payment_params, $recv_value, $cltv);
1252                 (route.unwrap(), payment_hash, payment_preimage, payment_secret)
1253         }}
1254 }
1255
1256 #[macro_export]
1257 /// Clears (and ignores) a PendingHTLCsForwardable event
1258 macro_rules! expect_pending_htlcs_forwardable_ignore {
1259         ($node: expr) => {{
1260                 let events = $node.node.get_and_clear_pending_events();
1261                 assert_eq!(events.len(), 1);
1262                 match events[0] {
1263                         $crate::util::events::Event::PendingHTLCsForwardable { .. } => { },
1264                         _ => panic!("Unexpected event"),
1265                 };
1266         }}
1267 }
1268
1269 #[macro_export]
1270 /// Handles a PendingHTLCsForwardable event
1271 macro_rules! expect_pending_htlcs_forwardable {
1272         ($node: expr) => {{
1273                 $crate::expect_pending_htlcs_forwardable_ignore!($node);
1274                 $node.node.process_pending_htlc_forwards();
1275
1276                 // Ensure process_pending_htlc_forwards is idempotent.
1277                 $node.node.process_pending_htlc_forwards();
1278         }}
1279 }
1280
1281 #[cfg(test)]
1282 macro_rules! expect_pending_htlcs_forwardable_from_events {
1283         ($node: expr, $events: expr, $ignore: expr) => {{
1284                 assert_eq!($events.len(), 1);
1285                 match $events[0] {
1286                         Event::PendingHTLCsForwardable { .. } => { },
1287                         _ => panic!("Unexpected event"),
1288                 };
1289                 if $ignore {
1290                         $node.node.process_pending_htlc_forwards();
1291
1292                         // Ensure process_pending_htlc_forwards is idempotent.
1293                         $node.node.process_pending_htlc_forwards();
1294                 }
1295         }}
1296 }
1297
1298 #[macro_export]
1299 #[cfg(any(test, feature = "_bench_unstable", feature = "_test_utils"))]
1300 macro_rules! expect_payment_received {
1301         ($node: expr, $expected_payment_hash: expr, $expected_payment_secret: expr, $expected_recv_value: expr) => {
1302                 expect_payment_received!($node, $expected_payment_hash, $expected_payment_secret, $expected_recv_value, None)
1303         };
1304         ($node: expr, $expected_payment_hash: expr, $expected_payment_secret: expr, $expected_recv_value: expr, $expected_payment_preimage: expr) => {
1305                 let events = $node.node.get_and_clear_pending_events();
1306                 assert_eq!(events.len(), 1);
1307                 match events[0] {
1308                         $crate::util::events::Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1309                                 assert_eq!($expected_payment_hash, *payment_hash);
1310                                 assert_eq!($expected_recv_value, amt);
1311                                 match purpose {
1312                                         $crate::util::events::PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1313                                                 assert_eq!(&$expected_payment_preimage, payment_preimage);
1314                                                 assert_eq!($expected_payment_secret, *payment_secret);
1315                                         },
1316                                         _ => {},
1317                                 }
1318                         },
1319                         _ => panic!("Unexpected event"),
1320                 }
1321         }
1322 }
1323
1324 #[cfg(test)]
1325 #[macro_export]
1326 macro_rules! expect_payment_sent_without_paths {
1327         ($node: expr, $expected_payment_preimage: expr) => {
1328                 expect_payment_sent!($node, $expected_payment_preimage, None::<u64>, false);
1329         };
1330         ($node: expr, $expected_payment_preimage: expr, $expected_fee_msat_opt: expr) => {
1331                 expect_payment_sent!($node, $expected_payment_preimage, $expected_fee_msat_opt, false);
1332         }
1333 }
1334
1335 #[macro_export]
1336 macro_rules! expect_payment_sent {
1337         ($node: expr, $expected_payment_preimage: expr) => {
1338                 $crate::expect_payment_sent!($node, $expected_payment_preimage, None::<u64>, true);
1339         };
1340         ($node: expr, $expected_payment_preimage: expr, $expected_fee_msat_opt: expr) => {
1341                 $crate::expect_payment_sent!($node, $expected_payment_preimage, $expected_fee_msat_opt, true);
1342         };
1343         ($node: expr, $expected_payment_preimage: expr, $expected_fee_msat_opt: expr, $expect_paths: expr) => { {
1344                 use bitcoin::hashes::Hash as _;
1345                 let events = $node.node.get_and_clear_pending_events();
1346                 let expected_payment_hash = $crate::ln::PaymentHash(
1347                         bitcoin::hashes::sha256::Hash::hash(&$expected_payment_preimage.0).into_inner());
1348                 if $expect_paths {
1349                         assert!(events.len() > 1);
1350                 } else {
1351                         assert_eq!(events.len(), 1);
1352                 }
1353                 let expected_payment_id = match events[0] {
1354                         $crate::util::events::Event::PaymentSent { ref payment_id, ref payment_preimage, ref payment_hash, ref fee_paid_msat } => {
1355                                 assert_eq!($expected_payment_preimage, *payment_preimage);
1356                                 assert_eq!(expected_payment_hash, *payment_hash);
1357                                 assert!(fee_paid_msat.is_some());
1358                                 if $expected_fee_msat_opt.is_some() {
1359                                         assert_eq!(*fee_paid_msat, $expected_fee_msat_opt);
1360                                 }
1361                                 payment_id.unwrap()
1362                         },
1363                         _ => panic!("Unexpected event"),
1364                 };
1365                 if $expect_paths {
1366                         for i in 1..events.len() {
1367                                 match events[i] {
1368                                         $crate::util::events::Event::PaymentPathSuccessful { payment_id, payment_hash, .. } => {
1369                                                 assert_eq!(payment_id, expected_payment_id);
1370                                                 assert_eq!(payment_hash, Some(expected_payment_hash));
1371                                         },
1372                                         _ => panic!("Unexpected event"),
1373                                 }
1374                         }
1375                 }
1376         } }
1377 }
1378
1379 #[cfg(test)]
1380 #[macro_export]
1381 macro_rules! expect_payment_path_successful {
1382         ($node: expr) => {
1383                 let events = $node.node.get_and_clear_pending_events();
1384                 assert_eq!(events.len(), 1);
1385                 match events[0] {
1386                         $crate::util::events::Event::PaymentPathSuccessful { .. } => {},
1387                         _ => panic!("Unexpected event"),
1388                 }
1389         }
1390 }
1391
1392 macro_rules! expect_payment_forwarded {
1393         ($node: expr, $prev_node: expr, $next_node: expr, $expected_fee: expr, $upstream_force_closed: expr, $downstream_force_closed: expr) => {
1394                 let events = $node.node.get_and_clear_pending_events();
1395                 assert_eq!(events.len(), 1);
1396                 match events[0] {
1397                         Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
1398                                 assert_eq!(fee_earned_msat, $expected_fee);
1399                                 if fee_earned_msat.is_some() {
1400                                         // Is the event prev_channel_id in one of the channels between the two nodes?
1401                                         assert!($node.node.list_channels().iter().any(|x| x.counterparty.node_id == $prev_node.node.get_our_node_id() && x.channel_id == prev_channel_id.unwrap()));
1402                                 }
1403                                 // We check for force closures since a force closed channel is removed from the
1404                                 // node's channel list
1405                                 if !$downstream_force_closed {
1406                                         assert!($node.node.list_channels().iter().any(|x| x.counterparty.node_id == $next_node.node.get_our_node_id() && x.channel_id == next_channel_id.unwrap()));
1407                                 }
1408                                 assert_eq!(claim_from_onchain_tx, $upstream_force_closed);
1409                         },
1410                         _ => panic!("Unexpected event"),
1411                 }
1412         }
1413 }
1414
1415 pub struct PaymentFailedConditions<'a> {
1416         pub(crate) expected_htlc_error_data: Option<(u16, &'a [u8])>,
1417         pub(crate) expected_blamed_scid: Option<u64>,
1418         pub(crate) expected_blamed_chan_closed: Option<bool>,
1419         pub(crate) expected_mpp_parts_remain: bool,
1420 }
1421
1422 impl<'a> PaymentFailedConditions<'a> {
1423         pub fn new() -> Self {
1424                 Self {
1425                         expected_htlc_error_data: None,
1426                         expected_blamed_scid: None,
1427                         expected_blamed_chan_closed: None,
1428                         expected_mpp_parts_remain: false,
1429                 }
1430         }
1431         pub fn mpp_parts_remain(mut self) -> Self {
1432                 self.expected_mpp_parts_remain = true;
1433                 self
1434         }
1435         pub fn blamed_scid(mut self, scid: u64) -> Self {
1436                 self.expected_blamed_scid = Some(scid);
1437                 self
1438         }
1439         pub fn blamed_chan_closed(mut self, closed: bool) -> Self {
1440                 self.expected_blamed_chan_closed = Some(closed);
1441                 self
1442         }
1443         pub fn expected_htlc_error_data(mut self, code: u16, data: &'a [u8]) -> Self {
1444                 self.expected_htlc_error_data = Some((code, data));
1445                 self
1446         }
1447 }
1448
1449 #[cfg(test)]
1450 macro_rules! expect_payment_failed_with_update {
1451         ($node: expr, $expected_payment_hash: expr, $rejected_by_dest: expr, $scid: expr, $chan_closed: expr) => {
1452                 expect_payment_failed_conditions!($node, $expected_payment_hash, $rejected_by_dest,
1453                         $crate::ln::functional_test_utils::PaymentFailedConditions::new().blamed_scid($scid).blamed_chan_closed($chan_closed));
1454         }
1455 }
1456
1457 #[cfg(test)]
1458 macro_rules! expect_payment_failed {
1459         ($node: expr, $expected_payment_hash: expr, $rejected_by_dest: expr $(, $expected_error_code: expr, $expected_error_data: expr)*) => {
1460                 #[allow(unused_mut)]
1461                 let mut conditions = $crate::ln::functional_test_utils::PaymentFailedConditions::new();
1462                 $(
1463                         conditions = conditions.expected_htlc_error_data($expected_error_code, &$expected_error_data);
1464                 )*
1465                 expect_payment_failed_conditions!($node, $expected_payment_hash, $rejected_by_dest, conditions);
1466         };
1467 }
1468
1469 #[cfg(test)]
1470 macro_rules! expect_payment_failed_conditions {
1471         ($node: expr, $expected_payment_hash: expr, $rejected_by_dest: expr, $conditions: expr) => {
1472                 let events = $node.node.get_and_clear_pending_events();
1473                 assert_eq!(events.len(), 1);
1474                 let expected_payment_id = match events[0] {
1475                         Event::PaymentPathFailed { ref payment_hash, rejected_by_dest, ref error_code, ref error_data, ref path, ref retry, ref payment_id, ref network_update, .. } => {
1476                                 assert_eq!(*payment_hash, $expected_payment_hash, "unexpected payment_hash");
1477                                 assert_eq!(rejected_by_dest, $rejected_by_dest, "unexpected rejected_by_dest value");
1478                                 assert!(retry.is_some(), "expected retry.is_some()");
1479                                 assert_eq!(retry.as_ref().unwrap().final_value_msat, path.last().unwrap().fee_msat, "Retry amount should match last hop in path");
1480                                 assert_eq!(retry.as_ref().unwrap().payment_params.payee_pubkey, path.last().unwrap().pubkey, "Retry payee node_id should match last hop in path");
1481
1482                                 assert!(error_code.is_some(), "expected error_code.is_some() = true");
1483                                 assert!(error_data.is_some(), "expected error_data.is_some() = true");
1484                                 if let Some((code, data)) = $conditions.expected_htlc_error_data {
1485                                         assert_eq!(error_code.unwrap(), code, "unexpected error code");
1486                                         assert_eq!(&error_data.as_ref().unwrap()[..], data, "unexpected error data");
1487                                 }
1488
1489                                 if let Some(chan_closed) = $conditions.expected_blamed_chan_closed {
1490                                         match network_update {
1491                                                 &Some($crate::routing::network_graph::NetworkUpdate::ChannelUpdateMessage { ref msg }) if !chan_closed => {
1492                                                         if let Some(scid) = $conditions.expected_blamed_scid {
1493                                                                 assert_eq!(msg.contents.short_channel_id, scid);
1494                                                         }
1495                                                         assert_eq!(msg.contents.flags & 2, 0);
1496                                                 },
1497                                                 &Some($crate::routing::network_graph::NetworkUpdate::ChannelClosed { short_channel_id, is_permanent }) if chan_closed => {
1498                                                         if let Some(scid) = $conditions.expected_blamed_scid {
1499                                                                 assert_eq!(short_channel_id, scid);
1500                                                         }
1501                                                         assert!(is_permanent);
1502                                                 },
1503                                                 Some(_) => panic!("Unexpected update type"),
1504                                                 None => panic!("Expected update"),
1505                                         }
1506                                 }
1507
1508                                 payment_id.unwrap()
1509                         },
1510                         _ => panic!("Unexpected event"),
1511                 };
1512                 if !$conditions.expected_mpp_parts_remain {
1513                         $node.node.abandon_payment(expected_payment_id);
1514                         let events = $node.node.get_and_clear_pending_events();
1515                         assert_eq!(events.len(), 1);
1516                         match events[0] {
1517                                 Event::PaymentFailed { ref payment_hash, ref payment_id } => {
1518                                         assert_eq!(*payment_hash, $expected_payment_hash, "unexpected second payment_hash");
1519                                         assert_eq!(*payment_id, expected_payment_id);
1520                                 }
1521                                 _ => panic!("Unexpected second event"),
1522                         }
1523                 }
1524         }
1525 }
1526
1527 pub fn send_along_route_with_secret<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, route: Route, expected_paths: &[&[&Node<'a, 'b, 'c>]], recv_value: u64, our_payment_hash: PaymentHash, our_payment_secret: PaymentSecret) -> PaymentId {
1528         let payment_id = origin_node.node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
1529         check_added_monitors!(origin_node, expected_paths.len());
1530         pass_along_route(origin_node, expected_paths, recv_value, our_payment_hash, our_payment_secret);
1531         payment_id
1532 }
1533
1534 pub fn pass_along_path<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_path: &[&Node<'a, 'b, 'c>], recv_value: u64, our_payment_hash: PaymentHash, our_payment_secret: Option<PaymentSecret>, ev: MessageSendEvent, payment_received_expected: bool, expected_preimage: Option<PaymentPreimage>) {
1535         let mut payment_event = SendEvent::from_event(ev);
1536         let mut prev_node = origin_node;
1537
1538         for (idx, &node) in expected_path.iter().enumerate() {
1539                 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
1540
1541                 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
1542                 check_added_monitors!(node, 0);
1543                 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
1544
1545                 expect_pending_htlcs_forwardable!(node);
1546
1547                 if idx == expected_path.len() - 1 {
1548                         let events_2 = node.node.get_and_clear_pending_events();
1549                         if payment_received_expected {
1550                                 assert_eq!(events_2.len(), 1);
1551                                 match events_2[0] {
1552                                         Event::PaymentReceived { ref payment_hash, ref purpose, amt} => {
1553                                                 assert_eq!(our_payment_hash, *payment_hash);
1554                                                 match &purpose {
1555                                                         PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1556                                                                 assert_eq!(expected_preimage, *payment_preimage);
1557                                                                 assert_eq!(our_payment_secret.unwrap(), *payment_secret);
1558                                                         },
1559                                                         PaymentPurpose::SpontaneousPayment(payment_preimage) => {
1560                                                                 assert_eq!(expected_preimage.unwrap(), *payment_preimage);
1561                                                                 assert!(our_payment_secret.is_none());
1562                                                         },
1563                                                 }
1564                                                 assert_eq!(amt, recv_value);
1565                                         },
1566                                         _ => panic!("Unexpected event"),
1567                                 }
1568                         } else {
1569                                 assert!(events_2.is_empty());
1570                         }
1571                 } else {
1572                         let mut events_2 = node.node.get_and_clear_pending_msg_events();
1573                         assert_eq!(events_2.len(), 1);
1574                         check_added_monitors!(node, 1);
1575                         payment_event = SendEvent::from_event(events_2.remove(0));
1576                         assert_eq!(payment_event.msgs.len(), 1);
1577                 }
1578
1579                 prev_node = node;
1580         }
1581 }
1582
1583 pub fn pass_along_route<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_route: &[&[&Node<'a, 'b, 'c>]], recv_value: u64, our_payment_hash: PaymentHash, our_payment_secret: PaymentSecret) {
1584         let mut events = origin_node.node.get_and_clear_pending_msg_events();
1585         assert_eq!(events.len(), expected_route.len());
1586         for (path_idx, (ev, expected_path)) in events.drain(..).zip(expected_route.iter()).enumerate() {
1587                 // Once we've gotten through all the HTLCs, the last one should result in a
1588                 // PaymentReceived (but each previous one should not!), .
1589                 let expect_payment = path_idx == expected_route.len() - 1;
1590                 pass_along_path(origin_node, expected_path, recv_value, our_payment_hash.clone(), Some(our_payment_secret), ev, expect_payment, None);
1591         }
1592 }
1593
1594 pub fn send_along_route<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, route: Route, expected_route: &[&Node<'a, 'b, 'c>], recv_value: u64) -> (PaymentPreimage, PaymentHash, PaymentSecret, PaymentId) {
1595         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(expected_route.last().unwrap());
1596         let payment_id = send_along_route_with_secret(origin_node, route, &[expected_route], recv_value, our_payment_hash, our_payment_secret);
1597         (our_payment_preimage, our_payment_hash, our_payment_secret, payment_id)
1598 }
1599
1600 pub fn do_claim_payment_along_route<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_paths: &[&[&Node<'a, 'b, 'c>]], skip_last: bool, our_payment_preimage: PaymentPreimage) -> u64 {
1601         for path in expected_paths.iter() {
1602                 assert_eq!(path.last().unwrap().node.get_our_node_id(), expected_paths[0].last().unwrap().node.get_our_node_id());
1603         }
1604         assert!(expected_paths[0].last().unwrap().node.claim_funds(our_payment_preimage));
1605         check_added_monitors!(expected_paths[0].last().unwrap(), expected_paths.len());
1606
1607         let mut expected_total_fee_msat = 0;
1608
1609         macro_rules! msgs_from_ev {
1610                 ($ev: expr) => {
1611                         match $ev {
1612                                 &MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
1613                                         assert!(update_add_htlcs.is_empty());
1614                                         assert_eq!(update_fulfill_htlcs.len(), 1);
1615                                         assert!(update_fail_htlcs.is_empty());
1616                                         assert!(update_fail_malformed_htlcs.is_empty());
1617                                         assert!(update_fee.is_none());
1618                                         ((update_fulfill_htlcs[0].clone(), commitment_signed.clone()), node_id.clone())
1619                                 },
1620                                 _ => panic!("Unexpected event"),
1621                         }
1622                 }
1623         }
1624         let mut per_path_msgs: Vec<((msgs::UpdateFulfillHTLC, msgs::CommitmentSigned), PublicKey)> = Vec::with_capacity(expected_paths.len());
1625         let events = expected_paths[0].last().unwrap().node.get_and_clear_pending_msg_events();
1626         assert_eq!(events.len(), expected_paths.len());
1627         for ev in events.iter() {
1628                 per_path_msgs.push(msgs_from_ev!(ev));
1629         }
1630
1631         for (expected_route, (path_msgs, next_hop)) in expected_paths.iter().zip(per_path_msgs.drain(..)) {
1632                 let mut next_msgs = Some(path_msgs);
1633                 let mut expected_next_node = next_hop;
1634
1635                 macro_rules! last_update_fulfill_dance {
1636                         ($node: expr, $prev_node: expr) => {
1637                                 {
1638                                         $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0);
1639                                         check_added_monitors!($node, 0);
1640                                         assert!($node.node.get_and_clear_pending_msg_events().is_empty());
1641                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
1642                                 }
1643                         }
1644                 }
1645                 macro_rules! mid_update_fulfill_dance {
1646                         ($node: expr, $prev_node: expr, $next_node: expr, $new_msgs: expr) => {
1647                                 {
1648                                         $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0);
1649                                         let fee = $node.node.channel_state.lock().unwrap().by_id.get(&next_msgs.as_ref().unwrap().0.channel_id).unwrap().config.forwarding_fee_base_msat;
1650                                         expect_payment_forwarded!($node, $next_node, $prev_node, Some(fee as u64), false, false);
1651                                         expected_total_fee_msat += fee as u64;
1652                                         check_added_monitors!($node, 1);
1653                                         let new_next_msgs = if $new_msgs {
1654                                                 let events = $node.node.get_and_clear_pending_msg_events();
1655                                                 assert_eq!(events.len(), 1);
1656                                                 let (res, nexthop) = msgs_from_ev!(&events[0]);
1657                                                 expected_next_node = nexthop;
1658                                                 Some(res)
1659                                         } else {
1660                                                 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
1661                                                 None
1662                                         };
1663                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
1664                                         next_msgs = new_next_msgs;
1665                                 }
1666                         }
1667                 }
1668
1669                 let mut prev_node = expected_route.last().unwrap();
1670                 for (idx, node) in expected_route.iter().rev().enumerate().skip(1) {
1671                         assert_eq!(expected_next_node, node.node.get_our_node_id());
1672                         let update_next_msgs = !skip_last || idx != expected_route.len() - 1;
1673                         if next_msgs.is_some() {
1674                                 // Since we are traversing in reverse, next_node is actually the previous node
1675                                 let next_node: &Node;
1676                                 if idx == expected_route.len() - 1 {
1677                                         next_node = origin_node;
1678                                 } else {
1679                                         next_node = expected_route[expected_route.len() - 1 - idx - 1];
1680                                 }
1681                                 mid_update_fulfill_dance!(node, prev_node, next_node, update_next_msgs);
1682                         } else {
1683                                 assert!(!update_next_msgs);
1684                                 assert!(node.node.get_and_clear_pending_msg_events().is_empty());
1685                         }
1686                         if !skip_last && idx == expected_route.len() - 1 {
1687                                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
1688                         }
1689
1690                         prev_node = node;
1691                 }
1692
1693                 if !skip_last {
1694                         last_update_fulfill_dance!(origin_node, expected_route.first().unwrap());
1695                 }
1696         }
1697
1698         // Ensure that claim_funds is idempotent.
1699         assert!(!expected_paths[0].last().unwrap().node.claim_funds(our_payment_preimage));
1700         assert!(expected_paths[0].last().unwrap().node.get_and_clear_pending_msg_events().is_empty());
1701         check_added_monitors!(expected_paths[0].last().unwrap(), 0);
1702
1703         expected_total_fee_msat
1704 }
1705 pub fn claim_payment_along_route<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_paths: &[&[&Node<'a, 'b, 'c>]], skip_last: bool, our_payment_preimage: PaymentPreimage) {
1706         let expected_total_fee_msat = do_claim_payment_along_route(origin_node, expected_paths, skip_last, our_payment_preimage);
1707         if !skip_last {
1708                 expect_payment_sent!(origin_node, our_payment_preimage, Some(expected_total_fee_msat));
1709         }
1710 }
1711
1712 pub fn claim_payment<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_route: &[&Node<'a, 'b, 'c>], our_payment_preimage: PaymentPreimage) {
1713         claim_payment_along_route(origin_node, &[expected_route], false, our_payment_preimage);
1714 }
1715
1716 pub const TEST_FINAL_CLTV: u32 = 70;
1717
1718 pub fn route_payment<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_route: &[&Node<'a, 'b, 'c>], recv_value: u64) -> (PaymentPreimage, PaymentHash, PaymentSecret) {
1719         let payment_params = PaymentParameters::from_node_id(expected_route.last().unwrap().node.get_our_node_id())
1720                 .with_features(InvoiceFeatures::known());
1721         let route = get_route!(origin_node, payment_params, recv_value, TEST_FINAL_CLTV).unwrap();
1722         assert_eq!(route.paths.len(), 1);
1723         assert_eq!(route.paths[0].len(), expected_route.len());
1724         for (node, hop) in expected_route.iter().zip(route.paths[0].iter()) {
1725                 assert_eq!(hop.pubkey, node.node.get_our_node_id());
1726         }
1727
1728         let res = send_along_route(origin_node, route, expected_route, recv_value);
1729         (res.0, res.1, res.2)
1730 }
1731
1732 pub fn route_over_limit<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_route: &[&Node<'a, 'b, 'c>], recv_value: u64)  {
1733         let payment_params = PaymentParameters::from_node_id(expected_route.last().unwrap().node.get_our_node_id())
1734                 .with_features(InvoiceFeatures::known());
1735         let network_graph = origin_node.network_graph.read_only();
1736         let scorer = test_utils::TestScorer::with_penalty(0);
1737         let seed = [0u8; 32];
1738         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
1739         let random_seed_bytes = keys_manager.get_secure_random_bytes();
1740         let route = get_route(
1741                 &origin_node.node.get_our_node_id(), &payment_params, &network_graph,
1742                 None, recv_value, TEST_FINAL_CLTV, origin_node.logger, &scorer, &random_seed_bytes).unwrap();
1743         assert_eq!(route.paths.len(), 1);
1744         assert_eq!(route.paths[0].len(), expected_route.len());
1745         for (node, hop) in expected_route.iter().zip(route.paths[0].iter()) {
1746                 assert_eq!(hop.pubkey, node.node.get_our_node_id());
1747         }
1748
1749         let (_, our_payment_hash, our_payment_preimage) = get_payment_preimage_hash!(expected_route.last().unwrap());
1750         unwrap_send_err!(origin_node.node.send_payment(&route, our_payment_hash, &Some(our_payment_preimage)), true, APIError::ChannelUnavailable { ref err },
1751                 assert!(err.contains("Cannot send value that would put us over the max HTLC value in flight our peer will accept")));
1752 }
1753
1754 pub fn send_payment<'a, 'b, 'c>(origin: &Node<'a, 'b, 'c>, expected_route: &[&Node<'a, 'b, 'c>], recv_value: u64)  {
1755         let our_payment_preimage = route_payment(&origin, expected_route, recv_value).0;
1756         claim_payment(&origin, expected_route, our_payment_preimage);
1757 }
1758
1759 pub fn fail_payment_along_route<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_paths_slice: &[&[&Node<'a, 'b, 'c>]], skip_last: bool, our_payment_hash: PaymentHash)  {
1760         let mut expected_paths: Vec<_> = expected_paths_slice.iter().collect();
1761         for path in expected_paths.iter() {
1762                 assert_eq!(path.last().unwrap().node.get_our_node_id(), expected_paths[0].last().unwrap().node.get_our_node_id());
1763         }
1764         assert!(expected_paths[0].last().unwrap().node.fail_htlc_backwards(&our_payment_hash));
1765         expect_pending_htlcs_forwardable!(expected_paths[0].last().unwrap());
1766         check_added_monitors!(expected_paths[0].last().unwrap(), expected_paths.len());
1767
1768         let mut per_path_msgs: Vec<((msgs::UpdateFailHTLC, msgs::CommitmentSigned), PublicKey)> = Vec::with_capacity(expected_paths.len());
1769         let events = expected_paths[0].last().unwrap().node.get_and_clear_pending_msg_events();
1770         assert_eq!(events.len(), expected_paths.len());
1771         for ev in events.iter() {
1772                 let (update_fail, commitment_signed, node_id) = match ev {
1773                         &MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
1774                                 assert!(update_add_htlcs.is_empty());
1775                                 assert!(update_fulfill_htlcs.is_empty());
1776                                 assert_eq!(update_fail_htlcs.len(), 1);
1777                                 assert!(update_fail_malformed_htlcs.is_empty());
1778                                 assert!(update_fee.is_none());
1779                                 (update_fail_htlcs[0].clone(), commitment_signed.clone(), node_id.clone())
1780                         },
1781                         _ => panic!("Unexpected event"),
1782                 };
1783                 per_path_msgs.push(((update_fail, commitment_signed), node_id));
1784         }
1785         per_path_msgs.sort_unstable_by(|(_, node_id_a), (_, node_id_b)| node_id_a.cmp(node_id_b));
1786         expected_paths.sort_unstable_by(|path_a, path_b| path_a[path_a.len() - 2].node.get_our_node_id().cmp(&path_b[path_b.len() - 2].node.get_our_node_id()));
1787
1788         for (i, (expected_route, (path_msgs, next_hop))) in expected_paths.iter().zip(per_path_msgs.drain(..)).enumerate() {
1789                 let mut next_msgs = Some(path_msgs);
1790                 let mut expected_next_node = next_hop;
1791                 let mut prev_node = expected_route.last().unwrap();
1792
1793                 for (idx, node) in expected_route.iter().rev().enumerate().skip(1) {
1794                         assert_eq!(expected_next_node, node.node.get_our_node_id());
1795                         let update_next_node = !skip_last || idx != expected_route.len() - 1;
1796                         if next_msgs.is_some() {
1797                                 node.node.handle_update_fail_htlc(&prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0);
1798                                 commitment_signed_dance!(node, prev_node, next_msgs.as_ref().unwrap().1, update_next_node);
1799                                 if !update_next_node {
1800                                         expect_pending_htlcs_forwardable!(node);
1801                                 }
1802                         }
1803                         let events = node.node.get_and_clear_pending_msg_events();
1804                         if update_next_node {
1805                                 assert_eq!(events.len(), 1);
1806                                 match events[0] {
1807                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
1808                                                 assert!(update_add_htlcs.is_empty());
1809                                                 assert!(update_fulfill_htlcs.is_empty());
1810                                                 assert_eq!(update_fail_htlcs.len(), 1);
1811                                                 assert!(update_fail_malformed_htlcs.is_empty());
1812                                                 assert!(update_fee.is_none());
1813                                                 expected_next_node = node_id.clone();
1814                                                 next_msgs = Some((update_fail_htlcs[0].clone(), commitment_signed.clone()));
1815                                         },
1816                                         _ => panic!("Unexpected event"),
1817                                 }
1818                         } else {
1819                                 assert!(events.is_empty());
1820                         }
1821                         if !skip_last && idx == expected_route.len() - 1 {
1822                                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
1823                         }
1824
1825                         prev_node = node;
1826                 }
1827
1828                 if !skip_last {
1829                         let prev_node = expected_route.first().unwrap();
1830                         origin_node.node.handle_update_fail_htlc(&prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0);
1831                         check_added_monitors!(origin_node, 0);
1832                         assert!(origin_node.node.get_and_clear_pending_msg_events().is_empty());
1833                         commitment_signed_dance!(origin_node, prev_node, next_msgs.as_ref().unwrap().1, false);
1834                         let events = origin_node.node.get_and_clear_pending_events();
1835                         assert_eq!(events.len(), 1);
1836                         let expected_payment_id = match events[0] {
1837                                 Event::PaymentPathFailed { payment_hash, rejected_by_dest, all_paths_failed, ref path, ref payment_id, .. } => {
1838                                         assert_eq!(payment_hash, our_payment_hash);
1839                                         assert!(rejected_by_dest);
1840                                         assert_eq!(all_paths_failed, i == expected_paths.len() - 1);
1841                                         for (idx, hop) in expected_route.iter().enumerate() {
1842                                                 assert_eq!(hop.node.get_our_node_id(), path[idx].pubkey);
1843                                         }
1844                                         payment_id.unwrap()
1845                                 },
1846                                 _ => panic!("Unexpected event"),
1847                         };
1848                         if i == expected_paths.len() - 1 {
1849                                 origin_node.node.abandon_payment(expected_payment_id);
1850                                 let events = origin_node.node.get_and_clear_pending_events();
1851                                 assert_eq!(events.len(), 1);
1852                                 match events[0] {
1853                                         Event::PaymentFailed { ref payment_hash, ref payment_id } => {
1854                                                 assert_eq!(*payment_hash, our_payment_hash, "unexpected second payment_hash");
1855                                                 assert_eq!(*payment_id, expected_payment_id);
1856                                         }
1857                                         _ => panic!("Unexpected second event"),
1858                                 }
1859                         }
1860                 }
1861         }
1862
1863         // Ensure that fail_htlc_backwards is idempotent.
1864         assert!(!expected_paths[0].last().unwrap().node.fail_htlc_backwards(&our_payment_hash));
1865         assert!(expected_paths[0].last().unwrap().node.get_and_clear_pending_events().is_empty());
1866         assert!(expected_paths[0].last().unwrap().node.get_and_clear_pending_msg_events().is_empty());
1867         check_added_monitors!(expected_paths[0].last().unwrap(), 0);
1868 }
1869
1870 pub fn fail_payment<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_path: &[&Node<'a, 'b, 'c>], our_payment_hash: PaymentHash)  {
1871         fail_payment_along_route(origin_node, &[&expected_path[..]], false, our_payment_hash);
1872 }
1873
1874 pub fn create_chanmon_cfgs(node_count: usize) -> Vec<TestChanMonCfg> {
1875         let mut chan_mon_cfgs = Vec::new();
1876         for i in 0..node_count {
1877                 let tx_broadcaster = test_utils::TestBroadcaster {
1878                         txn_broadcasted: Mutex::new(Vec::new()),
1879                         blocks: Arc::new(Mutex::new(vec![(genesis_block(Network::Testnet), 0)])),
1880                 };
1881                 let fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
1882                 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
1883                 let logger = test_utils::TestLogger::with_id(format!("node {}", i));
1884                 let persister = test_utils::TestPersister::new();
1885                 let seed = [i as u8; 32];
1886                 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
1887                 let network_graph = NetworkGraph::new(chain_source.genesis_hash);
1888
1889                 chan_mon_cfgs.push(TestChanMonCfg{ tx_broadcaster, fee_estimator, chain_source, logger, persister, keys_manager, network_graph });
1890         }
1891
1892         chan_mon_cfgs
1893 }
1894
1895 pub fn create_node_cfgs<'a>(node_count: usize, chanmon_cfgs: &'a Vec<TestChanMonCfg>) -> Vec<NodeCfg<'a>> {
1896         let mut nodes = Vec::new();
1897
1898         for i in 0..node_count {
1899                 let chain_monitor = test_utils::TestChainMonitor::new(Some(&chanmon_cfgs[i].chain_source), &chanmon_cfgs[i].tx_broadcaster, &chanmon_cfgs[i].logger, &chanmon_cfgs[i].fee_estimator, &chanmon_cfgs[i].persister, &chanmon_cfgs[i].keys_manager);
1900                 let seed = [i as u8; 32];
1901                 nodes.push(NodeCfg {
1902                         chain_source: &chanmon_cfgs[i].chain_source,
1903                         logger: &chanmon_cfgs[i].logger,
1904                         tx_broadcaster: &chanmon_cfgs[i].tx_broadcaster,
1905                         fee_estimator: &chanmon_cfgs[i].fee_estimator,
1906                         chain_monitor,
1907                         keys_manager: &chanmon_cfgs[i].keys_manager,
1908                         node_seed: seed,
1909                         features: InitFeatures::known(),
1910                         network_graph: &chanmon_cfgs[i].network_graph,
1911                 });
1912         }
1913
1914         nodes
1915 }
1916
1917 pub fn test_default_channel_config() -> UserConfig {
1918         let mut default_config = UserConfig::default();
1919         // Set cltv_expiry_delta slightly lower to keep the final CLTV values inside one byte in our
1920         // tests so that our script-length checks don't fail (see ACCEPTED_HTLC_SCRIPT_WEIGHT).
1921         default_config.channel_options.cltv_expiry_delta = MIN_CLTV_EXPIRY_DELTA;
1922         default_config.channel_options.announced_channel = true;
1923         default_config.peer_channel_config_limits.force_announced_channel_preference = false;
1924         // When most of our tests were written, the default HTLC minimum was fixed at 1000.
1925         // It now defaults to 1, so we simply set it to the expected value here.
1926         default_config.own_channel_config.our_htlc_minimum_msat = 1000;
1927         // When most of our tests were written, we didn't have the notion of a `max_dust_htlc_exposure_msat`,
1928         // It now defaults to 5_000_000 msat; to avoid interfering with tests we bump it to 50_000_000 msat.
1929         default_config.channel_options.max_dust_htlc_exposure_msat = 50_000_000;
1930         default_config
1931 }
1932
1933 pub fn create_node_chanmgrs<'a, 'b>(node_count: usize, cfgs: &'a Vec<NodeCfg<'b>>, node_config: &[Option<UserConfig>]) -> Vec<ChannelManager<EnforcingSigner, &'a TestChainMonitor<'b>, &'b test_utils::TestBroadcaster, &'a test_utils::TestKeysInterface, &'b test_utils::TestFeeEstimator, &'b test_utils::TestLogger>> {
1934         let mut chanmgrs = Vec::new();
1935         for i in 0..node_count {
1936                 let network = Network::Testnet;
1937                 let params = ChainParameters {
1938                         network,
1939                         best_block: BestBlock::from_genesis(network),
1940                 };
1941                 let node = ChannelManager::new(cfgs[i].fee_estimator, &cfgs[i].chain_monitor, cfgs[i].tx_broadcaster, cfgs[i].logger, cfgs[i].keys_manager,
1942                         if node_config[i].is_some() { node_config[i].clone().unwrap() } else { test_default_channel_config() }, params);
1943                 chanmgrs.push(node);
1944         }
1945
1946         chanmgrs
1947 }
1948
1949 pub fn create_network<'a, 'b: 'a, 'c: 'b>(node_count: usize, cfgs: &'b Vec<NodeCfg<'c>>, chan_mgrs: &'a Vec<ChannelManager<EnforcingSigner, &'b TestChainMonitor<'c>, &'c test_utils::TestBroadcaster, &'b test_utils::TestKeysInterface, &'c test_utils::TestFeeEstimator, &'c test_utils::TestLogger>>) -> Vec<Node<'a, 'b, 'c>> {
1950         let mut nodes = Vec::new();
1951         let chan_count = Rc::new(RefCell::new(0));
1952         let payment_count = Rc::new(RefCell::new(0));
1953         let connect_style = Rc::new(RefCell::new(ConnectStyle::random_style()));
1954
1955         for i in 0..node_count {
1956                 let net_graph_msg_handler = NetGraphMsgHandler::new(cfgs[i].network_graph, None, cfgs[i].logger);
1957                 nodes.push(Node{
1958                         chain_source: cfgs[i].chain_source, tx_broadcaster: cfgs[i].tx_broadcaster,
1959                         chain_monitor: &cfgs[i].chain_monitor, keys_manager: &cfgs[i].keys_manager,
1960                         node: &chan_mgrs[i], network_graph: &cfgs[i].network_graph, net_graph_msg_handler,
1961                         node_seed: cfgs[i].node_seed, network_chan_count: chan_count.clone(),
1962                         network_payment_count: payment_count.clone(), logger: cfgs[i].logger,
1963                         blocks: Arc::clone(&cfgs[i].tx_broadcaster.blocks),
1964                         connect_style: Rc::clone(&connect_style),
1965                 })
1966         }
1967
1968         for i in 0..node_count {
1969                 for j in (i+1)..node_count {
1970                         nodes[i].node.peer_connected(&nodes[j].node.get_our_node_id(), &msgs::Init { features: cfgs[j].features.clone(), remote_network_address: None });
1971                         nodes[j].node.peer_connected(&nodes[i].node.get_our_node_id(), &msgs::Init { features: cfgs[i].features.clone(), remote_network_address: None });
1972                 }
1973         }
1974
1975         nodes
1976 }
1977
1978 // Note that the following only works for CLTV values up to 128
1979 pub const ACCEPTED_HTLC_SCRIPT_WEIGHT: usize = 137; //Here we have a diff due to HTLC CLTV expiry being < 2^15 in test
1980 pub const OFFERED_HTLC_SCRIPT_WEIGHT: usize = 133;
1981
1982 #[derive(PartialEq)]
1983 pub enum HTLCType { NONE, TIMEOUT, SUCCESS }
1984 /// Tests that the given node has broadcast transactions for the given Channel
1985 ///
1986 /// First checks that the latest holder commitment tx has been broadcast, unless an explicit
1987 /// commitment_tx is provided, which may be used to test that a remote commitment tx was
1988 /// broadcast and the revoked outputs were claimed.
1989 ///
1990 /// Next tests that there is (or is not) a transaction that spends the commitment transaction
1991 /// that appears to be the type of HTLC transaction specified in has_htlc_tx.
1992 ///
1993 /// All broadcast transactions must be accounted for in one of the above three types of we'll
1994 /// also fail.
1995 pub fn test_txn_broadcast<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, chan: &(msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction), commitment_tx: Option<Transaction>, has_htlc_tx: HTLCType) -> Vec<Transaction>  {
1996         let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
1997         assert!(node_txn.len() >= if commitment_tx.is_some() { 0 } else { 1 } + if has_htlc_tx == HTLCType::NONE { 0 } else { 1 });
1998
1999         let mut res = Vec::with_capacity(2);
2000         node_txn.retain(|tx| {
2001                 if tx.input.len() == 1 && tx.input[0].previous_output.txid == chan.3.txid() {
2002                         check_spends!(tx, chan.3);
2003                         if commitment_tx.is_none() {
2004                                 res.push(tx.clone());
2005                         }
2006                         false
2007                 } else { true }
2008         });
2009         if let Some(explicit_tx) = commitment_tx {
2010                 res.push(explicit_tx.clone());
2011         }
2012
2013         assert_eq!(res.len(), 1);
2014
2015         if has_htlc_tx != HTLCType::NONE {
2016                 node_txn.retain(|tx| {
2017                         if tx.input.len() == 1 && tx.input[0].previous_output.txid == res[0].txid() {
2018                                 check_spends!(tx, res[0]);
2019                                 if has_htlc_tx == HTLCType::TIMEOUT {
2020                                         assert!(tx.lock_time != 0);
2021                                 } else {
2022                                         assert!(tx.lock_time == 0);
2023                                 }
2024                                 res.push(tx.clone());
2025                                 false
2026                         } else { true }
2027                 });
2028                 assert!(res.len() == 2 || res.len() == 3);
2029                 if res.len() == 3 {
2030                         assert_eq!(res[1], res[2]);
2031                 }
2032         }
2033
2034         assert!(node_txn.is_empty());
2035         res
2036 }
2037
2038 /// Tests that the given node has broadcast a claim transaction against the provided revoked
2039 /// HTLC transaction.
2040 pub fn test_revoked_htlc_claim_txn_broadcast<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, revoked_tx: Transaction, commitment_revoked_tx: Transaction)  {
2041         let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2042         // We may issue multiple claiming transaction on revoked outputs due to block rescan
2043         // for revoked htlc outputs
2044         if node_txn.len() != 1 && node_txn.len() != 2 && node_txn.len() != 3 { assert!(false); }
2045         node_txn.retain(|tx| {
2046                 if tx.input.len() == 1 && tx.input[0].previous_output.txid == revoked_tx.txid() {
2047                         check_spends!(tx, revoked_tx);
2048                         false
2049                 } else { true }
2050         });
2051         node_txn.retain(|tx| {
2052                 check_spends!(tx, commitment_revoked_tx);
2053                 false
2054         });
2055         assert!(node_txn.is_empty());
2056 }
2057
2058 pub fn check_preimage_claim<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, prev_txn: &Vec<Transaction>) -> Vec<Transaction>  {
2059         let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2060
2061         assert!(node_txn.len() >= 1);
2062         assert_eq!(node_txn[0].input.len(), 1);
2063         let mut found_prev = false;
2064
2065         for tx in prev_txn {
2066                 if node_txn[0].input[0].previous_output.txid == tx.txid() {
2067                         check_spends!(node_txn[0], tx);
2068                         let mut iter = node_txn[0].input[0].witness.iter();
2069                         iter.next().expect("expected 3 witness items");
2070                         iter.next().expect("expected 3 witness items");
2071                         assert!(iter.next().expect("expected 3 witness items").len() > 106); // must spend an htlc output
2072                         assert_eq!(tx.input.len(), 1); // must spend a commitment tx
2073
2074                         found_prev = true;
2075                         break;
2076                 }
2077         }
2078         assert!(found_prev);
2079
2080         let mut res = Vec::new();
2081         mem::swap(&mut *node_txn, &mut res);
2082         res
2083 }
2084
2085 pub fn handle_announce_close_broadcast_events<'a, 'b, 'c>(nodes: &Vec<Node<'a, 'b, 'c>>, a: usize, b: usize, needs_err_handle: bool, expected_error: &str)  {
2086         let events_1 = nodes[a].node.get_and_clear_pending_msg_events();
2087         assert_eq!(events_1.len(), 2);
2088         let as_update = match events_1[0] {
2089                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2090                         msg.clone()
2091                 },
2092                 _ => panic!("Unexpected event"),
2093         };
2094         match events_1[1] {
2095                 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
2096                         assert_eq!(node_id, nodes[b].node.get_our_node_id());
2097                         assert_eq!(msg.data, expected_error);
2098                         if needs_err_handle {
2099                                 nodes[b].node.handle_error(&nodes[a].node.get_our_node_id(), msg);
2100                         }
2101                 },
2102                 _ => panic!("Unexpected event"),
2103         }
2104
2105         let events_2 = nodes[b].node.get_and_clear_pending_msg_events();
2106         assert_eq!(events_2.len(), if needs_err_handle { 1 } else { 2 });
2107         let bs_update = match events_2[0] {
2108                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2109                         msg.clone()
2110                 },
2111                 _ => panic!("Unexpected event"),
2112         };
2113         if !needs_err_handle {
2114                 match events_2[1] {
2115                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
2116                                 assert_eq!(node_id, nodes[a].node.get_our_node_id());
2117                                 assert_eq!(msg.data, expected_error);
2118                         },
2119                         _ => panic!("Unexpected event"),
2120                 }
2121         }
2122
2123         for node in nodes {
2124                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
2125                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
2126         }
2127 }
2128
2129 pub fn get_announce_close_broadcast_events<'a, 'b, 'c>(nodes: &Vec<Node<'a, 'b, 'c>>, a: usize, b: usize)  {
2130         handle_announce_close_broadcast_events(nodes, a, b, false, "Channel closed because commitment or closing transaction was confirmed on chain.");
2131 }
2132
2133 #[cfg(test)]
2134 macro_rules! get_channel_value_stat {
2135         ($node: expr, $channel_id: expr) => {{
2136                 let chan_lock = $node.node.channel_state.lock().unwrap();
2137                 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
2138                 chan.get_value_stat()
2139         }}
2140 }
2141
2142 macro_rules! get_chan_reestablish_msgs {
2143         ($src_node: expr, $dst_node: expr) => {
2144                 {
2145                         let mut res = Vec::with_capacity(1);
2146                         for msg in $src_node.node.get_and_clear_pending_msg_events() {
2147                                 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
2148                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2149                                         res.push(msg.clone());
2150                                 } else {
2151                                         panic!("Unexpected event")
2152                                 }
2153                         }
2154                         res
2155                 }
2156         }
2157 }
2158
2159 macro_rules! handle_chan_reestablish_msgs {
2160         ($src_node: expr, $dst_node: expr) => {
2161                 {
2162                         let msg_events = $src_node.node.get_and_clear_pending_msg_events();
2163                         let mut idx = 0;
2164                         let funding_locked = if let Some(&MessageSendEvent::SendFundingLocked { ref node_id, ref msg }) = msg_events.get(0) {
2165                                 idx += 1;
2166                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2167                                 Some(msg.clone())
2168                         } else {
2169                                 None
2170                         };
2171
2172                         if let Some(&MessageSendEvent::SendAnnouncementSignatures { ref node_id, msg: _ }) = msg_events.get(idx) {
2173                                 idx += 1;
2174                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2175                         }
2176
2177                         let mut revoke_and_ack = None;
2178                         let mut commitment_update = None;
2179                         let order = if let Some(ev) = msg_events.get(idx) {
2180                                 match ev {
2181                                         &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
2182                                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2183                                                 revoke_and_ack = Some(msg.clone());
2184                                                 idx += 1;
2185                                                 RAACommitmentOrder::RevokeAndACKFirst
2186                                         },
2187                                         &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
2188                                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2189                                                 commitment_update = Some(updates.clone());
2190                                                 idx += 1;
2191                                                 RAACommitmentOrder::CommitmentFirst
2192                                         },
2193                                         _ => RAACommitmentOrder::CommitmentFirst,
2194                                 }
2195                         } else {
2196                                 RAACommitmentOrder::CommitmentFirst
2197                         };
2198
2199                         if let Some(ev) = msg_events.get(idx) {
2200                                 match ev {
2201                                         &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
2202                                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2203                                                 assert!(revoke_and_ack.is_none());
2204                                                 revoke_and_ack = Some(msg.clone());
2205                                                 idx += 1;
2206                                         },
2207                                         &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
2208                                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2209                                                 assert!(commitment_update.is_none());
2210                                                 commitment_update = Some(updates.clone());
2211                                                 idx += 1;
2212                                         },
2213                                         _ => {},
2214                                 }
2215                         }
2216
2217                         if let Some(&MessageSendEvent::SendChannelUpdate { ref node_id, ref msg }) = msg_events.get(idx) {
2218                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2219                                 idx += 1;
2220                                 assert_eq!(msg.contents.flags & 2, 0); // "disabled" flag must not be set as we just reconnected.
2221                         }
2222
2223                         assert_eq!(msg_events.len(), idx);
2224
2225                         (funding_locked, revoke_and_ack, commitment_update, order)
2226                 }
2227         }
2228 }
2229
2230 /// pending_htlc_adds includes both the holding cell and in-flight update_add_htlcs, whereas
2231 /// for claims/fails they are separated out.
2232 pub fn reconnect_nodes<'a, 'b, 'c>(node_a: &Node<'a, 'b, 'c>, node_b: &Node<'a, 'b, 'c>, send_funding_locked: (bool, bool), pending_htlc_adds: (i64, i64), pending_htlc_claims: (usize, usize), pending_htlc_fails: (usize, usize), pending_cell_htlc_claims: (usize, usize), pending_cell_htlc_fails: (usize, usize), pending_raa: (bool, bool))  {
2233         node_a.node.peer_connected(&node_b.node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
2234         let reestablish_1 = get_chan_reestablish_msgs!(node_a, node_b);
2235         node_b.node.peer_connected(&node_a.node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
2236         let reestablish_2 = get_chan_reestablish_msgs!(node_b, node_a);
2237
2238         if send_funding_locked.0 {
2239                 // If a expects a funding_locked, it better not think it has received a revoke_and_ack
2240                 // from b
2241                 for reestablish in reestablish_1.iter() {
2242                         assert_eq!(reestablish.next_remote_commitment_number, 0);
2243                 }
2244         }
2245         if send_funding_locked.1 {
2246                 // If b expects a funding_locked, it better not think it has received a revoke_and_ack
2247                 // from a
2248                 for reestablish in reestablish_2.iter() {
2249                         assert_eq!(reestablish.next_remote_commitment_number, 0);
2250                 }
2251         }
2252         if send_funding_locked.0 || send_funding_locked.1 {
2253                 // If we expect any funding_locked's, both sides better have set
2254                 // next_holder_commitment_number to 1
2255                 for reestablish in reestablish_1.iter() {
2256                         assert_eq!(reestablish.next_local_commitment_number, 1);
2257                 }
2258                 for reestablish in reestablish_2.iter() {
2259                         assert_eq!(reestablish.next_local_commitment_number, 1);
2260                 }
2261         }
2262
2263         let mut resp_1 = Vec::new();
2264         for msg in reestablish_1 {
2265                 node_b.node.handle_channel_reestablish(&node_a.node.get_our_node_id(), &msg);
2266                 resp_1.push(handle_chan_reestablish_msgs!(node_b, node_a));
2267         }
2268         if pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
2269                 check_added_monitors!(node_b, 1);
2270         } else {
2271                 check_added_monitors!(node_b, 0);
2272         }
2273
2274         let mut resp_2 = Vec::new();
2275         for msg in reestablish_2 {
2276                 node_a.node.handle_channel_reestablish(&node_b.node.get_our_node_id(), &msg);
2277                 resp_2.push(handle_chan_reestablish_msgs!(node_a, node_b));
2278         }
2279         if pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
2280                 check_added_monitors!(node_a, 1);
2281         } else {
2282                 check_added_monitors!(node_a, 0);
2283         }
2284
2285         // We don't yet support both needing updates, as that would require a different commitment dance:
2286         assert!((pending_htlc_adds.0 == 0 && pending_htlc_claims.0 == 0 && pending_htlc_fails.0 == 0 &&
2287                          pending_cell_htlc_claims.0 == 0 && pending_cell_htlc_fails.0 == 0) ||
2288                         (pending_htlc_adds.1 == 0 && pending_htlc_claims.1 == 0 && pending_htlc_fails.1 == 0 &&
2289                          pending_cell_htlc_claims.1 == 0 && pending_cell_htlc_fails.1 == 0));
2290
2291         for chan_msgs in resp_1.drain(..) {
2292                 if send_funding_locked.0 {
2293                         node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), &chan_msgs.0.unwrap());
2294                         let announcement_event = node_a.node.get_and_clear_pending_msg_events();
2295                         if !announcement_event.is_empty() {
2296                                 assert_eq!(announcement_event.len(), 1);
2297                                 if let MessageSendEvent::SendChannelUpdate { .. } = announcement_event[0] {
2298                                         //TODO: Test announcement_sigs re-sending
2299                                 } else { panic!("Unexpected event! {:?}", announcement_event[0]); }
2300                         }
2301                 } else {
2302                         assert!(chan_msgs.0.is_none());
2303                 }
2304                 if pending_raa.0 {
2305                         assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
2306                         node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap());
2307                         assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
2308                         check_added_monitors!(node_a, 1);
2309                 } else {
2310                         assert!(chan_msgs.1.is_none());
2311                 }
2312                 if pending_htlc_adds.0 != 0 || pending_htlc_claims.0 != 0 || pending_htlc_fails.0 != 0 || pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
2313                         let commitment_update = chan_msgs.2.unwrap();
2314                         if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
2315                                 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.0 as usize);
2316                         } else {
2317                                 assert!(commitment_update.update_add_htlcs.is_empty());
2318                         }
2319                         assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
2320                         assert_eq!(commitment_update.update_fail_htlcs.len(), pending_htlc_fails.0 + pending_cell_htlc_fails.0);
2321                         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
2322                         for update_add in commitment_update.update_add_htlcs {
2323                                 node_a.node.handle_update_add_htlc(&node_b.node.get_our_node_id(), &update_add);
2324                         }
2325                         for update_fulfill in commitment_update.update_fulfill_htlcs {
2326                                 node_a.node.handle_update_fulfill_htlc(&node_b.node.get_our_node_id(), &update_fulfill);
2327                         }
2328                         for update_fail in commitment_update.update_fail_htlcs {
2329                                 node_a.node.handle_update_fail_htlc(&node_b.node.get_our_node_id(), &update_fail);
2330                         }
2331
2332                         if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
2333                                 commitment_signed_dance!(node_a, node_b, commitment_update.commitment_signed, false);
2334                         } else {
2335                                 node_a.node.handle_commitment_signed(&node_b.node.get_our_node_id(), &commitment_update.commitment_signed);
2336                                 check_added_monitors!(node_a, 1);
2337                                 let as_revoke_and_ack = get_event_msg!(node_a, MessageSendEvent::SendRevokeAndACK, node_b.node.get_our_node_id());
2338                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
2339                                 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &as_revoke_and_ack);
2340                                 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
2341                                 check_added_monitors!(node_b, 1);
2342                         }
2343                 } else {
2344                         assert!(chan_msgs.2.is_none());
2345                 }
2346         }
2347
2348         for chan_msgs in resp_2.drain(..) {
2349                 if send_funding_locked.1 {
2350                         node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &chan_msgs.0.unwrap());
2351                         let announcement_event = node_b.node.get_and_clear_pending_msg_events();
2352                         if !announcement_event.is_empty() {
2353                                 assert_eq!(announcement_event.len(), 1);
2354                                 match announcement_event[0] {
2355                                         MessageSendEvent::SendChannelUpdate { .. } => {},
2356                                         MessageSendEvent::SendAnnouncementSignatures { .. } => {},
2357                                         _ => panic!("Unexpected event {:?}!", announcement_event[0]),
2358                                 }
2359                         }
2360                 } else {
2361                         assert!(chan_msgs.0.is_none());
2362                 }
2363                 if pending_raa.1 {
2364                         assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
2365                         node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap());
2366                         assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
2367                         check_added_monitors!(node_b, 1);
2368                 } else {
2369                         assert!(chan_msgs.1.is_none());
2370                 }
2371                 if pending_htlc_adds.1 != 0 || pending_htlc_claims.1 != 0 || pending_htlc_fails.1 != 0 || pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
2372                         let commitment_update = chan_msgs.2.unwrap();
2373                         if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
2374                                 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.1 as usize);
2375                         }
2376                         assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.1 + pending_cell_htlc_claims.1);
2377                         assert_eq!(commitment_update.update_fail_htlcs.len(), pending_htlc_fails.1 + pending_cell_htlc_fails.1);
2378                         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
2379                         for update_add in commitment_update.update_add_htlcs {
2380                                 node_b.node.handle_update_add_htlc(&node_a.node.get_our_node_id(), &update_add);
2381                         }
2382                         for update_fulfill in commitment_update.update_fulfill_htlcs {
2383                                 node_b.node.handle_update_fulfill_htlc(&node_a.node.get_our_node_id(), &update_fulfill);
2384                         }
2385                         for update_fail in commitment_update.update_fail_htlcs {
2386                                 node_b.node.handle_update_fail_htlc(&node_a.node.get_our_node_id(), &update_fail);
2387                         }
2388
2389                         if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
2390                                 commitment_signed_dance!(node_b, node_a, commitment_update.commitment_signed, false);
2391                         } else {
2392                                 node_b.node.handle_commitment_signed(&node_a.node.get_our_node_id(), &commitment_update.commitment_signed);
2393                                 check_added_monitors!(node_b, 1);
2394                                 let bs_revoke_and_ack = get_event_msg!(node_b, MessageSendEvent::SendRevokeAndACK, node_a.node.get_our_node_id());
2395                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
2396                                 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &bs_revoke_and_ack);
2397                                 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
2398                                 check_added_monitors!(node_a, 1);
2399                         }
2400                 } else {
2401                         assert!(chan_msgs.2.is_none());
2402                 }
2403         }
2404 }