Avoid attempting to forward to a closed chan on stale-data reload
[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         assert_eq!(node_a.node.list_channels().iter().find(|channel| channel.channel_id == create_chan_id).unwrap().user_channel_id, 42);
810         node_b.node.handle_open_channel(&node_a.node.get_our_node_id(), a_flags, &open_channel_msg);
811         let accept_channel_msg = get_event_msg!(node_b, MessageSendEvent::SendAcceptChannel, node_a.node.get_our_node_id());
812         assert_eq!(accept_channel_msg.temporary_channel_id, create_chan_id);
813         node_a.node.handle_accept_channel(&node_b.node.get_our_node_id(), b_flags, &accept_channel_msg);
814         assert_ne!(node_b.node.list_channels().iter().find(|channel| channel.channel_id == create_chan_id).unwrap().user_channel_id, 0);
815
816         sign_funding_transaction(node_a, node_b, channel_value, create_chan_id)
817 }
818
819 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) {
820         confirm_transaction_at(node_conf, tx, conf_height);
821         connect_blocks(node_conf, CHAN_CONFIRM_DEPTH - 1);
822         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()));
823 }
824
825 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]) {
826         let channel_id;
827         let events_6 = node_conf.node.get_and_clear_pending_msg_events();
828         assert_eq!(events_6.len(), 3);
829         let announcement_sigs_idx = if let MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } = events_6[1] {
830                 assert_eq!(*node_id, node_recv.node.get_our_node_id());
831                 2
832         } else if let MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } = events_6[2] {
833                 assert_eq!(*node_id, node_recv.node.get_our_node_id());
834                 1
835         } else { panic!("Unexpected event: {:?}", events_6[1]); };
836         ((match events_6[0] {
837                 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
838                         channel_id = msg.channel_id.clone();
839                         assert_eq!(*node_id, node_recv.node.get_our_node_id());
840                         msg.clone()
841                 },
842                 _ => panic!("Unexpected event"),
843         }, match events_6[announcement_sigs_idx] {
844                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
845                         assert_eq!(*node_id, node_recv.node.get_our_node_id());
846                         msg.clone()
847                 },
848                 _ => panic!("Unexpected event"),
849         }), channel_id)
850 }
851
852 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]) {
853         let conf_height = core::cmp::max(node_a.best_block_info().1 + 1, node_b.best_block_info().1 + 1);
854         create_chan_between_nodes_with_value_confirm_first(node_a, node_b, tx, conf_height);
855         confirm_transaction_at(node_a, tx, conf_height);
856         connect_blocks(node_a, CHAN_CONFIRM_DEPTH - 1);
857         expect_channel_ready_event(&node_a, &node_b.node.get_our_node_id());
858         create_chan_between_nodes_with_value_confirm_second(node_b, node_a)
859 }
860
861 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) {
862         let tx = create_chan_between_nodes_with_value_init(node_a, node_b, channel_value, push_msat, a_flags, b_flags);
863         let (msgs, chan_id) = create_chan_between_nodes_with_value_confirm(node_a, node_b, &tx);
864         (msgs, chan_id, tx)
865 }
866
867 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) {
868         node_b.node.handle_channel_ready(&node_a.node.get_our_node_id(), &as_funding_msgs.0);
869         let bs_announcement_sigs = get_event_msg!(node_b, MessageSendEvent::SendAnnouncementSignatures, node_a.node.get_our_node_id());
870         node_b.node.handle_announcement_signatures(&node_a.node.get_our_node_id(), &as_funding_msgs.1);
871
872         let events_7 = node_b.node.get_and_clear_pending_msg_events();
873         assert_eq!(events_7.len(), 1);
874         let (announcement, bs_update) = match events_7[0] {
875                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
876                         (msg, update_msg)
877                 },
878                 _ => panic!("Unexpected event"),
879         };
880
881         node_a.node.handle_announcement_signatures(&node_b.node.get_our_node_id(), &bs_announcement_sigs);
882         let events_8 = node_a.node.get_and_clear_pending_msg_events();
883         assert_eq!(events_8.len(), 1);
884         let as_update = match events_8[0] {
885                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
886                         assert!(*announcement == *msg);
887                         assert_eq!(update_msg.contents.short_channel_id, announcement.contents.short_channel_id);
888                         assert_eq!(update_msg.contents.short_channel_id, bs_update.contents.short_channel_id);
889                         update_msg
890                 },
891                 _ => panic!("Unexpected event"),
892         };
893
894         *node_a.network_chan_count.borrow_mut() += 1;
895
896         expect_channel_ready_event(&node_b, &node_a.node.get_our_node_id());
897         ((*announcement).clone(), (*as_update).clone(), (*bs_update).clone())
898 }
899
900 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) {
901         create_announced_chan_between_nodes_with_value(nodes, a, b, 100000, 10001, a_flags, b_flags)
902 }
903
904 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) {
905         let chan_announcement = create_chan_between_nodes_with_value(&nodes[a], &nodes[b], channel_value, push_msat, a_flags, b_flags);
906         update_nodes_with_chan_announce(nodes, a, b, &chan_announcement.0, &chan_announcement.1, &chan_announcement.2);
907         (chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
908 }
909
910 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) {
911         let mut no_announce_cfg = test_default_channel_config();
912         no_announce_cfg.channel_handshake_config.announced_channel = false;
913         nodes[a].node.create_channel(nodes[b].node.get_our_node_id(), channel_value, push_msat, 42, Some(no_announce_cfg)).unwrap();
914         let open_channel = get_event_msg!(nodes[a], MessageSendEvent::SendOpenChannel, nodes[b].node.get_our_node_id());
915         nodes[b].node.handle_open_channel(&nodes[a].node.get_our_node_id(), a_flags, &open_channel);
916         let accept_channel = get_event_msg!(nodes[b], MessageSendEvent::SendAcceptChannel, nodes[a].node.get_our_node_id());
917         nodes[a].node.handle_accept_channel(&nodes[b].node.get_our_node_id(), b_flags, &accept_channel);
918
919         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[a], &nodes[b].node.get_our_node_id(), channel_value, 42);
920         nodes[a].node.funding_transaction_generated(&temporary_channel_id, &nodes[b].node.get_our_node_id(), tx.clone()).unwrap();
921         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()));
922         check_added_monitors!(nodes[b], 1);
923
924         let cs_funding_signed = get_event_msg!(nodes[b], MessageSendEvent::SendFundingSigned, nodes[a].node.get_our_node_id());
925         nodes[a].node.handle_funding_signed(&nodes[b].node.get_our_node_id(), &cs_funding_signed);
926         check_added_monitors!(nodes[a], 1);
927
928         let conf_height = core::cmp::max(nodes[a].best_block_info().1 + 1, nodes[b].best_block_info().1 + 1);
929         confirm_transaction_at(&nodes[a], &tx, conf_height);
930         connect_blocks(&nodes[a], CHAN_CONFIRM_DEPTH - 1);
931         confirm_transaction_at(&nodes[b], &tx, conf_height);
932         connect_blocks(&nodes[b], CHAN_CONFIRM_DEPTH - 1);
933         let as_channel_ready = get_event_msg!(nodes[a], MessageSendEvent::SendChannelReady, nodes[b].node.get_our_node_id());
934         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()));
935         expect_channel_ready_event(&nodes[a], &nodes[b].node.get_our_node_id());
936         let as_update = get_event_msg!(nodes[a], MessageSendEvent::SendChannelUpdate, nodes[b].node.get_our_node_id());
937         nodes[b].node.handle_channel_ready(&nodes[a].node.get_our_node_id(), &as_channel_ready);
938         expect_channel_ready_event(&nodes[b], &nodes[a].node.get_our_node_id());
939         let bs_update = get_event_msg!(nodes[b], MessageSendEvent::SendChannelUpdate, nodes[a].node.get_our_node_id());
940
941         nodes[a].node.handle_channel_update(&nodes[b].node.get_our_node_id(), &bs_update);
942         nodes[b].node.handle_channel_update(&nodes[a].node.get_our_node_id(), &as_update);
943
944         let mut found_a = false;
945         for chan in nodes[a].node.list_usable_channels() {
946                 if chan.channel_id == as_channel_ready.channel_id {
947                         assert!(!found_a);
948                         found_a = true;
949                         assert!(!chan.is_public);
950                 }
951         }
952         assert!(found_a);
953
954         let mut found_b = false;
955         for chan in nodes[b].node.list_usable_channels() {
956                 if chan.channel_id == as_channel_ready.channel_id {
957                         assert!(!found_b);
958                         found_b = true;
959                         assert!(!chan.is_public);
960                 }
961         }
962         assert!(found_b);
963
964         (as_channel_ready, tx)
965 }
966
967 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) {
968         for node in nodes {
969                 assert!(node.gossip_sync.handle_channel_announcement(ann).unwrap());
970                 node.gossip_sync.handle_channel_update(upd_1).unwrap();
971                 node.gossip_sync.handle_channel_update(upd_2).unwrap();
972
973                 // Note that channel_updates are also delivered to ChannelManagers to ensure we have
974                 // forwarding info for local channels even if its not accepted in the network graph.
975                 node.node.handle_channel_update(&nodes[a].node.get_our_node_id(), &upd_1);
976                 node.node.handle_channel_update(&nodes[b].node.get_our_node_id(), &upd_2);
977         }
978 }
979
980 #[macro_export]
981 macro_rules! check_spends {
982         ($tx: expr, $($spends_txn: expr),*) => {
983                 {
984                         $(
985                         for outp in $spends_txn.output.iter() {
986                                 assert!(outp.value >= outp.script_pubkey.dust_value().to_sat(), "Input tx output didn't meet dust limit");
987                         }
988                         )*
989                         for outp in $tx.output.iter() {
990                                 assert!(outp.value >= outp.script_pubkey.dust_value().to_sat(), "Spending tx output didn't meet dust limit");
991                         }
992                         let get_output = |out_point: &bitcoin::blockdata::transaction::OutPoint| {
993                                 $(
994                                         if out_point.txid == $spends_txn.txid() {
995                                                 return $spends_txn.output.get(out_point.vout as usize).cloned()
996                                         }
997                                 )*
998                                 None
999                         };
1000                         let mut total_value_in = 0;
1001                         for input in $tx.input.iter() {
1002                                 total_value_in += get_output(&input.previous_output).unwrap().value;
1003                         }
1004                         let mut total_value_out = 0;
1005                         for output in $tx.output.iter() {
1006                                 total_value_out += output.value;
1007                         }
1008                         let min_fee = ($tx.weight() as u64 + 3) / 4; // One sat per vbyte (ie per weight/4, rounded up)
1009                         // Input amount - output amount = fee, so check that out + min_fee is smaller than input
1010                         assert!(total_value_out + min_fee <= total_value_in);
1011                         $tx.verify(get_output).unwrap();
1012                 }
1013         }
1014 }
1015
1016 macro_rules! get_closing_signed_broadcast {
1017         ($node: expr, $dest_pubkey: expr) => {
1018                 {
1019                         let events = $node.get_and_clear_pending_msg_events();
1020                         assert!(events.len() == 1 || events.len() == 2);
1021                         (match events[events.len() - 1] {
1022                                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
1023                                         assert_eq!(msg.contents.flags & 2, 2);
1024                                         msg.clone()
1025                                 },
1026                                 _ => panic!("Unexpected event"),
1027                         }, if events.len() == 2 {
1028                                 match events[0] {
1029                                         MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
1030                                                 assert_eq!(*node_id, $dest_pubkey);
1031                                                 Some(msg.clone())
1032                                         },
1033                                         _ => panic!("Unexpected event"),
1034                                 }
1035                         } else { None })
1036                 }
1037         }
1038 }
1039
1040 #[cfg(test)]
1041 macro_rules! check_warn_msg {
1042         ($node: expr, $recipient_node_id: expr, $chan_id: expr) => {{
1043                 let msg_events = $node.node.get_and_clear_pending_msg_events();
1044                 assert_eq!(msg_events.len(), 1);
1045                 match msg_events[0] {
1046                         MessageSendEvent::HandleError { action: ErrorAction::SendWarningMessage { ref msg, log_level: _ }, node_id } => {
1047                                 assert_eq!(node_id, $recipient_node_id);
1048                                 assert_eq!(msg.channel_id, $chan_id);
1049                                 msg.data.clone()
1050                         },
1051                         _ => panic!("Unexpected event"),
1052                 }
1053         }}
1054 }
1055
1056 /// Check that a channel's closing channel update has been broadcasted, and optionally
1057 /// check whether an error message event has occurred.
1058 #[macro_export]
1059 macro_rules! check_closed_broadcast {
1060         ($node: expr, $with_error_msg: expr) => {{
1061                 use $crate::util::events::MessageSendEvent;
1062                 use $crate::ln::msgs::ErrorAction;
1063
1064                 let msg_events = $node.node.get_and_clear_pending_msg_events();
1065                 assert_eq!(msg_events.len(), if $with_error_msg { 2 } else { 1 });
1066                 match msg_events[0] {
1067                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
1068                                 assert_eq!(msg.contents.flags & 2, 2);
1069                         },
1070                         _ => panic!("Unexpected event"),
1071                 }
1072                 if $with_error_msg {
1073                         match msg_events[1] {
1074                                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1075                                         // TODO: Check node_id
1076                                         Some(msg.clone())
1077                                 },
1078                                 _ => panic!("Unexpected event"),
1079                         }
1080                 } else { None }
1081         }}
1082 }
1083
1084 /// Check that a channel's closing channel events has been issued
1085 #[macro_export]
1086 macro_rules! check_closed_event {
1087         ($node: expr, $events: expr, $reason: expr) => {
1088                 check_closed_event!($node, $events, $reason, false);
1089         };
1090         ($node: expr, $events: expr, $reason: expr, $is_check_discard_funding: expr) => {{
1091                 use $crate::util::events::Event;
1092
1093                 let events = $node.node.get_and_clear_pending_events();
1094                 assert_eq!(events.len(), $events, "{:?}", events);
1095                 let expected_reason = $reason;
1096                 let mut issues_discard_funding = false;
1097                 for event in events {
1098                         match event {
1099                                 Event::ChannelClosed { ref reason, .. } => {
1100                                         assert_eq!(*reason, expected_reason);
1101                                 },
1102                                 Event::DiscardFunding { .. } => {
1103                                         issues_discard_funding = true;
1104                                 }
1105                                 _ => panic!("Unexpected event"),
1106                         }
1107                 }
1108                 assert_eq!($is_check_discard_funding, issues_discard_funding);
1109         }}
1110 }
1111
1112 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) {
1113         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) };
1114         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) };
1115         let (tx_a, tx_b);
1116
1117         node_a.close_channel(channel_id, &node_b.get_our_node_id()).unwrap();
1118         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()));
1119
1120         let events_1 = node_b.get_and_clear_pending_msg_events();
1121         assert!(events_1.len() >= 1);
1122         let shutdown_b = match events_1[0] {
1123                 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
1124                         assert_eq!(node_id, &node_a.get_our_node_id());
1125                         msg.clone()
1126                 },
1127                 _ => panic!("Unexpected event"),
1128         };
1129
1130         let closing_signed_b = if !close_inbound_first {
1131                 assert_eq!(events_1.len(), 1);
1132                 None
1133         } else {
1134                 Some(match events_1[1] {
1135                         MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
1136                                 assert_eq!(node_id, &node_a.get_our_node_id());
1137                                 msg.clone()
1138                         },
1139                         _ => panic!("Unexpected event"),
1140                 })
1141         };
1142
1143         node_a.handle_shutdown(&node_b.get_our_node_id(), &channelmanager::provided_init_features(), &shutdown_b);
1144         let (as_update, bs_update) = if close_inbound_first {
1145                 assert!(node_a.get_and_clear_pending_msg_events().is_empty());
1146                 node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap());
1147
1148                 node_b.handle_closing_signed(&node_a.get_our_node_id(), &get_event_msg!(struct_a, MessageSendEvent::SendClosingSigned, node_b.get_our_node_id()));
1149                 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
1150                 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
1151                 let (bs_update, closing_signed_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
1152
1153                 node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap());
1154                 let (as_update, none_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
1155                 assert!(none_a.is_none());
1156                 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
1157                 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
1158                 (as_update, bs_update)
1159         } else {
1160                 let closing_signed_a = get_event_msg!(struct_a, MessageSendEvent::SendClosingSigned, node_b.get_our_node_id());
1161
1162                 node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a);
1163                 node_a.handle_closing_signed(&node_b.get_our_node_id(), &get_event_msg!(struct_b, MessageSendEvent::SendClosingSigned, node_a.get_our_node_id()));
1164
1165                 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
1166                 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
1167                 let (as_update, closing_signed_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
1168
1169                 node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap());
1170                 let (bs_update, none_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
1171                 assert!(none_b.is_none());
1172                 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
1173                 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
1174                 (as_update, bs_update)
1175         };
1176         assert_eq!(tx_a, tx_b);
1177         check_spends!(tx_a, funding_tx);
1178
1179         (as_update, bs_update, tx_a)
1180 }
1181
1182 pub struct SendEvent {
1183         pub node_id: PublicKey,
1184         pub msgs: Vec<msgs::UpdateAddHTLC>,
1185         pub commitment_msg: msgs::CommitmentSigned,
1186 }
1187 impl SendEvent {
1188         pub fn from_commitment_update(node_id: PublicKey, updates: msgs::CommitmentUpdate) -> SendEvent {
1189                 assert!(updates.update_fulfill_htlcs.is_empty());
1190                 assert!(updates.update_fail_htlcs.is_empty());
1191                 assert!(updates.update_fail_malformed_htlcs.is_empty());
1192                 assert!(updates.update_fee.is_none());
1193                 SendEvent { node_id, msgs: updates.update_add_htlcs, commitment_msg: updates.commitment_signed }
1194         }
1195
1196         pub fn from_event(event: MessageSendEvent) -> SendEvent {
1197                 match event {
1198                         MessageSendEvent::UpdateHTLCs { node_id, updates } => SendEvent::from_commitment_update(node_id, updates),
1199                         _ => panic!("Unexpected event type!"),
1200                 }
1201         }
1202
1203         pub fn from_node<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>) -> SendEvent {
1204                 let mut events = node.node.get_and_clear_pending_msg_events();
1205                 assert_eq!(events.len(), 1);
1206                 SendEvent::from_event(events.pop().unwrap())
1207         }
1208 }
1209
1210 #[macro_export]
1211 /// Performs the "commitment signed dance" - the series of message exchanges which occur after a
1212 /// commitment update.
1213 macro_rules! commitment_signed_dance {
1214         ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */) => {
1215                 {
1216                         check_added_monitors!($node_a, 0);
1217                         assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
1218                         $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed);
1219                         check_added_monitors!($node_a, 1);
1220                         commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, false);
1221                 }
1222         };
1223         ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */, true /* return last RAA */) => {
1224                 {
1225                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!($node_a, $node_b.node.get_our_node_id());
1226                         check_added_monitors!($node_b, 0);
1227                         assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
1228                         $node_b.node.handle_revoke_and_ack(&$node_a.node.get_our_node_id(), &as_revoke_and_ack);
1229                         assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
1230                         check_added_monitors!($node_b, 1);
1231                         $node_b.node.handle_commitment_signed(&$node_a.node.get_our_node_id(), &as_commitment_signed);
1232                         let (bs_revoke_and_ack, extra_msg_option) = {
1233                                 let events = $node_b.node.get_and_clear_pending_msg_events();
1234                                 assert!(events.len() <= 2);
1235                                 (match events[0] {
1236                                         MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
1237                                                 assert_eq!(*node_id, $node_a.node.get_our_node_id());
1238                                                 (*msg).clone()
1239                                         },
1240                                         _ => panic!("Unexpected event"),
1241                                 }, events.get(1).map(|e| e.clone()))
1242                         };
1243                         check_added_monitors!($node_b, 1);
1244                         if $fail_backwards {
1245                                 assert!($node_a.node.get_and_clear_pending_events().is_empty());
1246                                 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
1247                         }
1248                         (extra_msg_option, bs_revoke_and_ack)
1249                 }
1250         };
1251         ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */, false /* return extra message */, true /* return last RAA */) => {
1252                 {
1253                         check_added_monitors!($node_a, 0);
1254                         assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
1255                         $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed);
1256                         check_added_monitors!($node_a, 1);
1257                         let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
1258                         assert!(extra_msg_option.is_none());
1259                         bs_revoke_and_ack
1260                 }
1261         };
1262         ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */) => {
1263                 {
1264                         let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
1265                         $node_a.node.handle_revoke_and_ack(&$node_b.node.get_our_node_id(), &bs_revoke_and_ack);
1266                         check_added_monitors!($node_a, 1);
1267                         extra_msg_option
1268                 }
1269         };
1270         ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, false /* no extra message */) => {
1271                 {
1272                         assert!(commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true).is_none());
1273                 }
1274         };
1275         ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr) => {
1276                 {
1277                         commitment_signed_dance!($node_a, $node_b, $commitment_signed, $fail_backwards, true);
1278                         if $fail_backwards {
1279                                 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 }]);
1280                                 check_added_monitors!($node_a, 1);
1281
1282                                 let channel_state = $node_a.node.channel_state.lock().unwrap();
1283                                 assert_eq!(channel_state.pending_msg_events.len(), 1);
1284                                 if let MessageSendEvent::UpdateHTLCs { ref node_id, .. } = channel_state.pending_msg_events[0] {
1285                                         assert_ne!(*node_id, $node_b.node.get_our_node_id());
1286                                 } else { panic!("Unexpected event"); }
1287                         } else {
1288                                 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
1289                         }
1290                 }
1291         }
1292 }
1293
1294 /// Get a payment preimage and hash.
1295 #[macro_export]
1296 macro_rules! get_payment_preimage_hash {
1297         ($dest_node: expr) => {
1298                 {
1299                         get_payment_preimage_hash!($dest_node, None)
1300                 }
1301         };
1302         ($dest_node: expr, $min_value_msat: expr) => {
1303                 {
1304                         use bitcoin::hashes::Hash as _;
1305                         let mut payment_count = $dest_node.network_payment_count.borrow_mut();
1306                         let payment_preimage = $crate::ln::PaymentPreimage([*payment_count; 32]);
1307                         *payment_count += 1;
1308                         let payment_hash = $crate::ln::PaymentHash(
1309                                 bitcoin::hashes::sha256::Hash::hash(&payment_preimage.0[..]).into_inner());
1310                         let payment_secret = $dest_node.node.create_inbound_payment_for_hash(payment_hash, $min_value_msat, 7200).unwrap();
1311                         (payment_preimage, payment_hash, payment_secret)
1312                 }
1313         }
1314 }
1315
1316 #[macro_export]
1317 macro_rules! get_route {
1318         ($send_node: expr, $payment_params: expr, $recv_value: expr, $cltv: expr) => {{
1319                 use $crate::chain::keysinterface::KeysInterface;
1320                 let scorer = $crate::util::test_utils::TestScorer::with_penalty(0);
1321                 let keys_manager = $crate::util::test_utils::TestKeysInterface::new(&[0u8; 32], bitcoin::network::constants::Network::Testnet);
1322                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
1323                 $crate::routing::router::get_route(
1324                         &$send_node.node.get_our_node_id(), &$payment_params, &$send_node.network_graph.read_only(),
1325                         Some(&$send_node.node.list_usable_channels().iter().collect::<Vec<_>>()),
1326                         $recv_value, $cltv, $send_node.logger, &scorer, &random_seed_bytes
1327                 )
1328         }}
1329 }
1330
1331 #[cfg(test)]
1332 #[macro_export]
1333 macro_rules! get_route_and_payment_hash {
1334         ($send_node: expr, $recv_node: expr, $recv_value: expr) => {{
1335                 let payment_params = $crate::routing::router::PaymentParameters::from_node_id($recv_node.node.get_our_node_id())
1336                         .with_features($crate::ln::channelmanager::provided_invoice_features());
1337                 $crate::get_route_and_payment_hash!($send_node, $recv_node, payment_params, $recv_value, TEST_FINAL_CLTV)
1338         }};
1339         ($send_node: expr, $recv_node: expr, $payment_params: expr, $recv_value: expr, $cltv: expr) => {{
1340                 let (payment_preimage, payment_hash, payment_secret) = $crate::get_payment_preimage_hash!($recv_node, Some($recv_value));
1341                 let route = $crate::get_route!($send_node, $payment_params, $recv_value, $cltv);
1342                 (route.unwrap(), payment_hash, payment_preimage, payment_secret)
1343         }}
1344 }
1345
1346 #[macro_export]
1347 macro_rules! expect_pending_htlcs_forwardable_conditions {
1348         ($node: expr, $expected_failures: expr) => {{
1349                 let expected_failures = $expected_failures;
1350                 let events = $node.node.get_and_clear_pending_events();
1351                 match events[0] {
1352                         $crate::util::events::Event::PendingHTLCsForwardable { .. } => { },
1353                         _ => panic!("Unexpected event {:?}", events),
1354                 };
1355
1356                 let count = expected_failures.len() + 1;
1357                 assert_eq!(events.len(), count);
1358
1359                 if expected_failures.len() > 0 {
1360                         expect_htlc_handling_failed_destinations!(events, expected_failures)
1361                 }
1362         }}
1363 }
1364
1365 #[macro_export]
1366 macro_rules! expect_htlc_handling_failed_destinations {
1367         ($events: expr, $expected_failures: expr) => {{
1368                 for event in $events {
1369                         match event {
1370                                 $crate::util::events::Event::PendingHTLCsForwardable { .. } => { },
1371                                 $crate::util::events::Event::HTLCHandlingFailed { ref failed_next_destination, .. } => {
1372                                         assert!($expected_failures.contains(&failed_next_destination))
1373                                 },
1374                                 _ => panic!("Unexpected destination"),
1375                         }
1376                 }
1377         }}
1378 }
1379
1380 #[macro_export]
1381 /// Clears (and ignores) a PendingHTLCsForwardable event
1382 macro_rules! expect_pending_htlcs_forwardable_ignore {
1383         ($node: expr) => {{
1384                 expect_pending_htlcs_forwardable_conditions!($node, vec![]);
1385         }};
1386 }
1387
1388 #[macro_export]
1389 /// Clears (and ignores) PendingHTLCsForwardable and HTLCHandlingFailed events
1390 macro_rules! expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore {
1391         ($node: expr, $expected_failures: expr) => {{
1392                 expect_pending_htlcs_forwardable_conditions!($node, $expected_failures);
1393         }};
1394 }
1395
1396 #[macro_export]
1397 /// Handles a PendingHTLCsForwardable event
1398 macro_rules! expect_pending_htlcs_forwardable {
1399         ($node: expr) => {{
1400                 expect_pending_htlcs_forwardable_ignore!($node);
1401                 $node.node.process_pending_htlc_forwards();
1402
1403                 // Ensure process_pending_htlc_forwards is idempotent.
1404                 $node.node.process_pending_htlc_forwards();
1405         }};
1406 }
1407
1408 #[macro_export]
1409 /// Handles a PendingHTLCsForwardable and HTLCHandlingFailed event
1410 macro_rules! expect_pending_htlcs_forwardable_and_htlc_handling_failed {
1411         ($node: expr, $expected_failures: expr) => {{
1412                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!($node, $expected_failures);
1413                 $node.node.process_pending_htlc_forwards();
1414
1415                 // Ensure process_pending_htlc_forwards is idempotent.
1416                 $node.node.process_pending_htlc_forwards();
1417         }}
1418 }
1419
1420 #[cfg(test)]
1421 macro_rules! expect_pending_htlcs_forwardable_from_events {
1422         ($node: expr, $events: expr, $ignore: expr) => {{
1423                 assert_eq!($events.len(), 1);
1424                 match $events[0] {
1425                         Event::PendingHTLCsForwardable { .. } => { },
1426                         _ => panic!("Unexpected event"),
1427                 };
1428                 if $ignore {
1429                         $node.node.process_pending_htlc_forwards();
1430
1431                         // Ensure process_pending_htlc_forwards is idempotent.
1432                         $node.node.process_pending_htlc_forwards();
1433                 }
1434         }}
1435 }
1436
1437 #[macro_export]
1438 #[cfg(any(test, feature = "_bench_unstable", feature = "_test_utils"))]
1439 macro_rules! expect_payment_received {
1440         ($node: expr, $expected_payment_hash: expr, $expected_payment_secret: expr, $expected_recv_value: expr) => {
1441                 expect_payment_received!($node, $expected_payment_hash, $expected_payment_secret, $expected_recv_value, None)
1442         };
1443         ($node: expr, $expected_payment_hash: expr, $expected_payment_secret: expr, $expected_recv_value: expr, $expected_payment_preimage: expr) => {
1444                 let events = $node.node.get_and_clear_pending_events();
1445                 assert_eq!(events.len(), 1);
1446                 match events[0] {
1447                         $crate::util::events::Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
1448                                 assert_eq!($expected_payment_hash, *payment_hash);
1449                                 assert_eq!($expected_recv_value, amount_msat);
1450                                 match purpose {
1451                                         $crate::util::events::PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1452                                                 assert_eq!(&$expected_payment_preimage, payment_preimage);
1453                                                 assert_eq!($expected_payment_secret, *payment_secret);
1454                                         },
1455                                         _ => {},
1456                                 }
1457                         },
1458                         _ => panic!("Unexpected event"),
1459                 }
1460         }
1461 }
1462
1463 #[macro_export]
1464 #[cfg(any(test, feature = "_bench_unstable", feature = "_test_utils"))]
1465 macro_rules! expect_payment_claimed {
1466         ($node: expr, $expected_payment_hash: expr, $expected_recv_value: expr) => {
1467                 let events = $node.node.get_and_clear_pending_events();
1468                 assert_eq!(events.len(), 1);
1469                 match events[0] {
1470                         $crate::util::events::Event::PaymentClaimed { ref payment_hash, amount_msat, .. } => {
1471                                 assert_eq!($expected_payment_hash, *payment_hash);
1472                                 assert_eq!($expected_recv_value, amount_msat);
1473                         },
1474                         _ => panic!("Unexpected event"),
1475                 }
1476         }
1477 }
1478
1479 #[cfg(test)]
1480 #[macro_export]
1481 macro_rules! expect_payment_sent_without_paths {
1482         ($node: expr, $expected_payment_preimage: expr) => {
1483                 expect_payment_sent!($node, $expected_payment_preimage, None::<u64>, false);
1484         };
1485         ($node: expr, $expected_payment_preimage: expr, $expected_fee_msat_opt: expr) => {
1486                 expect_payment_sent!($node, $expected_payment_preimage, $expected_fee_msat_opt, false);
1487         }
1488 }
1489
1490 #[macro_export]
1491 macro_rules! expect_payment_sent {
1492         ($node: expr, $expected_payment_preimage: expr) => {
1493                 $crate::expect_payment_sent!($node, $expected_payment_preimage, None::<u64>, true);
1494         };
1495         ($node: expr, $expected_payment_preimage: expr, $expected_fee_msat_opt: expr) => {
1496                 $crate::expect_payment_sent!($node, $expected_payment_preimage, $expected_fee_msat_opt, true);
1497         };
1498         ($node: expr, $expected_payment_preimage: expr, $expected_fee_msat_opt: expr, $expect_paths: expr) => { {
1499                 use bitcoin::hashes::Hash as _;
1500                 let events = $node.node.get_and_clear_pending_events();
1501                 let expected_payment_hash = $crate::ln::PaymentHash(
1502                         bitcoin::hashes::sha256::Hash::hash(&$expected_payment_preimage.0).into_inner());
1503                 if $expect_paths {
1504                         assert!(events.len() > 1);
1505                 } else {
1506                         assert_eq!(events.len(), 1);
1507                 }
1508                 let expected_payment_id = match events[0] {
1509                         $crate::util::events::Event::PaymentSent { ref payment_id, ref payment_preimage, ref payment_hash, ref fee_paid_msat } => {
1510                                 assert_eq!($expected_payment_preimage, *payment_preimage);
1511                                 assert_eq!(expected_payment_hash, *payment_hash);
1512                                 assert!(fee_paid_msat.is_some());
1513                                 if $expected_fee_msat_opt.is_some() {
1514                                         assert_eq!(*fee_paid_msat, $expected_fee_msat_opt);
1515                                 }
1516                                 payment_id.unwrap()
1517                         },
1518                         _ => panic!("Unexpected event"),
1519                 };
1520                 if $expect_paths {
1521                         for i in 1..events.len() {
1522                                 match events[i] {
1523                                         $crate::util::events::Event::PaymentPathSuccessful { payment_id, payment_hash, .. } => {
1524                                                 assert_eq!(payment_id, expected_payment_id);
1525                                                 assert_eq!(payment_hash, Some(expected_payment_hash));
1526                                         },
1527                                         _ => panic!("Unexpected event"),
1528                                 }
1529                         }
1530                 }
1531         } }
1532 }
1533
1534 #[cfg(test)]
1535 #[macro_export]
1536 macro_rules! expect_payment_path_successful {
1537         ($node: expr) => {
1538                 let events = $node.node.get_and_clear_pending_events();
1539                 assert_eq!(events.len(), 1);
1540                 match events[0] {
1541                         $crate::util::events::Event::PaymentPathSuccessful { .. } => {},
1542                         _ => panic!("Unexpected event"),
1543                 }
1544         }
1545 }
1546
1547 macro_rules! expect_payment_forwarded {
1548         ($node: expr, $prev_node: expr, $next_node: expr, $expected_fee: expr, $upstream_force_closed: expr, $downstream_force_closed: expr) => {
1549                 let events = $node.node.get_and_clear_pending_events();
1550                 assert_eq!(events.len(), 1);
1551                 match events[0] {
1552                         Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
1553                                 assert_eq!(fee_earned_msat, $expected_fee);
1554                                 if fee_earned_msat.is_some() {
1555                                         // Is the event prev_channel_id in one of the channels between the two nodes?
1556                                         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()));
1557                                 }
1558                                 // We check for force closures since a force closed channel is removed from the
1559                                 // node's channel list
1560                                 if !$downstream_force_closed {
1561                                         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()));
1562                                 }
1563                                 assert_eq!(claim_from_onchain_tx, $downstream_force_closed);
1564                         },
1565                         _ => panic!("Unexpected event"),
1566                 }
1567         }
1568 }
1569
1570 #[cfg(any(test, feature = "_bench_unstable", feature = "_test_utils"))]
1571 pub fn expect_channel_ready_event<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, expected_counterparty_node_id: &PublicKey) {
1572         let events = node.node.get_and_clear_pending_events();
1573         assert_eq!(events.len(), 1);
1574         match events[0] {
1575                 crate::util::events::Event::ChannelReady{ ref counterparty_node_id, .. } => {
1576                         assert_eq!(*expected_counterparty_node_id, *counterparty_node_id);
1577                 },
1578                 _ => panic!("Unexpected event"),
1579         }
1580 }
1581
1582
1583 pub struct PaymentFailedConditions<'a> {
1584         pub(crate) expected_htlc_error_data: Option<(u16, &'a [u8])>,
1585         pub(crate) expected_blamed_scid: Option<u64>,
1586         pub(crate) expected_blamed_chan_closed: Option<bool>,
1587         pub(crate) expected_mpp_parts_remain: bool,
1588 }
1589
1590 impl<'a> PaymentFailedConditions<'a> {
1591         pub fn new() -> Self {
1592                 Self {
1593                         expected_htlc_error_data: None,
1594                         expected_blamed_scid: None,
1595                         expected_blamed_chan_closed: None,
1596                         expected_mpp_parts_remain: false,
1597                 }
1598         }
1599         pub fn mpp_parts_remain(mut self) -> Self {
1600                 self.expected_mpp_parts_remain = true;
1601                 self
1602         }
1603         pub fn blamed_scid(mut self, scid: u64) -> Self {
1604                 self.expected_blamed_scid = Some(scid);
1605                 self
1606         }
1607         pub fn blamed_chan_closed(mut self, closed: bool) -> Self {
1608                 self.expected_blamed_chan_closed = Some(closed);
1609                 self
1610         }
1611         pub fn expected_htlc_error_data(mut self, code: u16, data: &'a [u8]) -> Self {
1612                 self.expected_htlc_error_data = Some((code, data));
1613                 self
1614         }
1615 }
1616
1617 #[cfg(test)]
1618 macro_rules! expect_payment_failed_with_update {
1619         ($node: expr, $expected_payment_hash: expr, $payment_failed_permanently: expr, $scid: expr, $chan_closed: expr) => {
1620                 $crate::ln::functional_test_utils::expect_payment_failed_conditions(
1621                         &$node, $expected_payment_hash, $payment_failed_permanently,
1622                         $crate::ln::functional_test_utils::PaymentFailedConditions::new()
1623                                 .blamed_scid($scid).blamed_chan_closed($chan_closed));
1624         }
1625 }
1626
1627 #[cfg(test)]
1628 macro_rules! expect_payment_failed {
1629         ($node: expr, $expected_payment_hash: expr, $payment_failed_permanently: expr $(, $expected_error_code: expr, $expected_error_data: expr)*) => {
1630                 #[allow(unused_mut)]
1631                 let mut conditions = $crate::ln::functional_test_utils::PaymentFailedConditions::new();
1632                 $(
1633                         conditions = conditions.expected_htlc_error_data($expected_error_code, &$expected_error_data);
1634                 )*
1635                 $crate::ln::functional_test_utils::expect_payment_failed_conditions(&$node, $expected_payment_hash, $payment_failed_permanently, conditions);
1636         };
1637 }
1638
1639 pub fn expect_payment_failed_conditions_event<'a, 'b, 'c, 'd, 'e>(
1640         node: &'a Node<'b, 'c, 'd>, payment_failed_event: Event, expected_payment_hash: PaymentHash,
1641         expected_payment_failed_permanently: bool, conditions: PaymentFailedConditions<'e>
1642 ) {
1643         let expected_payment_id = match payment_failed_event {
1644                 Event::PaymentPathFailed { payment_hash, payment_failed_permanently, path, retry, payment_id, network_update, short_channel_id,
1645                         #[cfg(test)]
1646                         error_code,
1647                         #[cfg(test)]
1648                         error_data, .. } => {
1649                         assert_eq!(payment_hash, expected_payment_hash, "unexpected payment_hash");
1650                         assert_eq!(payment_failed_permanently, expected_payment_failed_permanently, "unexpected payment_failed_permanently value");
1651                         assert!(retry.is_some(), "expected retry.is_some()");
1652                         assert_eq!(retry.as_ref().unwrap().final_value_msat, path.last().unwrap().fee_msat, "Retry amount should match last hop in path");
1653                         assert_eq!(retry.as_ref().unwrap().payment_params.payee_pubkey, path.last().unwrap().pubkey, "Retry payee node_id should match last hop in path");
1654                         if let Some(scid) = short_channel_id {
1655                                 assert!(retry.as_ref().unwrap().payment_params.previously_failed_channels.contains(&scid));
1656                         }
1657
1658                         #[cfg(test)]
1659                         {
1660                                 assert!(error_code.is_some(), "expected error_code.is_some() = true");
1661                                 assert!(error_data.is_some(), "expected error_data.is_some() = true");
1662                                 if let Some((code, data)) = conditions.expected_htlc_error_data {
1663                                         assert_eq!(error_code.unwrap(), code, "unexpected error code");
1664                                         assert_eq!(&error_data.as_ref().unwrap()[..], data, "unexpected error data");
1665                                 }
1666                         }
1667
1668                         if let Some(chan_closed) = conditions.expected_blamed_chan_closed {
1669                                 match network_update {
1670                                         Some(NetworkUpdate::ChannelUpdateMessage { ref msg }) if !chan_closed => {
1671                                                 if let Some(scid) = conditions.expected_blamed_scid {
1672                                                         assert_eq!(msg.contents.short_channel_id, scid);
1673                                                 }
1674                                                 const CHAN_DISABLED_FLAG: u8 = 2;
1675                                                 assert_eq!(msg.contents.flags & CHAN_DISABLED_FLAG, 0);
1676                                         },
1677                                         Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }) if chan_closed => {
1678                                                 if let Some(scid) = conditions.expected_blamed_scid {
1679                                                         assert_eq!(short_channel_id, scid);
1680                                                 }
1681                                                 assert!(is_permanent);
1682                                         },
1683                                         Some(_) => panic!("Unexpected update type"),
1684                                         None => panic!("Expected update"),
1685                                 }
1686                         }
1687
1688                         payment_id.unwrap()
1689                 },
1690                 _ => panic!("Unexpected event"),
1691         };
1692         if !conditions.expected_mpp_parts_remain {
1693                 node.node.abandon_payment(expected_payment_id);
1694                 let events = node.node.get_and_clear_pending_events();
1695                 assert_eq!(events.len(), 1);
1696                 match events[0] {
1697                         Event::PaymentFailed { ref payment_hash, ref payment_id } => {
1698                                 assert_eq!(*payment_hash, expected_payment_hash, "unexpected second payment_hash");
1699                                 assert_eq!(*payment_id, expected_payment_id);
1700                         }
1701                         _ => panic!("Unexpected second event"),
1702                 }
1703         }
1704 }
1705
1706 pub fn expect_payment_failed_conditions<'a, 'b, 'c, 'd, 'e>(
1707         node: &'a Node<'b, 'c, 'd>, expected_payment_hash: PaymentHash, expected_payment_failed_permanently: bool,
1708         conditions: PaymentFailedConditions<'e>
1709 ) {
1710         let mut events = node.node.get_and_clear_pending_events();
1711         assert_eq!(events.len(), 1);
1712         expect_payment_failed_conditions_event(node, events.pop().unwrap(), expected_payment_hash, expected_payment_failed_permanently, conditions);
1713 }
1714
1715 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 {
1716         let payment_id = PaymentId(origin_node.keys_manager.backing.get_secure_random_bytes());
1717         origin_node.node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), payment_id).unwrap();
1718         check_added_monitors!(origin_node, expected_paths.len());
1719         pass_along_route(origin_node, expected_paths, recv_value, our_payment_hash, our_payment_secret);
1720         payment_id
1721 }
1722
1723 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>) {
1724         let mut payment_event = SendEvent::from_event(ev);
1725         let mut prev_node = origin_node;
1726
1727         for (idx, &node) in expected_path.iter().enumerate() {
1728                 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
1729
1730                 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
1731                 check_added_monitors!(node, 0);
1732                 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
1733
1734                 expect_pending_htlcs_forwardable!(node);
1735
1736                 if idx == expected_path.len() - 1 && clear_recipient_events {
1737                         let events_2 = node.node.get_and_clear_pending_events();
1738                         if payment_received_expected {
1739                                 assert_eq!(events_2.len(), 1);
1740                                 match events_2[0] {
1741                                         Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
1742                                                 assert_eq!(our_payment_hash, *payment_hash);
1743                                                 match &purpose {
1744                                                         PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1745                                                                 assert_eq!(expected_preimage, *payment_preimage);
1746                                                                 assert_eq!(our_payment_secret.unwrap(), *payment_secret);
1747                                                         },
1748                                                         PaymentPurpose::SpontaneousPayment(payment_preimage) => {
1749                                                                 assert_eq!(expected_preimage.unwrap(), *payment_preimage);
1750                                                                 assert!(our_payment_secret.is_none());
1751                                                         },
1752                                                 }
1753                                                 assert_eq!(amount_msat, recv_value);
1754                                         },
1755                                         _ => panic!("Unexpected event"),
1756                                 }
1757                         } else {
1758                                 assert!(events_2.is_empty());
1759                         }
1760                 } else if idx != expected_path.len() - 1 {
1761                         let mut events_2 = node.node.get_and_clear_pending_msg_events();
1762                         assert_eq!(events_2.len(), 1);
1763                         check_added_monitors!(node, 1);
1764                         payment_event = SendEvent::from_event(events_2.remove(0));
1765                         assert_eq!(payment_event.msgs.len(), 1);
1766                 }
1767
1768                 prev_node = node;
1769         }
1770 }
1771
1772 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>) {
1773         do_pass_along_path(origin_node, expected_path, recv_value, our_payment_hash, our_payment_secret, ev, payment_received_expected, true, expected_preimage);
1774 }
1775
1776 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) {
1777         let mut events = origin_node.node.get_and_clear_pending_msg_events();
1778         assert_eq!(events.len(), expected_route.len());
1779         for (path_idx, (ev, expected_path)) in events.drain(..).zip(expected_route.iter()).enumerate() {
1780                 // Once we've gotten through all the HTLCs, the last one should result in a
1781                 // PaymentReceived (but each previous one should not!), .
1782                 let expect_payment = path_idx == expected_route.len() - 1;
1783                 pass_along_path(origin_node, expected_path, recv_value, our_payment_hash.clone(), Some(our_payment_secret), ev, expect_payment, None);
1784         }
1785 }
1786
1787 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) {
1788         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(expected_route.last().unwrap());
1789         let payment_id = send_along_route_with_secret(origin_node, route, &[expected_route], recv_value, our_payment_hash, our_payment_secret);
1790         (our_payment_preimage, our_payment_hash, our_payment_secret, payment_id)
1791 }
1792
1793 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 {
1794         for path in expected_paths.iter() {
1795                 assert_eq!(path.last().unwrap().node.get_our_node_id(), expected_paths[0].last().unwrap().node.get_our_node_id());
1796         }
1797         expected_paths[0].last().unwrap().node.claim_funds(our_payment_preimage);
1798
1799         let claim_event = expected_paths[0].last().unwrap().node.get_and_clear_pending_events();
1800         assert_eq!(claim_event.len(), 1);
1801         match claim_event[0] {
1802                 Event::PaymentClaimed { purpose: PaymentPurpose::SpontaneousPayment(preimage), .. }|
1803                 Event::PaymentClaimed { purpose: PaymentPurpose::InvoicePayment { payment_preimage: Some(preimage), ..}, .. } =>
1804                         assert_eq!(preimage, our_payment_preimage),
1805                 Event::PaymentClaimed { purpose: PaymentPurpose::InvoicePayment { .. }, payment_hash, .. } =>
1806                         assert_eq!(&payment_hash.0, &Sha256::hash(&our_payment_preimage.0)[..]),
1807                 _ => panic!(),
1808         }
1809
1810         check_added_monitors!(expected_paths[0].last().unwrap(), expected_paths.len());
1811
1812         let mut expected_total_fee_msat = 0;
1813
1814         macro_rules! msgs_from_ev {
1815                 ($ev: expr) => {
1816                         match $ev {
1817                                 &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 } } => {
1818                                         assert!(update_add_htlcs.is_empty());
1819                                         assert_eq!(update_fulfill_htlcs.len(), 1);
1820                                         assert!(update_fail_htlcs.is_empty());
1821                                         assert!(update_fail_malformed_htlcs.is_empty());
1822                                         assert!(update_fee.is_none());
1823                                         ((update_fulfill_htlcs[0].clone(), commitment_signed.clone()), node_id.clone())
1824                                 },
1825                                 _ => panic!("Unexpected event"),
1826                         }
1827                 }
1828         }
1829         let mut per_path_msgs: Vec<((msgs::UpdateFulfillHTLC, msgs::CommitmentSigned), PublicKey)> = Vec::with_capacity(expected_paths.len());
1830         let events = expected_paths[0].last().unwrap().node.get_and_clear_pending_msg_events();
1831         assert_eq!(events.len(), expected_paths.len());
1832         for ev in events.iter() {
1833                 per_path_msgs.push(msgs_from_ev!(ev));
1834         }
1835
1836         for (expected_route, (path_msgs, next_hop)) in expected_paths.iter().zip(per_path_msgs.drain(..)) {
1837                 let mut next_msgs = Some(path_msgs);
1838                 let mut expected_next_node = next_hop;
1839
1840                 macro_rules! last_update_fulfill_dance {
1841                         ($node: expr, $prev_node: expr) => {
1842                                 {
1843                                         $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0);
1844                                         check_added_monitors!($node, 0);
1845                                         assert!($node.node.get_and_clear_pending_msg_events().is_empty());
1846                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
1847                                 }
1848                         }
1849                 }
1850                 macro_rules! mid_update_fulfill_dance {
1851                         ($node: expr, $prev_node: expr, $next_node: expr, $new_msgs: expr) => {
1852                                 {
1853                                         $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0);
1854                                         let fee = {
1855                                                 let channel_state = $node.node.channel_state.lock().unwrap();
1856                                                 let channel = channel_state
1857                                                         .by_id.get(&next_msgs.as_ref().unwrap().0.channel_id).unwrap();
1858                                                 if let Some(prev_config) = channel.prev_config() {
1859                                                         prev_config.forwarding_fee_base_msat
1860                                                 } else {
1861                                                         channel.config().forwarding_fee_base_msat
1862                                                 }
1863                                         };
1864                                         expect_payment_forwarded!($node, $next_node, $prev_node, Some(fee as u64), false, false);
1865                                         expected_total_fee_msat += fee as u64;
1866                                         check_added_monitors!($node, 1);
1867                                         let new_next_msgs = if $new_msgs {
1868                                                 let events = $node.node.get_and_clear_pending_msg_events();
1869                                                 assert_eq!(events.len(), 1);
1870                                                 let (res, nexthop) = msgs_from_ev!(&events[0]);
1871                                                 expected_next_node = nexthop;
1872                                                 Some(res)
1873                                         } else {
1874                                                 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
1875                                                 None
1876                                         };
1877                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
1878                                         next_msgs = new_next_msgs;
1879                                 }
1880                         }
1881                 }
1882
1883                 let mut prev_node = expected_route.last().unwrap();
1884                 for (idx, node) in expected_route.iter().rev().enumerate().skip(1) {
1885                         assert_eq!(expected_next_node, node.node.get_our_node_id());
1886                         let update_next_msgs = !skip_last || idx != expected_route.len() - 1;
1887                         if next_msgs.is_some() {
1888                                 // Since we are traversing in reverse, next_node is actually the previous node
1889                                 let next_node: &Node;
1890                                 if idx == expected_route.len() - 1 {
1891                                         next_node = origin_node;
1892                                 } else {
1893                                         next_node = expected_route[expected_route.len() - 1 - idx - 1];
1894                                 }
1895                                 mid_update_fulfill_dance!(node, prev_node, next_node, update_next_msgs);
1896                         } else {
1897                                 assert!(!update_next_msgs);
1898                                 assert!(node.node.get_and_clear_pending_msg_events().is_empty());
1899                         }
1900                         if !skip_last && idx == expected_route.len() - 1 {
1901                                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
1902                         }
1903
1904                         prev_node = node;
1905                 }
1906
1907                 if !skip_last {
1908                         last_update_fulfill_dance!(origin_node, expected_route.first().unwrap());
1909                 }
1910         }
1911
1912         // Ensure that claim_funds is idempotent.
1913         expected_paths[0].last().unwrap().node.claim_funds(our_payment_preimage);
1914         assert!(expected_paths[0].last().unwrap().node.get_and_clear_pending_msg_events().is_empty());
1915         check_added_monitors!(expected_paths[0].last().unwrap(), 0);
1916
1917         expected_total_fee_msat
1918 }
1919 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) {
1920         let expected_total_fee_msat = do_claim_payment_along_route(origin_node, expected_paths, skip_last, our_payment_preimage);
1921         if !skip_last {
1922                 expect_payment_sent!(origin_node, our_payment_preimage, Some(expected_total_fee_msat));
1923         }
1924 }
1925
1926 pub fn claim_payment<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_route: &[&Node<'a, 'b, 'c>], our_payment_preimage: PaymentPreimage) {
1927         claim_payment_along_route(origin_node, &[expected_route], false, our_payment_preimage);
1928 }
1929
1930 pub const TEST_FINAL_CLTV: u32 = 70;
1931
1932 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) {
1933         let payment_params = PaymentParameters::from_node_id(expected_route.last().unwrap().node.get_our_node_id())
1934                 .with_features(channelmanager::provided_invoice_features());
1935         let route = get_route!(origin_node, payment_params, recv_value, TEST_FINAL_CLTV).unwrap();
1936         assert_eq!(route.paths.len(), 1);
1937         assert_eq!(route.paths[0].len(), expected_route.len());
1938         for (node, hop) in expected_route.iter().zip(route.paths[0].iter()) {
1939                 assert_eq!(hop.pubkey, node.node.get_our_node_id());
1940         }
1941
1942         let res = send_along_route(origin_node, route, expected_route, recv_value);
1943         (res.0, res.1, res.2)
1944 }
1945
1946 pub fn route_over_limit<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_route: &[&Node<'a, 'b, 'c>], recv_value: u64)  {
1947         let payment_params = PaymentParameters::from_node_id(expected_route.last().unwrap().node.get_our_node_id())
1948                 .with_features(channelmanager::provided_invoice_features());
1949         let network_graph = origin_node.network_graph.read_only();
1950         let scorer = test_utils::TestScorer::with_penalty(0);
1951         let seed = [0u8; 32];
1952         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
1953         let random_seed_bytes = keys_manager.get_secure_random_bytes();
1954         let route = get_route(
1955                 &origin_node.node.get_our_node_id(), &payment_params, &network_graph,
1956                 None, recv_value, TEST_FINAL_CLTV, origin_node.logger, &scorer, &random_seed_bytes).unwrap();
1957         assert_eq!(route.paths.len(), 1);
1958         assert_eq!(route.paths[0].len(), expected_route.len());
1959         for (node, hop) in expected_route.iter().zip(route.paths[0].iter()) {
1960                 assert_eq!(hop.pubkey, node.node.get_our_node_id());
1961         }
1962
1963         let (_, our_payment_hash, our_payment_preimage) = get_payment_preimage_hash!(expected_route.last().unwrap());
1964         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 },
1965                 assert!(err.contains("Cannot send value that would put us over the max HTLC value in flight our peer will accept")));
1966 }
1967
1968 pub fn send_payment<'a, 'b, 'c>(origin: &Node<'a, 'b, 'c>, expected_route: &[&Node<'a, 'b, 'c>], recv_value: u64)  {
1969         let our_payment_preimage = route_payment(&origin, expected_route, recv_value).0;
1970         claim_payment(&origin, expected_route, our_payment_preimage);
1971 }
1972
1973 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) {
1974         for path in expected_paths.iter() {
1975                 assert_eq!(path.last().unwrap().node.get_our_node_id(), expected_paths[0].last().unwrap().node.get_our_node_id());
1976         }
1977         expected_paths[0].last().unwrap().node.fail_htlc_backwards(&our_payment_hash);
1978         let expected_destinations: Vec<HTLCDestination> = repeat(HTLCDestination::FailedPayment { payment_hash: our_payment_hash }).take(expected_paths.len()).collect();
1979         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(expected_paths[0].last().unwrap(), expected_destinations);
1980
1981         pass_failed_payment_back(origin_node, expected_paths, skip_last, our_payment_hash);
1982 }
1983
1984 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) {
1985         let expected_payment_id = pass_failed_payment_back_no_abandon(origin_node, expected_paths_slice, skip_last, our_payment_hash);
1986         if !skip_last {
1987                 origin_node.node.abandon_payment(expected_payment_id.unwrap());
1988                 let events = origin_node.node.get_and_clear_pending_events();
1989                 assert_eq!(events.len(), 1);
1990                 match events[0] {
1991                         Event::PaymentFailed { ref payment_hash, ref payment_id } => {
1992                                 assert_eq!(*payment_hash, our_payment_hash, "unexpected second payment_hash");
1993                                 assert_eq!(*payment_id, expected_payment_id.unwrap());
1994                         }
1995                         _ => panic!("Unexpected second event"),
1996                 }
1997         }
1998 }
1999
2000 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> {
2001         let mut expected_paths: Vec<_> = expected_paths_slice.iter().collect();
2002         check_added_monitors!(expected_paths[0].last().unwrap(), expected_paths.len());
2003
2004         let mut per_path_msgs: Vec<((msgs::UpdateFailHTLC, msgs::CommitmentSigned), PublicKey)> = Vec::with_capacity(expected_paths.len());
2005         let events = expected_paths[0].last().unwrap().node.get_and_clear_pending_msg_events();
2006         assert_eq!(events.len(), expected_paths.len());
2007         for ev in events.iter() {
2008                 let (update_fail, commitment_signed, node_id) = match ev {
2009                         &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 } } => {
2010                                 assert!(update_add_htlcs.is_empty());
2011                                 assert!(update_fulfill_htlcs.is_empty());
2012                                 assert_eq!(update_fail_htlcs.len(), 1);
2013                                 assert!(update_fail_malformed_htlcs.is_empty());
2014                                 assert!(update_fee.is_none());
2015                                 (update_fail_htlcs[0].clone(), commitment_signed.clone(), node_id.clone())
2016                         },
2017                         _ => panic!("Unexpected event"),
2018                 };
2019                 per_path_msgs.push(((update_fail, commitment_signed), node_id));
2020         }
2021         per_path_msgs.sort_unstable_by(|(_, node_id_a), (_, node_id_b)| node_id_a.cmp(node_id_b));
2022         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()));
2023
2024         let mut expected_payment_id = None;
2025
2026         for (i, (expected_route, (path_msgs, next_hop))) in expected_paths.iter().zip(per_path_msgs.drain(..)).enumerate() {
2027                 let mut next_msgs = Some(path_msgs);
2028                 let mut expected_next_node = next_hop;
2029                 let mut prev_node = expected_route.last().unwrap();
2030
2031                 for (idx, node) in expected_route.iter().rev().enumerate().skip(1) {
2032                         assert_eq!(expected_next_node, node.node.get_our_node_id());
2033                         let update_next_node = !skip_last || idx != expected_route.len() - 1;
2034                         if next_msgs.is_some() {
2035                                 node.node.handle_update_fail_htlc(&prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0);
2036                                 commitment_signed_dance!(node, prev_node, next_msgs.as_ref().unwrap().1, update_next_node);
2037                                 if !update_next_node {
2038                                         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 }]);
2039                                 }
2040                         }
2041                         let events = node.node.get_and_clear_pending_msg_events();
2042                         if update_next_node {
2043                                 assert_eq!(events.len(), 1);
2044                                 match events[0] {
2045                                         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 } } => {
2046                                                 assert!(update_add_htlcs.is_empty());
2047                                                 assert!(update_fulfill_htlcs.is_empty());
2048                                                 assert_eq!(update_fail_htlcs.len(), 1);
2049                                                 assert!(update_fail_malformed_htlcs.is_empty());
2050                                                 assert!(update_fee.is_none());
2051                                                 expected_next_node = node_id.clone();
2052                                                 next_msgs = Some((update_fail_htlcs[0].clone(), commitment_signed.clone()));
2053                                         },
2054                                         _ => panic!("Unexpected event"),
2055                                 }
2056                         } else {
2057                                 assert!(events.is_empty());
2058                         }
2059                         if !skip_last && idx == expected_route.len() - 1 {
2060                                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
2061                         }
2062
2063                         prev_node = node;
2064                 }
2065
2066                 if !skip_last {
2067                         let prev_node = expected_route.first().unwrap();
2068                         origin_node.node.handle_update_fail_htlc(&prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0);
2069                         check_added_monitors!(origin_node, 0);
2070                         assert!(origin_node.node.get_and_clear_pending_msg_events().is_empty());
2071                         commitment_signed_dance!(origin_node, prev_node, next_msgs.as_ref().unwrap().1, false);
2072                         let events = origin_node.node.get_and_clear_pending_events();
2073                         assert_eq!(events.len(), 1);
2074                         expected_payment_id = Some(match events[0] {
2075                                 Event::PaymentPathFailed { payment_hash, payment_failed_permanently, all_paths_failed, ref path, ref payment_id, .. } => {
2076                                         assert_eq!(payment_hash, our_payment_hash);
2077                                         assert!(payment_failed_permanently);
2078                                         assert_eq!(all_paths_failed, i == expected_paths.len() - 1);
2079                                         for (idx, hop) in expected_route.iter().enumerate() {
2080                                                 assert_eq!(hop.node.get_our_node_id(), path[idx].pubkey);
2081                                         }
2082                                         payment_id.unwrap()
2083                                 },
2084                                 _ => panic!("Unexpected event"),
2085                         });
2086                 }
2087         }
2088
2089         // Ensure that fail_htlc_backwards is idempotent.
2090         expected_paths[0].last().unwrap().node.fail_htlc_backwards(&our_payment_hash);
2091         assert!(expected_paths[0].last().unwrap().node.get_and_clear_pending_events().is_empty());
2092         assert!(expected_paths[0].last().unwrap().node.get_and_clear_pending_msg_events().is_empty());
2093         check_added_monitors!(expected_paths[0].last().unwrap(), 0);
2094
2095         expected_payment_id
2096 }
2097
2098 pub fn fail_payment<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_path: &[&Node<'a, 'b, 'c>], our_payment_hash: PaymentHash)  {
2099         fail_payment_along_route(origin_node, &[&expected_path[..]], false, our_payment_hash);
2100 }
2101
2102 pub fn create_chanmon_cfgs(node_count: usize) -> Vec<TestChanMonCfg> {
2103         let mut chan_mon_cfgs = Vec::new();
2104         for i in 0..node_count {
2105                 let tx_broadcaster = test_utils::TestBroadcaster {
2106                         txn_broadcasted: Mutex::new(Vec::new()),
2107                         blocks: Arc::new(Mutex::new(vec![(genesis_block(Network::Testnet), 0)])),
2108                 };
2109                 let fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
2110                 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
2111                 let logger = test_utils::TestLogger::with_id(format!("node {}", i));
2112                 let persister = test_utils::TestPersister::new();
2113                 let seed = [i as u8; 32];
2114                 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
2115
2116                 chan_mon_cfgs.push(TestChanMonCfg{ tx_broadcaster, fee_estimator, chain_source, logger, persister, keys_manager });
2117         }
2118
2119         chan_mon_cfgs
2120 }
2121
2122 pub fn create_node_cfgs<'a>(node_count: usize, chanmon_cfgs: &'a Vec<TestChanMonCfg>) -> Vec<NodeCfg<'a>> {
2123         let mut nodes = Vec::new();
2124
2125         for i in 0..node_count {
2126                 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);
2127                 let seed = [i as u8; 32];
2128                 nodes.push(NodeCfg {
2129                         chain_source: &chanmon_cfgs[i].chain_source,
2130                         logger: &chanmon_cfgs[i].logger,
2131                         tx_broadcaster: &chanmon_cfgs[i].tx_broadcaster,
2132                         fee_estimator: &chanmon_cfgs[i].fee_estimator,
2133                         chain_monitor,
2134                         keys_manager: &chanmon_cfgs[i].keys_manager,
2135                         node_seed: seed,
2136                         features: channelmanager::provided_init_features(),
2137                         network_graph: NetworkGraph::new(chanmon_cfgs[i].chain_source.genesis_hash, &chanmon_cfgs[i].logger),
2138                 });
2139         }
2140
2141         nodes
2142 }
2143
2144 pub fn test_default_channel_config() -> UserConfig {
2145         let mut default_config = UserConfig::default();
2146         // Set cltv_expiry_delta slightly lower to keep the final CLTV values inside one byte in our
2147         // tests so that our script-length checks don't fail (see ACCEPTED_HTLC_SCRIPT_WEIGHT).
2148         default_config.channel_config.cltv_expiry_delta = MIN_CLTV_EXPIRY_DELTA;
2149         default_config.channel_handshake_config.announced_channel = true;
2150         default_config.channel_handshake_limits.force_announced_channel_preference = false;
2151         // When most of our tests were written, the default HTLC minimum was fixed at 1000.
2152         // It now defaults to 1, so we simply set it to the expected value here.
2153         default_config.channel_handshake_config.our_htlc_minimum_msat = 1000;
2154         // When most of our tests were written, we didn't have the notion of a `max_dust_htlc_exposure_msat`,
2155         // It now defaults to 5_000_000 msat; to avoid interfering with tests we bump it to 50_000_000 msat.
2156         default_config.channel_config.max_dust_htlc_exposure_msat = 50_000_000;
2157         default_config
2158 }
2159
2160 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>> {
2161         let mut chanmgrs = Vec::new();
2162         for i in 0..node_count {
2163                 let network = Network::Testnet;
2164                 let params = ChainParameters {
2165                         network,
2166                         best_block: BestBlock::from_genesis(network),
2167                 };
2168                 let node = ChannelManager::new(cfgs[i].fee_estimator, &cfgs[i].chain_monitor, cfgs[i].tx_broadcaster, cfgs[i].logger, cfgs[i].keys_manager,
2169                         if node_config[i].is_some() { node_config[i].clone().unwrap() } else { test_default_channel_config() }, params);
2170                 chanmgrs.push(node);
2171         }
2172
2173         chanmgrs
2174 }
2175
2176 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>> {
2177         let mut nodes = Vec::new();
2178         let chan_count = Rc::new(RefCell::new(0));
2179         let payment_count = Rc::new(RefCell::new(0));
2180         let connect_style = Rc::new(RefCell::new(ConnectStyle::random_style()));
2181
2182         for i in 0..node_count {
2183                 let gossip_sync = P2PGossipSync::new(&cfgs[i].network_graph, None, cfgs[i].logger);
2184                 nodes.push(Node{
2185                         chain_source: cfgs[i].chain_source, tx_broadcaster: cfgs[i].tx_broadcaster,
2186                         fee_estimator: cfgs[i].fee_estimator,
2187                         chain_monitor: &cfgs[i].chain_monitor, keys_manager: &cfgs[i].keys_manager,
2188                         node: &chan_mgrs[i], network_graph: &cfgs[i].network_graph, gossip_sync,
2189                         node_seed: cfgs[i].node_seed, network_chan_count: chan_count.clone(),
2190                         network_payment_count: payment_count.clone(), logger: cfgs[i].logger,
2191                         blocks: Arc::clone(&cfgs[i].tx_broadcaster.blocks),
2192                         connect_style: Rc::clone(&connect_style),
2193                 })
2194         }
2195
2196         for i in 0..node_count {
2197                 for j in (i+1)..node_count {
2198                         nodes[i].node.peer_connected(&nodes[j].node.get_our_node_id(), &msgs::Init { features: cfgs[j].features.clone(), remote_network_address: None }).unwrap();
2199                         nodes[j].node.peer_connected(&nodes[i].node.get_our_node_id(), &msgs::Init { features: cfgs[i].features.clone(), remote_network_address: None }).unwrap();
2200                 }
2201         }
2202
2203         nodes
2204 }
2205
2206 // Note that the following only works for CLTV values up to 128
2207 pub const ACCEPTED_HTLC_SCRIPT_WEIGHT: usize = 137; //Here we have a diff due to HTLC CLTV expiry being < 2^15 in test
2208
2209 #[derive(PartialEq)]
2210 pub enum HTLCType { NONE, TIMEOUT, SUCCESS }
2211 /// Tests that the given node has broadcast transactions for the given Channel
2212 ///
2213 /// First checks that the latest holder commitment tx has been broadcast, unless an explicit
2214 /// commitment_tx is provided, which may be used to test that a remote commitment tx was
2215 /// broadcast and the revoked outputs were claimed.
2216 ///
2217 /// Next tests that there is (or is not) a transaction that spends the commitment transaction
2218 /// that appears to be the type of HTLC transaction specified in has_htlc_tx.
2219 ///
2220 /// All broadcast transactions must be accounted for in one of the above three types of we'll
2221 /// also fail.
2222 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>  {
2223         let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2224         assert!(node_txn.len() >= if commitment_tx.is_some() { 0 } else { 1 } + if has_htlc_tx == HTLCType::NONE { 0 } else { 1 });
2225
2226         let mut res = Vec::with_capacity(2);
2227         node_txn.retain(|tx| {
2228                 if tx.input.len() == 1 && tx.input[0].previous_output.txid == chan.3.txid() {
2229                         check_spends!(tx, chan.3);
2230                         if commitment_tx.is_none() {
2231                                 res.push(tx.clone());
2232                         }
2233                         false
2234                 } else { true }
2235         });
2236         if let Some(explicit_tx) = commitment_tx {
2237                 res.push(explicit_tx.clone());
2238         }
2239
2240         assert_eq!(res.len(), 1);
2241
2242         if has_htlc_tx != HTLCType::NONE {
2243                 node_txn.retain(|tx| {
2244                         if tx.input.len() == 1 && tx.input[0].previous_output.txid == res[0].txid() {
2245                                 check_spends!(tx, res[0]);
2246                                 if has_htlc_tx == HTLCType::TIMEOUT {
2247                                         assert!(tx.lock_time.0 != 0);
2248                                 } else {
2249                                         assert!(tx.lock_time.0 == 0);
2250                                 }
2251                                 res.push(tx.clone());
2252                                 false
2253                         } else { true }
2254                 });
2255                 assert!(res.len() == 2 || res.len() == 3);
2256                 if res.len() == 3 {
2257                         assert_eq!(res[1], res[2]);
2258                 }
2259         }
2260
2261         assert!(node_txn.is_empty());
2262         res
2263 }
2264
2265 /// Tests that the given node has broadcast a claim transaction against the provided revoked
2266 /// HTLC transaction.
2267 pub fn test_revoked_htlc_claim_txn_broadcast<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, revoked_tx: Transaction, commitment_revoked_tx: Transaction)  {
2268         let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2269         // We may issue multiple claiming transaction on revoked outputs due to block rescan
2270         // for revoked htlc outputs
2271         if node_txn.len() != 1 && node_txn.len() != 2 && node_txn.len() != 3 { assert!(false); }
2272         node_txn.retain(|tx| {
2273                 if tx.input.len() == 1 && tx.input[0].previous_output.txid == revoked_tx.txid() {
2274                         check_spends!(tx, revoked_tx);
2275                         false
2276                 } else { true }
2277         });
2278         node_txn.retain(|tx| {
2279                 check_spends!(tx, commitment_revoked_tx);
2280                 false
2281         });
2282         assert!(node_txn.is_empty());
2283 }
2284
2285 pub fn check_preimage_claim<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, prev_txn: &Vec<Transaction>) -> Vec<Transaction>  {
2286         let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2287
2288         assert!(node_txn.len() >= 1);
2289         assert_eq!(node_txn[0].input.len(), 1);
2290         let mut found_prev = false;
2291
2292         for tx in prev_txn {
2293                 if node_txn[0].input[0].previous_output.txid == tx.txid() {
2294                         check_spends!(node_txn[0], tx);
2295                         let mut iter = node_txn[0].input[0].witness.iter();
2296                         iter.next().expect("expected 3 witness items");
2297                         iter.next().expect("expected 3 witness items");
2298                         assert!(iter.next().expect("expected 3 witness items").len() > 106); // must spend an htlc output
2299                         assert_eq!(tx.input.len(), 1); // must spend a commitment tx
2300
2301                         found_prev = true;
2302                         break;
2303                 }
2304         }
2305         assert!(found_prev);
2306
2307         let mut res = Vec::new();
2308         mem::swap(&mut *node_txn, &mut res);
2309         res
2310 }
2311
2312 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)  {
2313         let events_1 = nodes[a].node.get_and_clear_pending_msg_events();
2314         assert_eq!(events_1.len(), 2);
2315         let as_update = match events_1[0] {
2316                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2317                         msg.clone()
2318                 },
2319                 _ => panic!("Unexpected event"),
2320         };
2321         match events_1[1] {
2322                 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
2323                         assert_eq!(node_id, nodes[b].node.get_our_node_id());
2324                         assert_eq!(msg.data, expected_error);
2325                         if needs_err_handle {
2326                                 nodes[b].node.handle_error(&nodes[a].node.get_our_node_id(), msg);
2327                         }
2328                 },
2329                 _ => panic!("Unexpected event"),
2330         }
2331
2332         let events_2 = nodes[b].node.get_and_clear_pending_msg_events();
2333         assert_eq!(events_2.len(), if needs_err_handle { 1 } else { 2 });
2334         let bs_update = match events_2[0] {
2335                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2336                         msg.clone()
2337                 },
2338                 _ => panic!("Unexpected event"),
2339         };
2340         if !needs_err_handle {
2341                 match events_2[1] {
2342                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
2343                                 assert_eq!(node_id, nodes[a].node.get_our_node_id());
2344                                 assert_eq!(msg.data, expected_error);
2345                         },
2346                         _ => panic!("Unexpected event"),
2347                 }
2348         }
2349
2350         for node in nodes {
2351                 node.gossip_sync.handle_channel_update(&as_update).unwrap();
2352                 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
2353         }
2354 }
2355
2356 pub fn get_announce_close_broadcast_events<'a, 'b, 'c>(nodes: &Vec<Node<'a, 'b, 'c>>, a: usize, b: usize)  {
2357         handle_announce_close_broadcast_events(nodes, a, b, false, "Channel closed because commitment or closing transaction was confirmed on chain.");
2358 }
2359
2360 #[cfg(test)]
2361 macro_rules! get_channel_value_stat {
2362         ($node: expr, $channel_id: expr) => {{
2363                 let chan_lock = $node.node.channel_state.lock().unwrap();
2364                 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
2365                 chan.get_value_stat()
2366         }}
2367 }
2368
2369 macro_rules! get_chan_reestablish_msgs {
2370         ($src_node: expr, $dst_node: expr) => {
2371                 {
2372                         let mut announcements = $crate::prelude::HashSet::new();
2373                         let mut res = Vec::with_capacity(1);
2374                         for msg in $src_node.node.get_and_clear_pending_msg_events() {
2375                                 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
2376                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2377                                         res.push(msg.clone());
2378                                 } else if let MessageSendEvent::SendChannelAnnouncement { ref node_id, ref msg, .. } = msg {
2379                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2380                                         announcements.insert(msg.contents.short_channel_id);
2381                                 } else {
2382                                         panic!("Unexpected event")
2383                                 }
2384                         }
2385                         for chan in $src_node.node.list_channels() {
2386                                 if chan.is_public && chan.counterparty.node_id != $dst_node.node.get_our_node_id() {
2387                                         if let Some(scid) = chan.short_channel_id {
2388                                                 assert!(announcements.remove(&scid));
2389                                         }
2390                                 }
2391                         }
2392                         assert!(announcements.is_empty());
2393                         res
2394                 }
2395         }
2396 }
2397
2398 macro_rules! handle_chan_reestablish_msgs {
2399         ($src_node: expr, $dst_node: expr) => {
2400                 {
2401                         let msg_events = $src_node.node.get_and_clear_pending_msg_events();
2402                         let mut idx = 0;
2403                         let channel_ready = if let Some(&MessageSendEvent::SendChannelReady { ref node_id, ref msg }) = msg_events.get(0) {
2404                                 idx += 1;
2405                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2406                                 Some(msg.clone())
2407                         } else {
2408                                 None
2409                         };
2410
2411                         if let Some(&MessageSendEvent::SendAnnouncementSignatures { ref node_id, msg: _ }) = msg_events.get(idx) {
2412                                 idx += 1;
2413                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2414                         }
2415
2416                         let mut revoke_and_ack = None;
2417                         let mut commitment_update = None;
2418                         let order = if let Some(ev) = msg_events.get(idx) {
2419                                 match ev {
2420                                         &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
2421                                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2422                                                 revoke_and_ack = Some(msg.clone());
2423                                                 idx += 1;
2424                                                 RAACommitmentOrder::RevokeAndACKFirst
2425                                         },
2426                                         &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
2427                                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2428                                                 commitment_update = Some(updates.clone());
2429                                                 idx += 1;
2430                                                 RAACommitmentOrder::CommitmentFirst
2431                                         },
2432                                         _ => RAACommitmentOrder::CommitmentFirst,
2433                                 }
2434                         } else {
2435                                 RAACommitmentOrder::CommitmentFirst
2436                         };
2437
2438                         if let Some(ev) = msg_events.get(idx) {
2439                                 match ev {
2440                                         &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
2441                                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2442                                                 assert!(revoke_and_ack.is_none());
2443                                                 revoke_and_ack = Some(msg.clone());
2444                                                 idx += 1;
2445                                         },
2446                                         &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
2447                                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2448                                                 assert!(commitment_update.is_none());
2449                                                 commitment_update = Some(updates.clone());
2450                                                 idx += 1;
2451                                         },
2452                                         _ => {},
2453                                 }
2454                         }
2455
2456                         if let Some(&MessageSendEvent::SendChannelUpdate { ref node_id, ref msg }) = msg_events.get(idx) {
2457                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2458                                 idx += 1;
2459                                 assert_eq!(msg.contents.flags & 2, 0); // "disabled" flag must not be set as we just reconnected.
2460                         }
2461
2462                         assert_eq!(msg_events.len(), idx);
2463
2464                         (channel_ready, revoke_and_ack, commitment_update, order)
2465                 }
2466         }
2467 }
2468
2469 /// pending_htlc_adds includes both the holding cell and in-flight update_add_htlcs, whereas
2470 /// for claims/fails they are separated out.
2471 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))  {
2472         node_a.node.peer_connected(&node_b.node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
2473         let reestablish_1 = get_chan_reestablish_msgs!(node_a, node_b);
2474         node_b.node.peer_connected(&node_a.node.get_our_node_id(), &msgs::Init { features: channelmanager::provided_init_features(), remote_network_address: None }).unwrap();
2475         let reestablish_2 = get_chan_reestablish_msgs!(node_b, node_a);
2476
2477         if send_channel_ready.0 {
2478                 // If a expects a channel_ready, it better not think it has received a revoke_and_ack
2479                 // from b
2480                 for reestablish in reestablish_1.iter() {
2481                         assert_eq!(reestablish.next_remote_commitment_number, 0);
2482                 }
2483         }
2484         if send_channel_ready.1 {
2485                 // If b expects a channel_ready, it better not think it has received a revoke_and_ack
2486                 // from a
2487                 for reestablish in reestablish_2.iter() {
2488                         assert_eq!(reestablish.next_remote_commitment_number, 0);
2489                 }
2490         }
2491         if send_channel_ready.0 || send_channel_ready.1 {
2492                 // If we expect any channel_ready's, both sides better have set
2493                 // next_holder_commitment_number to 1
2494                 for reestablish in reestablish_1.iter() {
2495                         assert_eq!(reestablish.next_local_commitment_number, 1);
2496                 }
2497                 for reestablish in reestablish_2.iter() {
2498                         assert_eq!(reestablish.next_local_commitment_number, 1);
2499                 }
2500         }
2501
2502         let mut resp_1 = Vec::new();
2503         for msg in reestablish_1 {
2504                 node_b.node.handle_channel_reestablish(&node_a.node.get_our_node_id(), &msg);
2505                 resp_1.push(handle_chan_reestablish_msgs!(node_b, node_a));
2506         }
2507         if pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
2508                 check_added_monitors!(node_b, 1);
2509         } else {
2510                 check_added_monitors!(node_b, 0);
2511         }
2512
2513         let mut resp_2 = Vec::new();
2514         for msg in reestablish_2 {
2515                 node_a.node.handle_channel_reestablish(&node_b.node.get_our_node_id(), &msg);
2516                 resp_2.push(handle_chan_reestablish_msgs!(node_a, node_b));
2517         }
2518         if pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
2519                 check_added_monitors!(node_a, 1);
2520         } else {
2521                 check_added_monitors!(node_a, 0);
2522         }
2523
2524         // We don't yet support both needing updates, as that would require a different commitment dance:
2525         assert!((pending_htlc_adds.0 == 0 && pending_htlc_claims.0 == 0 && pending_htlc_fails.0 == 0 &&
2526                          pending_cell_htlc_claims.0 == 0 && pending_cell_htlc_fails.0 == 0) ||
2527                         (pending_htlc_adds.1 == 0 && pending_htlc_claims.1 == 0 && pending_htlc_fails.1 == 0 &&
2528                          pending_cell_htlc_claims.1 == 0 && pending_cell_htlc_fails.1 == 0));
2529
2530         for chan_msgs in resp_1.drain(..) {
2531                 if send_channel_ready.0 {
2532                         node_a.node.handle_channel_ready(&node_b.node.get_our_node_id(), &chan_msgs.0.unwrap());
2533                         let announcement_event = node_a.node.get_and_clear_pending_msg_events();
2534                         if !announcement_event.is_empty() {
2535                                 assert_eq!(announcement_event.len(), 1);
2536                                 if let MessageSendEvent::SendChannelUpdate { .. } = announcement_event[0] {
2537                                         //TODO: Test announcement_sigs re-sending
2538                                 } else { panic!("Unexpected event! {:?}", announcement_event[0]); }
2539                         }
2540                 } else {
2541                         assert!(chan_msgs.0.is_none());
2542                 }
2543                 if pending_raa.0 {
2544                         assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
2545                         node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap());
2546                         assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
2547                         check_added_monitors!(node_a, 1);
2548                 } else {
2549                         assert!(chan_msgs.1.is_none());
2550                 }
2551                 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 {
2552                         let commitment_update = chan_msgs.2.unwrap();
2553                         if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
2554                                 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.0 as usize);
2555                         } else {
2556                                 assert!(commitment_update.update_add_htlcs.is_empty());
2557                         }
2558                         assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
2559                         assert_eq!(commitment_update.update_fail_htlcs.len(), pending_htlc_fails.0 + pending_cell_htlc_fails.0);
2560                         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
2561                         for update_add in commitment_update.update_add_htlcs {
2562                                 node_a.node.handle_update_add_htlc(&node_b.node.get_our_node_id(), &update_add);
2563                         }
2564                         for update_fulfill in commitment_update.update_fulfill_htlcs {
2565                                 node_a.node.handle_update_fulfill_htlc(&node_b.node.get_our_node_id(), &update_fulfill);
2566                         }
2567                         for update_fail in commitment_update.update_fail_htlcs {
2568                                 node_a.node.handle_update_fail_htlc(&node_b.node.get_our_node_id(), &update_fail);
2569                         }
2570
2571                         if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
2572                                 commitment_signed_dance!(node_a, node_b, commitment_update.commitment_signed, false);
2573                         } else {
2574                                 node_a.node.handle_commitment_signed(&node_b.node.get_our_node_id(), &commitment_update.commitment_signed);
2575                                 check_added_monitors!(node_a, 1);
2576                                 let as_revoke_and_ack = get_event_msg!(node_a, MessageSendEvent::SendRevokeAndACK, node_b.node.get_our_node_id());
2577                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
2578                                 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &as_revoke_and_ack);
2579                                 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
2580                                 check_added_monitors!(node_b, 1);
2581                         }
2582                 } else {
2583                         assert!(chan_msgs.2.is_none());
2584                 }
2585         }
2586
2587         for chan_msgs in resp_2.drain(..) {
2588                 if send_channel_ready.1 {
2589                         node_b.node.handle_channel_ready(&node_a.node.get_our_node_id(), &chan_msgs.0.unwrap());
2590                         let announcement_event = node_b.node.get_and_clear_pending_msg_events();
2591                         if !announcement_event.is_empty() {
2592                                 assert_eq!(announcement_event.len(), 1);
2593                                 match announcement_event[0] {
2594                                         MessageSendEvent::SendChannelUpdate { .. } => {},
2595                                         MessageSendEvent::SendAnnouncementSignatures { .. } => {},
2596                                         _ => panic!("Unexpected event {:?}!", announcement_event[0]),
2597                                 }
2598                         }
2599                 } else {
2600                         assert!(chan_msgs.0.is_none());
2601                 }
2602                 if pending_raa.1 {
2603                         assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
2604                         node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap());
2605                         assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
2606                         check_added_monitors!(node_b, 1);
2607                 } else {
2608                         assert!(chan_msgs.1.is_none());
2609                 }
2610                 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 {
2611                         let commitment_update = chan_msgs.2.unwrap();
2612                         if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
2613                                 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.1 as usize);
2614                         }
2615                         assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.1 + pending_cell_htlc_claims.1);
2616                         assert_eq!(commitment_update.update_fail_htlcs.len(), pending_htlc_fails.1 + pending_cell_htlc_fails.1);
2617                         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
2618                         for update_add in commitment_update.update_add_htlcs {
2619                                 node_b.node.handle_update_add_htlc(&node_a.node.get_our_node_id(), &update_add);
2620                         }
2621                         for update_fulfill in commitment_update.update_fulfill_htlcs {
2622                                 node_b.node.handle_update_fulfill_htlc(&node_a.node.get_our_node_id(), &update_fulfill);
2623                         }
2624                         for update_fail in commitment_update.update_fail_htlcs {
2625                                 node_b.node.handle_update_fail_htlc(&node_a.node.get_our_node_id(), &update_fail);
2626                         }
2627
2628                         if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
2629                                 commitment_signed_dance!(node_b, node_a, commitment_update.commitment_signed, false);
2630                         } else {
2631                                 node_b.node.handle_commitment_signed(&node_a.node.get_our_node_id(), &commitment_update.commitment_signed);
2632                                 check_added_monitors!(node_b, 1);
2633                                 let bs_revoke_and_ack = get_event_msg!(node_b, MessageSendEvent::SendRevokeAndACK, node_a.node.get_our_node_id());
2634                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
2635                                 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &bs_revoke_and_ack);
2636                                 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
2637                                 check_added_monitors!(node_a, 1);
2638                         }
2639                 } else {
2640                         assert!(chan_msgs.2.is_none());
2641                 }
2642         }
2643 }