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