Add support for retrieving and suspending the channel signer
[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, chainmonitor::Persist};
14 use crate::sign::EntropySource;
15 use crate::chain::channelmonitor::ChannelMonitor;
16 use crate::chain::transaction::OutPoint;
17 use crate::events::{ClaimedHTLC, ClosureReason, Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentPurpose, PaymentFailureReason};
18 use crate::events::bump_transaction::{BumpTransactionEvent, BumpTransactionEventHandler, Wallet, WalletSource};
19 use crate::ln::{ChannelId, PaymentPreimage, PaymentHash, PaymentSecret};
20 use crate::ln::channelmanager::{AChannelManager, ChainParameters, ChannelManager, ChannelManagerReadArgs, RAACommitmentOrder, PaymentSendFailure, RecipientOnionFields, PaymentId, MIN_CLTV_EXPIRY_DELTA};
21 use crate::routing::gossip::{P2PGossipSync, NetworkGraph, NetworkUpdate};
22 use crate::routing::router::{self, PaymentParameters, Route, RouteParameters};
23 use crate::ln::features::InitFeatures;
24 use crate::ln::msgs;
25 use crate::ln::msgs::{ChannelMessageHandler,RoutingMessageHandler};
26 use crate::util::test_channel_signer::TestChannelSigner;
27 use crate::util::scid_utils;
28 use crate::util::test_utils;
29 use crate::util::test_utils::{panicking, TestChainMonitor, TestScorer, TestKeysInterface};
30 use crate::util::errors::APIError;
31 use crate::util::config::{UserConfig, MaxDustHTLCExposure};
32 use crate::util::ser::{ReadableArgs, Writeable};
33 #[cfg(test)]
34 use crate::util::logger::Logger;
35
36 use bitcoin::blockdata::block::{Block, BlockHeader};
37 use bitcoin::blockdata::transaction::{Transaction, TxOut};
38 use bitcoin::hash_types::BlockHash;
39 use bitcoin::hashes::sha256::Hash as Sha256;
40 use bitcoin::hashes::Hash as _;
41 use bitcoin::network::constants::Network;
42 use bitcoin::secp256k1::{PublicKey, SecretKey};
43
44 use crate::io;
45 use crate::prelude::*;
46 use core::cell::RefCell;
47 use alloc::rc::Rc;
48 use crate::sync::{Arc, Mutex, LockTestExt, RwLock};
49 use core::mem;
50 use core::iter::repeat;
51 use bitcoin::{PackedLockTime, TxIn, TxMerkleNode};
52
53 pub const CHAN_CONFIRM_DEPTH: u32 = 10;
54
55 /// Mine the given transaction in the next block and then mine CHAN_CONFIRM_DEPTH - 1 blocks on
56 /// top, giving the given transaction CHAN_CONFIRM_DEPTH confirmations.
57 ///
58 /// Returns the SCID a channel confirmed in the given transaction will have, assuming the funding
59 /// output is the 1st output in the transaction.
60 pub fn confirm_transaction<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, tx: &Transaction) -> u64 {
61         let scid = confirm_transaction_at(node, tx, node.best_block_info().1 + 1);
62         connect_blocks(node, CHAN_CONFIRM_DEPTH - 1);
63         scid
64 }
65 /// Mine a single block containing the given transaction
66 ///
67 /// Returns the SCID a channel confirmed in the given transaction will have, assuming the funding
68 /// output is the 1st output in the transaction.
69 pub fn mine_transaction<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, tx: &Transaction) -> u64 {
70         let height = node.best_block_info().1 + 1;
71         confirm_transaction_at(node, tx, height)
72 }
73 /// Mine a single block containing the given transactions
74 pub fn mine_transactions<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, txn: &[&Transaction]) {
75         let height = node.best_block_info().1 + 1;
76         confirm_transactions_at(node, txn, height);
77 }
78 /// Mine a single block containing the given transaction without extra consistency checks which may
79 /// impact ChannelManager state.
80 pub fn mine_transaction_without_consistency_checks<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, tx: &Transaction) {
81         let height = node.best_block_info().1 + 1;
82         let mut block = Block {
83                 header: BlockHeader { version: 0x20000000, prev_blockhash: node.best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: height, bits: 42, nonce: 42 },
84                 txdata: Vec::new(),
85         };
86         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
87                 block.txdata.push(Transaction { version: 0, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: Vec::new() });
88         }
89         block.txdata.push((*tx).clone());
90         do_connect_block_without_consistency_checks(node, block, false);
91 }
92 /// Mine the given transaction at the given height, mining blocks as required to build to that
93 /// height
94 ///
95 /// Returns the SCID a channel confirmed in the given transaction will have, assuming the funding
96 /// output is the 1st output in the transaction.
97 pub fn confirm_transactions_at<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, txn: &[&Transaction], conf_height: u32) -> u64 {
98         let first_connect_height = node.best_block_info().1 + 1;
99         assert!(first_connect_height <= conf_height);
100         if conf_height > first_connect_height {
101                 connect_blocks(node, conf_height - first_connect_height);
102         }
103         let mut txdata = Vec::new();
104         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
105                 txdata.push(Transaction { version: 0, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: Vec::new() });
106         }
107         for tx in txn {
108                 txdata.push((*tx).clone());
109         }
110         let block = create_dummy_block(node.best_block_hash(), conf_height, txdata);
111         connect_block(node, &block);
112         scid_utils::scid_from_parts(conf_height as u64, block.txdata.len() as u64 - 1, 0).unwrap()
113 }
114 pub fn confirm_transaction_at<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, tx: &Transaction, conf_height: u32) -> u64 {
115         confirm_transactions_at(node, &[tx], conf_height)
116 }
117
118 /// The possible ways we may notify a ChannelManager of a new block
119 #[derive(Clone, Copy, Debug, PartialEq)]
120 pub enum ConnectStyle {
121         /// Calls `best_block_updated` first, detecting transactions in the block only after receiving
122         /// the header and height information.
123         BestBlockFirst,
124         /// The same as `BestBlockFirst`, however when we have multiple blocks to connect, we only
125         /// make a single `best_block_updated` call.
126         BestBlockFirstSkippingBlocks,
127         /// The same as `BestBlockFirst` when connecting blocks. During disconnection only
128         /// `transaction_unconfirmed` is called.
129         BestBlockFirstReorgsOnlyTip,
130         /// Calls `transactions_confirmed` first, detecting transactions in the block before updating
131         /// the header and height information.
132         TransactionsFirst,
133         /// The same as `TransactionsFirst`, however when we have multiple blocks to connect, we only
134         /// make a single `best_block_updated` call.
135         TransactionsFirstSkippingBlocks,
136         /// The same as `TransactionsFirst`, however when we have multiple blocks to connect, we only
137         /// make a single `best_block_updated` call. Further, we call `transactions_confirmed` multiple
138         /// times to ensure it's idempotent.
139         TransactionsDuplicativelyFirstSkippingBlocks,
140         /// The same as `TransactionsFirst`, however when we have multiple blocks to connect, we only
141         /// make a single `best_block_updated` call. Further, we call `transactions_confirmed` multiple
142         /// times to ensure it's idempotent.
143         HighlyRedundantTransactionsFirstSkippingBlocks,
144         /// The same as `TransactionsFirst` when connecting blocks. During disconnection only
145         /// `transaction_unconfirmed` is called.
146         TransactionsFirstReorgsOnlyTip,
147         /// Provides the full block via the `chain::Listen` interface. In the current code this is
148         /// equivalent to `TransactionsFirst` with some additional assertions.
149         FullBlockViaListen,
150 }
151
152 impl ConnectStyle {
153         pub fn skips_blocks(&self) -> bool {
154                 match self {
155                         ConnectStyle::BestBlockFirst => false,
156                         ConnectStyle::BestBlockFirstSkippingBlocks => true,
157                         ConnectStyle::BestBlockFirstReorgsOnlyTip => true,
158                         ConnectStyle::TransactionsFirst => false,
159                         ConnectStyle::TransactionsFirstSkippingBlocks => true,
160                         ConnectStyle::TransactionsDuplicativelyFirstSkippingBlocks => true,
161                         ConnectStyle::HighlyRedundantTransactionsFirstSkippingBlocks => true,
162                         ConnectStyle::TransactionsFirstReorgsOnlyTip => true,
163                         ConnectStyle::FullBlockViaListen => false,
164                 }
165         }
166
167         pub fn updates_best_block_first(&self) -> bool {
168                 match self {
169                         ConnectStyle::BestBlockFirst => true,
170                         ConnectStyle::BestBlockFirstSkippingBlocks => true,
171                         ConnectStyle::BestBlockFirstReorgsOnlyTip => true,
172                         ConnectStyle::TransactionsFirst => false,
173                         ConnectStyle::TransactionsFirstSkippingBlocks => false,
174                         ConnectStyle::TransactionsDuplicativelyFirstSkippingBlocks => false,
175                         ConnectStyle::HighlyRedundantTransactionsFirstSkippingBlocks => false,
176                         ConnectStyle::TransactionsFirstReorgsOnlyTip => false,
177                         ConnectStyle::FullBlockViaListen => false,
178                 }
179         }
180
181         fn random_style() -> ConnectStyle {
182                 #[cfg(feature = "std")] {
183                         use core::hash::{BuildHasher, Hasher};
184                         // Get a random value using the only std API to do so - the DefaultHasher
185                         let rand_val = std::collections::hash_map::RandomState::new().build_hasher().finish();
186                         let res = match rand_val % 9 {
187                                 0 => ConnectStyle::BestBlockFirst,
188                                 1 => ConnectStyle::BestBlockFirstSkippingBlocks,
189                                 2 => ConnectStyle::BestBlockFirstReorgsOnlyTip,
190                                 3 => ConnectStyle::TransactionsFirst,
191                                 4 => ConnectStyle::TransactionsFirstSkippingBlocks,
192                                 5 => ConnectStyle::TransactionsDuplicativelyFirstSkippingBlocks,
193                                 6 => ConnectStyle::HighlyRedundantTransactionsFirstSkippingBlocks,
194                                 7 => ConnectStyle::TransactionsFirstReorgsOnlyTip,
195                                 8 => ConnectStyle::FullBlockViaListen,
196                                 _ => unreachable!(),
197                         };
198                         eprintln!("Using Block Connection Style: {:?}", res);
199                         res
200                 }
201                 #[cfg(not(feature = "std"))] {
202                         ConnectStyle::FullBlockViaListen
203                 }
204         }
205 }
206
207 pub fn create_dummy_header(prev_blockhash: BlockHash, time: u32) -> BlockHeader {
208         BlockHeader {
209                 version: 0x2000_0000,
210                 prev_blockhash,
211                 merkle_root: TxMerkleNode::all_zeros(),
212                 time,
213                 bits: 42,
214                 nonce: 42,
215         }
216 }
217
218 pub fn create_dummy_block(prev_blockhash: BlockHash, time: u32, txdata: Vec<Transaction>) -> Block {
219         Block { header: create_dummy_header(prev_blockhash, time), txdata }
220 }
221
222 pub fn connect_blocks<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, depth: u32) -> BlockHash {
223         let skip_intermediaries = node.connect_style.borrow().skips_blocks();
224
225         let height = node.best_block_info().1 + 1;
226         let mut block = create_dummy_block(node.best_block_hash(), height, Vec::new());
227         assert!(depth >= 1);
228         for i in 1..depth {
229                 let prev_blockhash = block.header.block_hash();
230                 do_connect_block_with_consistency_checks(node, block, skip_intermediaries);
231                 block = create_dummy_block(prev_blockhash, height + i, Vec::new());
232         }
233         let hash = block.header.block_hash();
234         do_connect_block_with_consistency_checks(node, block, false);
235         hash
236 }
237
238 pub fn connect_block<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, block: &Block) {
239         do_connect_block_with_consistency_checks(node, block.clone(), false);
240 }
241
242 fn call_claimable_balances<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>) {
243         // Ensure `get_claimable_balances`' self-tests never panic
244         for funding_outpoint in node.chain_monitor.chain_monitor.list_monitors() {
245                 node.chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances();
246         }
247 }
248
249 fn do_connect_block_with_consistency_checks<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, block: Block, skip_intermediaries: bool) {
250         call_claimable_balances(node);
251         do_connect_block_without_consistency_checks(node, block, skip_intermediaries);
252         call_claimable_balances(node);
253         node.node.test_process_background_events();
254 }
255
256 fn do_connect_block_without_consistency_checks<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, block: Block, skip_intermediaries: bool) {
257         let height = node.best_block_info().1 + 1;
258         #[cfg(feature = "std")] {
259                 eprintln!("Connecting block using Block Connection Style: {:?}", *node.connect_style.borrow());
260         }
261         // Update the block internally before handing it over to LDK, to ensure our assertions regarding
262         // transaction broadcast are correct.
263         node.blocks.lock().unwrap().push((block.clone(), height));
264         if !skip_intermediaries {
265                 let txdata: Vec<_> = block.txdata.iter().enumerate().collect();
266                 match *node.connect_style.borrow() {
267                         ConnectStyle::BestBlockFirst|ConnectStyle::BestBlockFirstSkippingBlocks|ConnectStyle::BestBlockFirstReorgsOnlyTip => {
268                                 node.chain_monitor.chain_monitor.best_block_updated(&block.header, height);
269                                 call_claimable_balances(node);
270                                 node.chain_monitor.chain_monitor.transactions_confirmed(&block.header, &txdata, height);
271                                 node.node.best_block_updated(&block.header, height);
272                                 node.node.transactions_confirmed(&block.header, &txdata, height);
273                         },
274                         ConnectStyle::TransactionsFirst|ConnectStyle::TransactionsFirstSkippingBlocks|
275                         ConnectStyle::TransactionsDuplicativelyFirstSkippingBlocks|ConnectStyle::HighlyRedundantTransactionsFirstSkippingBlocks|
276                         ConnectStyle::TransactionsFirstReorgsOnlyTip => {
277                                 if *node.connect_style.borrow() == ConnectStyle::HighlyRedundantTransactionsFirstSkippingBlocks {
278                                         let mut connections = Vec::new();
279                                         for (block, height) in node.blocks.lock().unwrap().iter() {
280                                                 if !block.txdata.is_empty() {
281                                                         // Reconnect all transactions we've ever seen to ensure transaction connection
282                                                         // is *really* idempotent. This is a somewhat likely deployment for some
283                                                         // esplora implementations of chain sync which try to reduce state and
284                                                         // complexity as much as possible.
285                                                         //
286                                                         // Sadly we have to clone the block here to maintain lockorder. In the
287                                                         // future we should consider Arc'ing the blocks to avoid this.
288                                                         connections.push((block.clone(), *height));
289                                                 }
290                                         }
291                                         for (old_block, height) in connections {
292                                                 node.chain_monitor.chain_monitor.transactions_confirmed(&old_block.header,
293                                                         &old_block.txdata.iter().enumerate().collect::<Vec<_>>(), height);
294                                         }
295                                 }
296                                 node.chain_monitor.chain_monitor.transactions_confirmed(&block.header, &txdata, height);
297                                 if *node.connect_style.borrow() == ConnectStyle::TransactionsDuplicativelyFirstSkippingBlocks {
298                                         node.chain_monitor.chain_monitor.transactions_confirmed(&block.header, &txdata, height);
299                                 }
300                                 call_claimable_balances(node);
301                                 node.chain_monitor.chain_monitor.best_block_updated(&block.header, height);
302                                 node.node.transactions_confirmed(&block.header, &txdata, height);
303                                 node.node.best_block_updated(&block.header, height);
304                         },
305                         ConnectStyle::FullBlockViaListen => {
306                                 node.chain_monitor.chain_monitor.block_connected(&block, height);
307                                 node.node.block_connected(&block, height);
308                         }
309                 }
310         }
311
312         for tx in &block.txdata {
313                 for input in &tx.input {
314                         node.wallet_source.remove_utxo(input.previous_output);
315                 }
316                 let wallet_script = node.wallet_source.get_change_script().unwrap();
317                 for (idx, output) in tx.output.iter().enumerate() {
318                         if output.script_pubkey == wallet_script {
319                                 let outpoint = bitcoin::OutPoint { txid: tx.txid(), vout: idx as u32 };
320                                 node.wallet_source.add_utxo(outpoint, output.value);
321                         }
322                 }
323         }
324 }
325
326 pub fn disconnect_blocks<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, count: u32) {
327         call_claimable_balances(node);
328         #[cfg(feature = "std")] {
329                 eprintln!("Disconnecting {} blocks using Block Connection Style: {:?}", count, *node.connect_style.borrow());
330         }
331         for i in 0..count {
332                 let orig = node.blocks.lock().unwrap().pop().unwrap();
333                 assert!(orig.1 > 0); // Cannot disconnect genesis
334                 let prev = node.blocks.lock().unwrap().last().unwrap().clone();
335
336                 match *node.connect_style.borrow() {
337                         ConnectStyle::FullBlockViaListen => {
338                                 node.chain_monitor.chain_monitor.block_disconnected(&orig.0.header, orig.1);
339                                 Listen::block_disconnected(node.node, &orig.0.header, orig.1);
340                         },
341                         ConnectStyle::BestBlockFirstSkippingBlocks|ConnectStyle::TransactionsFirstSkippingBlocks|
342                         ConnectStyle::HighlyRedundantTransactionsFirstSkippingBlocks|ConnectStyle::TransactionsDuplicativelyFirstSkippingBlocks => {
343                                 if i == count - 1 {
344                                         node.chain_monitor.chain_monitor.best_block_updated(&prev.0.header, prev.1);
345                                         node.node.best_block_updated(&prev.0.header, prev.1);
346                                 }
347                         },
348                         ConnectStyle::BestBlockFirstReorgsOnlyTip|ConnectStyle::TransactionsFirstReorgsOnlyTip => {
349                                 for tx in orig.0.txdata {
350                                         node.chain_monitor.chain_monitor.transaction_unconfirmed(&tx.txid());
351                                         node.node.transaction_unconfirmed(&tx.txid());
352                                 }
353                         },
354                         _ => {
355                                 node.chain_monitor.chain_monitor.best_block_updated(&prev.0.header, prev.1);
356                                 node.node.best_block_updated(&prev.0.header, prev.1);
357                         },
358                 }
359                 call_claimable_balances(node);
360         }
361 }
362
363 pub fn disconnect_all_blocks<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>) {
364         let count = node.blocks.lock().unwrap().len() as u32 - 1;
365         disconnect_blocks(node, count);
366 }
367
368 pub struct TestChanMonCfg {
369         pub tx_broadcaster: test_utils::TestBroadcaster,
370         pub fee_estimator: test_utils::TestFeeEstimator,
371         pub chain_source: test_utils::TestChainSource,
372         pub persister: test_utils::TestPersister,
373         pub logger: test_utils::TestLogger,
374         pub keys_manager: test_utils::TestKeysInterface,
375         pub scorer: RwLock<test_utils::TestScorer>,
376 }
377
378 pub struct NodeCfg<'a> {
379         pub chain_source: &'a test_utils::TestChainSource,
380         pub tx_broadcaster: &'a test_utils::TestBroadcaster,
381         pub fee_estimator: &'a test_utils::TestFeeEstimator,
382         pub router: test_utils::TestRouter<'a>,
383         pub chain_monitor: test_utils::TestChainMonitor<'a>,
384         pub keys_manager: &'a test_utils::TestKeysInterface,
385         pub logger: &'a test_utils::TestLogger,
386         pub network_graph: Arc<NetworkGraph<&'a test_utils::TestLogger>>,
387         pub node_seed: [u8; 32],
388         pub override_init_features: Rc<RefCell<Option<InitFeatures>>>,
389 }
390
391 type TestChannelManager<'node_cfg, 'chan_mon_cfg> = ChannelManager<
392         &'node_cfg TestChainMonitor<'chan_mon_cfg>,
393         &'chan_mon_cfg test_utils::TestBroadcaster,
394         &'node_cfg test_utils::TestKeysInterface,
395         &'node_cfg test_utils::TestKeysInterface,
396         &'node_cfg test_utils::TestKeysInterface,
397         &'chan_mon_cfg test_utils::TestFeeEstimator,
398         &'node_cfg test_utils::TestRouter<'chan_mon_cfg>,
399         &'chan_mon_cfg test_utils::TestLogger,
400 >;
401
402 pub struct Node<'chan_man, 'node_cfg: 'chan_man, 'chan_mon_cfg: 'node_cfg> {
403         pub chain_source: &'chan_mon_cfg test_utils::TestChainSource,
404         pub tx_broadcaster: &'chan_mon_cfg test_utils::TestBroadcaster,
405         pub fee_estimator: &'chan_mon_cfg test_utils::TestFeeEstimator,
406         pub router: &'node_cfg test_utils::TestRouter<'chan_mon_cfg>,
407         pub chain_monitor: &'node_cfg test_utils::TestChainMonitor<'chan_mon_cfg>,
408         pub keys_manager: &'chan_mon_cfg test_utils::TestKeysInterface,
409         pub node: &'chan_man TestChannelManager<'node_cfg, 'chan_mon_cfg>,
410         pub network_graph: &'node_cfg NetworkGraph<&'chan_mon_cfg test_utils::TestLogger>,
411         pub gossip_sync: P2PGossipSync<&'node_cfg NetworkGraph<&'chan_mon_cfg test_utils::TestLogger>, &'chan_mon_cfg test_utils::TestChainSource, &'chan_mon_cfg test_utils::TestLogger>,
412         pub node_seed: [u8; 32],
413         pub network_payment_count: Rc<RefCell<u8>>,
414         pub network_chan_count: Rc<RefCell<u32>>,
415         pub logger: &'chan_mon_cfg test_utils::TestLogger,
416         pub blocks: Arc<Mutex<Vec<(Block, u32)>>>,
417         pub connect_style: Rc<RefCell<ConnectStyle>>,
418         pub override_init_features: Rc<RefCell<Option<InitFeatures>>>,
419         pub wallet_source: Arc<test_utils::TestWalletSource>,
420         pub bump_tx_handler: BumpTransactionEventHandler<
421                 &'chan_mon_cfg test_utils::TestBroadcaster,
422                 Arc<Wallet<Arc<test_utils::TestWalletSource>, &'chan_mon_cfg test_utils::TestLogger>>,
423                 &'chan_mon_cfg test_utils::TestKeysInterface,
424                 &'chan_mon_cfg test_utils::TestLogger,
425         >,
426 }
427 #[cfg(feature = "std")]
428 impl<'a, 'b, 'c> std::panic::UnwindSafe for Node<'a, 'b, 'c> {}
429 #[cfg(feature = "std")]
430 impl<'a, 'b, 'c> std::panic::RefUnwindSafe for Node<'a, 'b, 'c> {}
431 impl<'a, 'b, 'c> Node<'a, 'b, 'c> {
432         pub fn best_block_hash(&self) -> BlockHash {
433                 self.blocks.lock().unwrap().last().unwrap().0.block_hash()
434         }
435         pub fn best_block_info(&self) -> (BlockHash, u32) {
436                 self.blocks.lock().unwrap().last().map(|(a, b)| (a.block_hash(), *b)).unwrap()
437         }
438         pub fn get_block_header(&self, height: u32) -> BlockHeader {
439                 self.blocks.lock().unwrap()[height as usize].0.header
440         }
441         /// Changes the channel signer's availability for the specified peer and channel.
442         ///
443         /// When `available` is set to `true`, the channel signer will behave normally. When set to
444         /// `false`, the channel signer will act like an off-line remote signer and will return `Err` for
445         /// several of the signing methods. Currently, only `get_per_commitment_point` and
446         /// `release_commitment_secret` are affected by this setting.
447         #[cfg(test)]
448         pub fn set_channel_signer_available(&self, peer_id: &PublicKey, chan_id: &ChannelId, available: bool) {
449                 let per_peer_state = self.node.per_peer_state.read().unwrap();
450                 let chan_lock = per_peer_state.get(peer_id).unwrap().lock().unwrap();
451                 let signer = (|| {
452                         match chan_lock.channel_by_id.get(chan_id) {
453                                 Some(phase) => phase.context().get_signer(),
454                                 None => panic!("Couldn't find a channel with id {}", chan_id),
455                         }
456                 })();
457                 log_debug!(self.logger, "Setting channel signer for {} as available={}", chan_id, available);
458                 signer.as_ecdsa().unwrap().set_available(available);
459         }
460 }
461
462 /// If we need an unsafe pointer to a `Node` (ie to reference it in a thread
463 /// pre-std::thread::scope), this provides that with `Sync`. Note that accessing some of the fields
464 /// in the `Node` are not safe to use (i.e. the ones behind an `Rc`), but that's left to the caller
465 /// to figure out.
466 pub struct NodePtr(pub *const Node<'static, 'static, 'static>);
467 impl NodePtr {
468         pub fn from_node<'a, 'b: 'a, 'c: 'b>(node: &Node<'a, 'b, 'c>) -> Self {
469                 Self((node as *const Node<'a, 'b, 'c>).cast())
470         }
471 }
472 unsafe impl Send for NodePtr {}
473 unsafe impl Sync for NodePtr {}
474
475
476 pub trait NodeHolder {
477         type CM: AChannelManager;
478         fn node(&self) -> &ChannelManager<
479                 <Self::CM as AChannelManager>::M,
480                 <Self::CM as AChannelManager>::T,
481                 <Self::CM as AChannelManager>::ES,
482                 <Self::CM as AChannelManager>::NS,
483                 <Self::CM as AChannelManager>::SP,
484                 <Self::CM as AChannelManager>::F,
485                 <Self::CM as AChannelManager>::R,
486                 <Self::CM as AChannelManager>::L>;
487         fn chain_monitor(&self) -> Option<&test_utils::TestChainMonitor>;
488 }
489 impl<H: NodeHolder> NodeHolder for &H {
490         type CM = H::CM;
491         fn node(&self) -> &ChannelManager<
492                 <Self::CM as AChannelManager>::M,
493                 <Self::CM as AChannelManager>::T,
494                 <Self::CM as AChannelManager>::ES,
495                 <Self::CM as AChannelManager>::NS,
496                 <Self::CM as AChannelManager>::SP,
497                 <Self::CM as AChannelManager>::F,
498                 <Self::CM as AChannelManager>::R,
499                 <Self::CM as AChannelManager>::L> { (*self).node() }
500         fn chain_monitor(&self) -> Option<&test_utils::TestChainMonitor> { (*self).chain_monitor() }
501 }
502 impl<'a, 'b: 'a, 'c: 'b> NodeHolder for Node<'a, 'b, 'c> {
503         type CM = TestChannelManager<'b, 'c>;
504         fn node(&self) -> &TestChannelManager<'b, 'c> { &self.node }
505         fn chain_monitor(&self) -> Option<&test_utils::TestChainMonitor> { Some(self.chain_monitor) }
506 }
507
508 impl<'a, 'b, 'c> Drop for Node<'a, 'b, 'c> {
509         fn drop(&mut self) {
510                 if !panicking() {
511                         // Check that we processed all pending events
512                         let msg_events = self.node.get_and_clear_pending_msg_events();
513                         if !msg_events.is_empty() {
514                                 panic!("Had excess message events on node {}: {:?}", self.logger.id, msg_events);
515                         }
516                         let events = self.node.get_and_clear_pending_events();
517                         if !events.is_empty() {
518                                 panic!("Had excess events on node {}: {:?}", self.logger.id, events);
519                         }
520                         let added_monitors = self.chain_monitor.added_monitors.lock().unwrap().split_off(0);
521                         if !added_monitors.is_empty() {
522                                 panic!("Had {} excess added monitors on node {}", added_monitors.len(), self.logger.id);
523                         }
524
525                         // Check that if we serialize the network graph, we can deserialize it again.
526                         let network_graph = {
527                                 let mut w = test_utils::TestVecWriter(Vec::new());
528                                 self.network_graph.write(&mut w).unwrap();
529                                 let network_graph_deser = <NetworkGraph<_>>::read(&mut io::Cursor::new(&w.0), self.logger).unwrap();
530                                 assert!(network_graph_deser == *self.network_graph);
531                                 let gossip_sync = P2PGossipSync::new(
532                                         &network_graph_deser, Some(self.chain_source), self.logger
533                                 );
534                                 let mut chan_progress = 0;
535                                 loop {
536                                         let orig_announcements = self.gossip_sync.get_next_channel_announcement(chan_progress);
537                                         let deserialized_announcements = gossip_sync.get_next_channel_announcement(chan_progress);
538                                         assert!(orig_announcements == deserialized_announcements);
539                                         chan_progress = match orig_announcements {
540                                                 Some(announcement) => announcement.0.contents.short_channel_id + 1,
541                                                 None => break,
542                                         };
543                                 }
544                                 let mut node_progress = None;
545                                 loop {
546                                         let orig_announcements = self.gossip_sync.get_next_node_announcement(node_progress.as_ref());
547                                         let deserialized_announcements = gossip_sync.get_next_node_announcement(node_progress.as_ref());
548                                         assert!(orig_announcements == deserialized_announcements);
549                                         node_progress = match orig_announcements {
550                                                 Some(announcement) => Some(announcement.contents.node_id),
551                                                 None => break,
552                                         };
553                                 }
554                                 network_graph_deser
555                         };
556
557                         // Check that if we serialize and then deserialize all our channel monitors we get the
558                         // same set of outputs to watch for on chain as we have now. Note that if we write
559                         // tests that fully close channels and remove the monitors at some point this may break.
560                         let feeest = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
561                         let mut deserialized_monitors = Vec::new();
562                         {
563                                 for outpoint in self.chain_monitor.chain_monitor.list_monitors() {
564                                         let mut w = test_utils::TestVecWriter(Vec::new());
565                                         self.chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut w).unwrap();
566                                         let (_, deserialized_monitor) = <(BlockHash, ChannelMonitor<TestChannelSigner>)>::read(
567                                                 &mut io::Cursor::new(&w.0), (self.keys_manager, self.keys_manager)).unwrap();
568                                         deserialized_monitors.push(deserialized_monitor);
569                                 }
570                         }
571
572                         let broadcaster = test_utils::TestBroadcaster {
573                                 txn_broadcasted: Mutex::new(self.tx_broadcaster.txn_broadcasted.lock().unwrap().clone()),
574                                 blocks: Arc::new(Mutex::new(self.tx_broadcaster.blocks.lock().unwrap().clone())),
575                         };
576
577                         // Before using all the new monitors to check the watch outpoints, use the full set of
578                         // them to ensure we can write and reload our ChannelManager.
579                         {
580                                 let mut channel_monitors = HashMap::new();
581                                 for monitor in deserialized_monitors.iter_mut() {
582                                         channel_monitors.insert(monitor.get_funding_txo().0, monitor);
583                                 }
584
585                                 let scorer = RwLock::new(test_utils::TestScorer::new());
586                                 let mut w = test_utils::TestVecWriter(Vec::new());
587                                 self.node.write(&mut w).unwrap();
588                                 <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestRouter, &test_utils::TestLogger>)>::read(&mut io::Cursor::new(w.0), ChannelManagerReadArgs {
589                                         default_config: *self.node.get_current_default_configuration(),
590                                         entropy_source: self.keys_manager,
591                                         node_signer: self.keys_manager,
592                                         signer_provider: self.keys_manager,
593                                         fee_estimator: &test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
594                                         router: &test_utils::TestRouter::new(Arc::new(network_graph), &scorer),
595                                         chain_monitor: self.chain_monitor,
596                                         tx_broadcaster: &broadcaster,
597                                         logger: &self.logger,
598                                         channel_monitors,
599                                 }).unwrap();
600                         }
601
602                         let persister = test_utils::TestPersister::new();
603                         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
604                         let chain_monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &broadcaster, &self.logger, &feeest, &persister, &self.keys_manager);
605                         for deserialized_monitor in deserialized_monitors.drain(..) {
606                                 if chain_monitor.watch_channel(deserialized_monitor.get_funding_txo().0, deserialized_monitor) != Ok(ChannelMonitorUpdateStatus::Completed) {
607                                         panic!();
608                                 }
609                         }
610                         assert_eq!(*chain_source.watched_txn.unsafe_well_ordered_double_lock_self(), *self.chain_source.watched_txn.unsafe_well_ordered_double_lock_self());
611                         assert_eq!(*chain_source.watched_outputs.unsafe_well_ordered_double_lock_self(), *self.chain_source.watched_outputs.unsafe_well_ordered_double_lock_self());
612                 }
613         }
614 }
615
616 pub fn create_chan_between_nodes<'a, 'b, 'c: 'd, 'd>(node_a: &'a Node<'b, 'c, 'd>, node_b: &'a Node<'b, 'c, 'd>) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, ChannelId, Transaction) {
617         create_chan_between_nodes_with_value(node_a, node_b, 100000, 10001)
618 }
619
620 pub fn create_chan_between_nodes_with_value<'a, 'b, 'c: 'd, 'd>(node_a: &'a Node<'b, 'c, 'd>, node_b: &'a Node<'b, 'c, 'd>, channel_value: u64, push_msat: u64) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, ChannelId, Transaction) {
621         let (channel_ready, channel_id, tx) = create_chan_between_nodes_with_value_a(node_a, node_b, channel_value, push_msat);
622         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(node_a, node_b, &channel_ready);
623         (announcement, as_update, bs_update, channel_id, tx)
624 }
625
626 /// Gets an RAA and CS which were sent in response to a commitment update
627 pub fn get_revoke_commit_msgs<CM: AChannelManager, H: NodeHolder<CM=CM>>(node: &H, recipient: &PublicKey) -> (msgs::RevokeAndACK, msgs::CommitmentSigned) {
628         let events = node.node().get_and_clear_pending_msg_events();
629         assert_eq!(events.len(), 2);
630         (match events[0] {
631                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
632                         assert_eq!(node_id, recipient);
633                         (*msg).clone()
634                 },
635                 _ => panic!("Unexpected event"),
636         }, match events[1] {
637                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
638                         assert_eq!(node_id, recipient);
639                         assert!(updates.update_add_htlcs.is_empty());
640                         assert!(updates.update_fulfill_htlcs.is_empty());
641                         assert!(updates.update_fail_htlcs.is_empty());
642                         assert!(updates.update_fail_malformed_htlcs.is_empty());
643                         assert!(updates.update_fee.is_none());
644                         updates.commitment_signed.clone()
645                 },
646                 _ => panic!("Unexpected event"),
647         })
648 }
649
650 #[macro_export]
651 /// Gets an RAA and CS which were sent in response to a commitment update
652 ///
653 /// Don't use this, use the identically-named function instead.
654 macro_rules! get_revoke_commit_msgs {
655         ($node: expr, $node_id: expr) => {
656                 $crate::ln::functional_test_utils::get_revoke_commit_msgs(&$node, &$node_id)
657         }
658 }
659
660 /// Get an specific event message from the pending events queue.
661 #[macro_export]
662 macro_rules! get_event_msg {
663         ($node: expr, $event_type: path, $node_id: expr) => {
664                 {
665                         let events = $node.node.get_and_clear_pending_msg_events();
666                         assert_eq!(events.len(), 1);
667                         match events[0] {
668                                 $event_type { ref node_id, ref msg } => {
669                                         assert_eq!(*node_id, $node_id);
670                                         (*msg).clone()
671                                 },
672                                 _ => panic!("Unexpected event"),
673                         }
674                 }
675         }
676 }
677
678 /// Get an error message from the pending events queue.
679 pub fn get_err_msg(node: &Node, recipient: &PublicKey) -> msgs::ErrorMessage {
680         let events = node.node.get_and_clear_pending_msg_events();
681         assert_eq!(events.len(), 1);
682         match events[0] {
683                 MessageSendEvent::HandleError {
684                         action: msgs::ErrorAction::SendErrorMessage { ref msg }, ref node_id
685                 } => {
686                         assert_eq!(node_id, recipient);
687                         (*msg).clone()
688                 },
689                 MessageSendEvent::HandleError {
690                         action: msgs::ErrorAction::DisconnectPeer { ref msg }, ref node_id
691                 } => {
692                         assert_eq!(node_id, recipient);
693                         msg.as_ref().unwrap().clone()
694                 },
695                 _ => panic!("Unexpected event"),
696         }
697 }
698
699 /// Get a specific event from the pending events queue.
700 #[macro_export]
701 macro_rules! get_event {
702         ($node: expr, $event_type: path) => {
703                 {
704                         let mut events = $node.node.get_and_clear_pending_events();
705                         assert_eq!(events.len(), 1);
706                         let ev = events.pop().unwrap();
707                         match ev {
708                                 $event_type { .. } => {
709                                         ev
710                                 },
711                                 _ => panic!("Unexpected event"),
712                         }
713                 }
714         }
715 }
716
717 /// Gets an UpdateHTLCs MessageSendEvent
718 pub fn get_htlc_update_msgs(node: &Node, recipient: &PublicKey) -> msgs::CommitmentUpdate {
719         let events = node.node.get_and_clear_pending_msg_events();
720         assert_eq!(events.len(), 1);
721         match events[0] {
722                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
723                         assert_eq!(node_id, recipient);
724                         (*updates).clone()
725                 },
726                 _ => panic!("Unexpected event"),
727         }
728 }
729
730 #[macro_export]
731 /// Gets an UpdateHTLCs MessageSendEvent
732 ///
733 /// Don't use this, use the identically-named function instead.
734 macro_rules! get_htlc_update_msgs {
735         ($node: expr, $node_id: expr) => {
736                 $crate::ln::functional_test_utils::get_htlc_update_msgs(&$node, &$node_id)
737         }
738 }
739
740 /// Fetches the first `msg_event` to the passed `node_id` in the passed `msg_events` vec.
741 /// Returns the `msg_event`.
742 ///
743 /// Note that even though `BroadcastChannelAnnouncement` and `BroadcastChannelUpdate`
744 /// `msg_events` are stored under specific peers, this function does not fetch such `msg_events` as
745 /// such messages are intended to all peers.
746 pub fn remove_first_msg_event_to_node(msg_node_id: &PublicKey, msg_events: &mut Vec<MessageSendEvent>) -> MessageSendEvent {
747         let ev_index = msg_events.iter().position(|e| { match e {
748                 MessageSendEvent::SendAcceptChannel { node_id, .. } => {
749                         node_id == msg_node_id
750                 },
751                 MessageSendEvent::SendOpenChannel { node_id, .. } => {
752                         node_id == msg_node_id
753                 },
754                 MessageSendEvent::SendFundingCreated { node_id, .. } => {
755                         node_id == msg_node_id
756                 },
757                 MessageSendEvent::SendFundingSigned { node_id, .. } => {
758                         node_id == msg_node_id
759                 },
760                 MessageSendEvent::SendChannelReady { node_id, .. } => {
761                         node_id == msg_node_id
762                 },
763                 MessageSendEvent::SendAnnouncementSignatures { node_id, .. } => {
764                         node_id == msg_node_id
765                 },
766                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
767                         node_id == msg_node_id
768                 },
769                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
770                         node_id == msg_node_id
771                 },
772                 MessageSendEvent::SendClosingSigned { node_id, .. } => {
773                         node_id == msg_node_id
774                 },
775                 MessageSendEvent::SendShutdown { node_id, .. } => {
776                         node_id == msg_node_id
777                 },
778                 MessageSendEvent::SendChannelReestablish { node_id, .. } => {
779                         node_id == msg_node_id
780                 },
781                 MessageSendEvent::SendChannelAnnouncement { node_id, .. } => {
782                         node_id == msg_node_id
783                 },
784                 MessageSendEvent::BroadcastChannelAnnouncement { .. } => {
785                         false
786                 },
787                 MessageSendEvent::BroadcastChannelUpdate { .. } => {
788                         false
789                 },
790                 MessageSendEvent::BroadcastNodeAnnouncement { .. } => {
791                         false
792                 },
793                 MessageSendEvent::SendChannelUpdate { node_id, .. } => {
794                         node_id == msg_node_id
795                 },
796                 MessageSendEvent::HandleError { node_id, .. } => {
797                         node_id == msg_node_id
798                 },
799                 MessageSendEvent::SendChannelRangeQuery { node_id, .. } => {
800                         node_id == msg_node_id
801                 },
802                 MessageSendEvent::SendShortIdsQuery { node_id, .. } => {
803                         node_id == msg_node_id
804                 },
805                 MessageSendEvent::SendReplyChannelRange { node_id, .. } => {
806                         node_id == msg_node_id
807                 },
808                 MessageSendEvent::SendGossipTimestampFilter { node_id, .. } => {
809                         node_id == msg_node_id
810                 },
811                 MessageSendEvent::SendAcceptChannelV2 { node_id, .. } => {
812                         node_id == msg_node_id
813                 },
814                 MessageSendEvent::SendOpenChannelV2 { node_id, .. } => {
815                         node_id == msg_node_id
816                 },
817                 MessageSendEvent::SendTxAddInput { node_id, .. } => {
818                         node_id == msg_node_id
819                 },
820                 MessageSendEvent::SendTxAddOutput { node_id, .. } => {
821                         node_id == msg_node_id
822                 },
823                 MessageSendEvent::SendTxRemoveInput { node_id, .. } => {
824                         node_id == msg_node_id
825                 },
826                 MessageSendEvent::SendTxRemoveOutput { node_id, .. } => {
827                         node_id == msg_node_id
828                 },
829                 MessageSendEvent::SendTxComplete { node_id, .. } => {
830                         node_id == msg_node_id
831                 },
832                 MessageSendEvent::SendTxSignatures { node_id, .. } => {
833                         node_id == msg_node_id
834                 },
835                 MessageSendEvent::SendTxInitRbf { node_id, .. } => {
836                         node_id == msg_node_id
837                 },
838                 MessageSendEvent::SendTxAckRbf { node_id, .. } => {
839                         node_id == msg_node_id
840                 },
841                 MessageSendEvent::SendTxAbort { node_id, .. } => {
842                         node_id == msg_node_id
843                 },
844         }});
845         if ev_index.is_some() {
846                 msg_events.remove(ev_index.unwrap())
847         } else {
848                 panic!("Couldn't find any MessageSendEvent to the node!")
849         }
850 }
851
852 #[cfg(test)]
853 macro_rules! get_channel_ref {
854         ($node: expr, $counterparty_node: expr, $per_peer_state_lock: ident, $peer_state_lock: ident, $channel_id: expr) => {
855                 {
856                         $per_peer_state_lock = $node.node.per_peer_state.read().unwrap();
857                         $peer_state_lock = $per_peer_state_lock.get(&$counterparty_node.node.get_our_node_id()).unwrap().lock().unwrap();
858                         $peer_state_lock.channel_by_id.get_mut(&$channel_id).unwrap()
859                 }
860         }
861 }
862
863 #[cfg(test)]
864 macro_rules! get_feerate {
865         ($node: expr, $counterparty_node: expr, $channel_id: expr) => {
866                 {
867                         let mut per_peer_state_lock;
868                         let mut peer_state_lock;
869                         let phase = get_channel_ref!($node, $counterparty_node, per_peer_state_lock, peer_state_lock, $channel_id);
870                         phase.context().get_feerate_sat_per_1000_weight()
871                 }
872         }
873 }
874
875 #[cfg(test)]
876 macro_rules! get_channel_type_features {
877         ($node: expr, $counterparty_node: expr, $channel_id: expr) => {
878                 {
879                         let mut per_peer_state_lock;
880                         let mut peer_state_lock;
881                         let chan = get_channel_ref!($node, $counterparty_node, per_peer_state_lock, peer_state_lock, $channel_id);
882                         chan.context().get_channel_type().clone()
883                 }
884         }
885 }
886
887 /// Returns a channel monitor given a channel id, making some naive assumptions
888 #[macro_export]
889 macro_rules! get_monitor {
890         ($node: expr, $channel_id: expr) => {
891                 {
892                         use bitcoin::hashes::Hash;
893                         let mut monitor = None;
894                         // Assume funding vout is either 0 or 1 blindly
895                         for index in 0..2 {
896                                 if let Ok(mon) = $node.chain_monitor.chain_monitor.get_monitor(
897                                         $crate::chain::transaction::OutPoint {
898                                                 txid: bitcoin::Txid::from_slice(&$channel_id.0[..]).unwrap(), index
899                                         })
900                                 {
901                                         monitor = Some(mon);
902                                         break;
903                                 }
904                         }
905                         monitor.unwrap()
906                 }
907         }
908 }
909
910 /// Returns any local commitment transactions for the channel.
911 #[macro_export]
912 macro_rules! get_local_commitment_txn {
913         ($node: expr, $channel_id: expr) => {
914                 {
915                         $crate::get_monitor!($node, $channel_id).unsafe_get_latest_holder_commitment_txn(&$node.logger)
916                 }
917         }
918 }
919
920 /// Check the error from attempting a payment.
921 #[macro_export]
922 macro_rules! unwrap_send_err {
923         ($res: expr, $all_failed: expr, $type: pat, $check: expr) => {
924                 match &$res {
925                         &Err(PaymentSendFailure::AllFailedResendSafe(ref fails)) if $all_failed => {
926                                 assert_eq!(fails.len(), 1);
927                                 match fails[0] {
928                                         $type => { $check },
929                                         _ => panic!(),
930                                 }
931                         },
932                         &Err(PaymentSendFailure::PartialFailure { ref results, .. }) if !$all_failed => {
933                                 assert_eq!(results.len(), 1);
934                                 match results[0] {
935                                         Err($type) => { $check },
936                                         _ => panic!(),
937                                 }
938                         },
939                         _ => panic!(),
940                 }
941         }
942 }
943
944 /// Check whether N channel monitor(s) have been added.
945 pub fn check_added_monitors<CM: AChannelManager, H: NodeHolder<CM=CM>>(node: &H, count: usize) {
946         if let Some(chain_monitor) = node.chain_monitor() {
947                 let mut added_monitors = chain_monitor.added_monitors.lock().unwrap();
948                 assert_eq!(added_monitors.len(), count);
949                 added_monitors.clear();
950         }
951 }
952
953 /// Check whether N channel monitor(s) have been added.
954 ///
955 /// Don't use this, use the identically-named function instead.
956 #[macro_export]
957 macro_rules! check_added_monitors {
958         ($node: expr, $count: expr) => {
959                 $crate::ln::functional_test_utils::check_added_monitors(&$node, $count);
960         }
961 }
962
963 /// Checks whether the claimed HTLC for the specified path has the correct channel information.
964 ///
965 /// This will panic if the path is empty, if the HTLC's channel ID is not actually a channel that
966 /// connects the final two nodes in the path, or if the `user_channel_id` is incorrect.
967 pub fn check_claimed_htlc_channel<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, path: &[&Node<'a, 'b, 'c>], htlc: &ClaimedHTLC) {
968         let mut nodes = path.iter().rev();
969         let dest = nodes.next().expect("path should have a destination").node;
970         let prev = nodes.next().unwrap_or(&origin_node).node;
971         let dest_channels = dest.list_channels();
972         let ch = dest_channels.iter().find(|ch| ch.channel_id == htlc.channel_id)
973                 .expect("HTLC's channel should be one of destination node's channels");
974         assert_eq!(htlc.user_channel_id, ch.user_channel_id);
975         assert_eq!(ch.counterparty.node_id, prev.get_our_node_id());
976 }
977
978 pub fn _reload_node<'a, 'b, 'c>(node: &'a Node<'a, 'b, 'c>, default_config: UserConfig, chanman_encoded: &[u8], monitors_encoded: &[&[u8]]) -> TestChannelManager<'b, 'c> {
979         let mut monitors_read = Vec::with_capacity(monitors_encoded.len());
980         for encoded in monitors_encoded {
981                 let mut monitor_read = &encoded[..];
982                 let (_, monitor) = <(BlockHash, ChannelMonitor<TestChannelSigner>)>
983                         ::read(&mut monitor_read, (node.keys_manager, node.keys_manager)).unwrap();
984                 assert!(monitor_read.is_empty());
985                 monitors_read.push(monitor);
986         }
987
988         let mut node_read = &chanman_encoded[..];
989         let (_, node_deserialized) = {
990                 let mut channel_monitors = HashMap::new();
991                 for monitor in monitors_read.iter_mut() {
992                         assert!(channel_monitors.insert(monitor.get_funding_txo().0, monitor).is_none());
993                 }
994                 <(BlockHash, TestChannelManager<'b, 'c>)>::read(&mut node_read, ChannelManagerReadArgs {
995                         default_config,
996                         entropy_source: node.keys_manager,
997                         node_signer: node.keys_manager,
998                         signer_provider: node.keys_manager,
999                         fee_estimator: node.fee_estimator,
1000                         router: node.router,
1001                         chain_monitor: node.chain_monitor,
1002                         tx_broadcaster: node.tx_broadcaster,
1003                         logger: node.logger,
1004                         channel_monitors,
1005                 }).unwrap()
1006         };
1007         assert!(node_read.is_empty());
1008
1009         for monitor in monitors_read.drain(..) {
1010                 assert_eq!(node.chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor),
1011                         Ok(ChannelMonitorUpdateStatus::Completed));
1012                 check_added_monitors!(node, 1);
1013         }
1014
1015         node_deserialized
1016 }
1017
1018 #[cfg(test)]
1019 macro_rules! reload_node {
1020         ($node: expr, $new_config: expr, $chanman_encoded: expr, $monitors_encoded: expr, $persister: ident, $new_chain_monitor: ident, $new_channelmanager: ident) => {
1021                 let chanman_encoded = $chanman_encoded;
1022
1023                 $persister = test_utils::TestPersister::new();
1024                 $new_chain_monitor = test_utils::TestChainMonitor::new(Some($node.chain_source), $node.tx_broadcaster.clone(), $node.logger, $node.fee_estimator, &$persister, &$node.keys_manager);
1025                 $node.chain_monitor = &$new_chain_monitor;
1026
1027                 $new_channelmanager = _reload_node(&$node, $new_config, &chanman_encoded, $monitors_encoded);
1028                 $node.node = &$new_channelmanager;
1029         };
1030         ($node: expr, $chanman_encoded: expr, $monitors_encoded: expr, $persister: ident, $new_chain_monitor: ident, $new_channelmanager: ident) => {
1031                 reload_node!($node, $crate::util::config::UserConfig::default(), $chanman_encoded, $monitors_encoded, $persister, $new_chain_monitor, $new_channelmanager);
1032         };
1033 }
1034
1035 pub fn create_funding_transaction<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>,
1036         expected_counterparty_node_id: &PublicKey, expected_chan_value: u64, expected_user_chan_id: u128)
1037  -> (ChannelId, Transaction, OutPoint)
1038 {
1039         internal_create_funding_transaction(node, expected_counterparty_node_id, expected_chan_value, expected_user_chan_id, false)
1040 }
1041
1042 pub fn create_coinbase_funding_transaction<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>,
1043         expected_counterparty_node_id: &PublicKey, expected_chan_value: u64, expected_user_chan_id: u128)
1044  -> (ChannelId, Transaction, OutPoint)
1045 {
1046         internal_create_funding_transaction(node, expected_counterparty_node_id, expected_chan_value, expected_user_chan_id, true)
1047 }
1048
1049 fn internal_create_funding_transaction<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>,
1050         expected_counterparty_node_id: &PublicKey, expected_chan_value: u64, expected_user_chan_id: u128,
1051         coinbase: bool) -> (ChannelId, Transaction, OutPoint) {
1052         let chan_id = *node.network_chan_count.borrow();
1053
1054         let events = node.node.get_and_clear_pending_events();
1055         assert_eq!(events.len(), 1);
1056         match events[0] {
1057                 Event::FundingGenerationReady { ref temporary_channel_id, ref counterparty_node_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
1058                         assert_eq!(counterparty_node_id, expected_counterparty_node_id);
1059                         assert_eq!(*channel_value_satoshis, expected_chan_value);
1060                         assert_eq!(user_channel_id, expected_user_chan_id);
1061
1062                         let input = if coinbase {
1063                                 vec![TxIn {
1064                                         previous_output: bitcoin::OutPoint::null(),
1065                                         ..Default::default()
1066                                 }]
1067                         } else {
1068                                 Vec::new()
1069                         };
1070
1071                         let tx = Transaction { version: chan_id as i32, lock_time: PackedLockTime::ZERO, input, output: vec![TxOut {
1072                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
1073                         }]};
1074                         let funding_outpoint = OutPoint { txid: tx.txid(), index: 0 };
1075                         (*temporary_channel_id, tx, funding_outpoint)
1076                 },
1077                 _ => panic!("Unexpected event"),
1078         }
1079 }
1080
1081 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: ChannelId) -> Transaction {
1082         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(node_a, &node_b.node.get_our_node_id(), channel_value, 42);
1083         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
1084
1085         assert!(node_a.node.funding_transaction_generated(&temporary_channel_id, &node_b.node.get_our_node_id(), tx.clone()).is_ok());
1086         check_added_monitors!(node_a, 0);
1087
1088         let funding_created_msg = get_event_msg!(node_a, MessageSendEvent::SendFundingCreated, node_b.node.get_our_node_id());
1089         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
1090         node_b.node.handle_funding_created(&node_a.node.get_our_node_id(), &funding_created_msg);
1091         {
1092                 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
1093                 assert_eq!(added_monitors.len(), 1);
1094                 assert_eq!(added_monitors[0].0, funding_output);
1095                 added_monitors.clear();
1096         }
1097         expect_channel_pending_event(&node_b, &node_a.node.get_our_node_id());
1098
1099         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()));
1100         {
1101                 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
1102                 assert_eq!(added_monitors.len(), 1);
1103                 assert_eq!(added_monitors[0].0, funding_output);
1104                 added_monitors.clear();
1105         }
1106         expect_channel_pending_event(&node_a, &node_b.node.get_our_node_id());
1107
1108         let events_4 = node_a.node.get_and_clear_pending_events();
1109         assert_eq!(events_4.len(), 0);
1110
1111         assert_eq!(node_a.tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1112         assert_eq!(node_a.tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
1113         node_a.tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1114
1115         // Ensure that funding_transaction_generated is idempotent.
1116         assert!(node_a.node.funding_transaction_generated(&temporary_channel_id, &node_b.node.get_our_node_id(), tx.clone()).is_err());
1117         assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
1118         check_added_monitors!(node_a, 0);
1119
1120         tx
1121 }
1122
1123 // Receiver must have been initialized with manually_accept_inbound_channels set to true.
1124 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, ChannelId) {
1125         let initiator_channels = initiator.node.list_usable_channels().len();
1126         let receiver_channels = receiver.node.list_usable_channels().len();
1127
1128         initiator.node.create_channel(receiver.node.get_our_node_id(), 100_000, 10_001, 42, initiator_config).unwrap();
1129         let open_channel = get_event_msg!(initiator, MessageSendEvent::SendOpenChannel, receiver.node.get_our_node_id());
1130
1131         receiver.node.handle_open_channel(&initiator.node.get_our_node_id(), &open_channel);
1132         let events = receiver.node.get_and_clear_pending_events();
1133         assert_eq!(events.len(), 1);
1134         match events[0] {
1135                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
1136                         receiver.node.accept_inbound_channel_from_trusted_peer_0conf(&temporary_channel_id, &initiator.node.get_our_node_id(), 0).unwrap();
1137                 },
1138                 _ => panic!("Unexpected event"),
1139         };
1140
1141         let accept_channel = get_event_msg!(receiver, MessageSendEvent::SendAcceptChannel, initiator.node.get_our_node_id());
1142         assert_eq!(accept_channel.minimum_depth, 0);
1143         initiator.node.handle_accept_channel(&receiver.node.get_our_node_id(), &accept_channel);
1144
1145         let (temporary_channel_id, tx, _) = create_funding_transaction(&initiator, &receiver.node.get_our_node_id(), 100_000, 42);
1146         initiator.node.funding_transaction_generated(&temporary_channel_id, &receiver.node.get_our_node_id(), tx.clone()).unwrap();
1147         let funding_created = get_event_msg!(initiator, MessageSendEvent::SendFundingCreated, receiver.node.get_our_node_id());
1148
1149         receiver.node.handle_funding_created(&initiator.node.get_our_node_id(), &funding_created);
1150         check_added_monitors!(receiver, 1);
1151         let bs_signed_locked = receiver.node.get_and_clear_pending_msg_events();
1152         assert_eq!(bs_signed_locked.len(), 2);
1153         let as_channel_ready;
1154         match &bs_signed_locked[0] {
1155                 MessageSendEvent::SendFundingSigned { node_id, msg } => {
1156                         assert_eq!(*node_id, initiator.node.get_our_node_id());
1157                         initiator.node.handle_funding_signed(&receiver.node.get_our_node_id(), &msg);
1158                         expect_channel_pending_event(&initiator, &receiver.node.get_our_node_id());
1159                         expect_channel_pending_event(&receiver, &initiator.node.get_our_node_id());
1160                         check_added_monitors!(initiator, 1);
1161
1162                         assert_eq!(initiator.tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1163                         assert_eq!(initiator.tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0)[0], tx);
1164
1165                         as_channel_ready = get_event_msg!(initiator, MessageSendEvent::SendChannelReady, receiver.node.get_our_node_id());
1166                 }
1167                 _ => panic!("Unexpected event"),
1168         }
1169         match &bs_signed_locked[1] {
1170                 MessageSendEvent::SendChannelReady { node_id, msg } => {
1171                         assert_eq!(*node_id, initiator.node.get_our_node_id());
1172                         initiator.node.handle_channel_ready(&receiver.node.get_our_node_id(), &msg);
1173                         expect_channel_ready_event(&initiator, &receiver.node.get_our_node_id());
1174                 }
1175                 _ => panic!("Unexpected event"),
1176         }
1177
1178         receiver.node.handle_channel_ready(&initiator.node.get_our_node_id(), &as_channel_ready);
1179         expect_channel_ready_event(&receiver, &initiator.node.get_our_node_id());
1180
1181         let as_channel_update = get_event_msg!(initiator, MessageSendEvent::SendChannelUpdate, receiver.node.get_our_node_id());
1182         let bs_channel_update = get_event_msg!(receiver, MessageSendEvent::SendChannelUpdate, initiator.node.get_our_node_id());
1183
1184         initiator.node.handle_channel_update(&receiver.node.get_our_node_id(), &bs_channel_update);
1185         receiver.node.handle_channel_update(&initiator.node.get_our_node_id(), &as_channel_update);
1186
1187         assert_eq!(initiator.node.list_usable_channels().len(), initiator_channels + 1);
1188         assert_eq!(receiver.node.list_usable_channels().len(), receiver_channels + 1);
1189
1190         (tx, as_channel_ready.channel_id)
1191 }
1192
1193 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) -> Transaction {
1194         let create_chan_id = node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
1195         let open_channel_msg = get_event_msg!(node_a, MessageSendEvent::SendOpenChannel, node_b.node.get_our_node_id());
1196         assert_eq!(open_channel_msg.temporary_channel_id, create_chan_id);
1197         assert_eq!(node_a.node.list_channels().iter().find(|channel| channel.channel_id == create_chan_id).unwrap().user_channel_id, 42);
1198         node_b.node.handle_open_channel(&node_a.node.get_our_node_id(), &open_channel_msg);
1199         if node_b.node.get_current_default_configuration().manually_accept_inbound_channels {
1200                 let events = node_b.node.get_and_clear_pending_events();
1201                 assert_eq!(events.len(), 1);
1202                 match &events[0] {
1203                         Event::OpenChannelRequest { temporary_channel_id, counterparty_node_id, .. } =>
1204                                 node_b.node.accept_inbound_channel(temporary_channel_id, counterparty_node_id, 42).unwrap(),
1205                         _ => panic!("Unexpected event"),
1206                 };
1207         }
1208         let accept_channel_msg = get_event_msg!(node_b, MessageSendEvent::SendAcceptChannel, node_a.node.get_our_node_id());
1209         assert_eq!(accept_channel_msg.temporary_channel_id, create_chan_id);
1210         node_a.node.handle_accept_channel(&node_b.node.get_our_node_id(), &accept_channel_msg);
1211         assert_ne!(node_b.node.list_channels().iter().find(|channel| channel.channel_id == create_chan_id).unwrap().user_channel_id, 0);
1212
1213         sign_funding_transaction(node_a, node_b, channel_value, create_chan_id)
1214 }
1215
1216 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) {
1217         confirm_transaction_at(node_conf, tx, conf_height);
1218         connect_blocks(node_conf, CHAN_CONFIRM_DEPTH - 1);
1219         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()));
1220 }
1221
1222 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), ChannelId) {
1223         let channel_id;
1224         let events_6 = node_conf.node.get_and_clear_pending_msg_events();
1225         assert_eq!(events_6.len(), 3);
1226         let announcement_sigs_idx = if let MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } = events_6[1] {
1227                 assert_eq!(*node_id, node_recv.node.get_our_node_id());
1228                 2
1229         } else if let MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } = events_6[2] {
1230                 assert_eq!(*node_id, node_recv.node.get_our_node_id());
1231                 1
1232         } else { panic!("Unexpected event: {:?}", events_6[1]); };
1233         ((match events_6[0] {
1234                 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
1235                         channel_id = msg.channel_id.clone();
1236                         assert_eq!(*node_id, node_recv.node.get_our_node_id());
1237                         msg.clone()
1238                 },
1239                 _ => panic!("Unexpected event"),
1240         }, match events_6[announcement_sigs_idx] {
1241                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
1242                         assert_eq!(*node_id, node_recv.node.get_our_node_id());
1243                         msg.clone()
1244                 },
1245                 _ => panic!("Unexpected event"),
1246         }), channel_id)
1247 }
1248
1249 pub fn create_chan_between_nodes_with_value_confirm<'a, 'b, 'c: 'd, 'd>(node_a: &'a Node<'b, 'c, 'd>, node_b: &'a Node<'b, 'c, 'd>, tx: &Transaction) -> ((msgs::ChannelReady, msgs::AnnouncementSignatures), ChannelId) {
1250         let conf_height = core::cmp::max(node_a.best_block_info().1 + 1, node_b.best_block_info().1 + 1);
1251         create_chan_between_nodes_with_value_confirm_first(node_a, node_b, tx, conf_height);
1252         confirm_transaction_at(node_a, tx, conf_height);
1253         connect_blocks(node_a, CHAN_CONFIRM_DEPTH - 1);
1254         expect_channel_ready_event(&node_a, &node_b.node.get_our_node_id());
1255         create_chan_between_nodes_with_value_confirm_second(node_b, node_a)
1256 }
1257
1258 pub fn create_chan_between_nodes_with_value_a<'a, 'b, 'c: 'd, 'd>(node_a: &'a Node<'b, 'c, 'd>, node_b: &'a Node<'b, 'c, 'd>, channel_value: u64, push_msat: u64) -> ((msgs::ChannelReady, msgs::AnnouncementSignatures), ChannelId, Transaction) {
1259         let tx = create_chan_between_nodes_with_value_init(node_a, node_b, channel_value, push_msat);
1260         let (msgs, chan_id) = create_chan_between_nodes_with_value_confirm(node_a, node_b, &tx);
1261         (msgs, chan_id, tx)
1262 }
1263
1264 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) {
1265         node_b.node.handle_channel_ready(&node_a.node.get_our_node_id(), &as_funding_msgs.0);
1266         let bs_announcement_sigs = get_event_msg!(node_b, MessageSendEvent::SendAnnouncementSignatures, node_a.node.get_our_node_id());
1267         node_b.node.handle_announcement_signatures(&node_a.node.get_our_node_id(), &as_funding_msgs.1);
1268
1269         let events_7 = node_b.node.get_and_clear_pending_msg_events();
1270         assert_eq!(events_7.len(), 1);
1271         let (announcement, bs_update) = match events_7[0] {
1272                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
1273                         (msg, update_msg.clone().unwrap())
1274                 },
1275                 _ => panic!("Unexpected event"),
1276         };
1277
1278         node_a.node.handle_announcement_signatures(&node_b.node.get_our_node_id(), &bs_announcement_sigs);
1279         let events_8 = node_a.node.get_and_clear_pending_msg_events();
1280         assert_eq!(events_8.len(), 1);
1281         let as_update = match events_8[0] {
1282                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
1283                         assert!(*announcement == *msg);
1284                         let update_msg = update_msg.clone().unwrap();
1285                         assert_eq!(update_msg.contents.short_channel_id, announcement.contents.short_channel_id);
1286                         assert_eq!(update_msg.contents.short_channel_id, bs_update.contents.short_channel_id);
1287                         update_msg
1288                 },
1289                 _ => panic!("Unexpected event"),
1290         };
1291
1292         *node_a.network_chan_count.borrow_mut() += 1;
1293
1294         expect_channel_ready_event(&node_b, &node_a.node.get_our_node_id());
1295         ((*announcement).clone(), as_update, bs_update)
1296 }
1297
1298 pub fn create_announced_chan_between_nodes<'a, 'b, 'c: 'd, 'd>(nodes: &'a Vec<Node<'b, 'c, 'd>>, a: usize, b: usize) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, ChannelId, Transaction) {
1299         create_announced_chan_between_nodes_with_value(nodes, a, b, 100000, 10001)
1300 }
1301
1302 pub fn create_announced_chan_between_nodes_with_value<'a, 'b, 'c: 'd, 'd>(nodes: &'a Vec<Node<'b, 'c, 'd>>, a: usize, b: usize, channel_value: u64, push_msat: u64) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, ChannelId, Transaction) {
1303         let chan_announcement = create_chan_between_nodes_with_value(&nodes[a], &nodes[b], channel_value, push_msat);
1304         update_nodes_with_chan_announce(nodes, a, b, &chan_announcement.0, &chan_announcement.1, &chan_announcement.2);
1305         (chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
1306 }
1307
1308 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) -> (msgs::ChannelReady, Transaction) {
1309         let mut no_announce_cfg = test_default_channel_config();
1310         no_announce_cfg.channel_handshake_config.announced_channel = false;
1311         nodes[a].node.create_channel(nodes[b].node.get_our_node_id(), channel_value, push_msat, 42, Some(no_announce_cfg)).unwrap();
1312         let open_channel = get_event_msg!(nodes[a], MessageSendEvent::SendOpenChannel, nodes[b].node.get_our_node_id());
1313         nodes[b].node.handle_open_channel(&nodes[a].node.get_our_node_id(), &open_channel);
1314         let accept_channel = get_event_msg!(nodes[b], MessageSendEvent::SendAcceptChannel, nodes[a].node.get_our_node_id());
1315         nodes[a].node.handle_accept_channel(&nodes[b].node.get_our_node_id(), &accept_channel);
1316
1317         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[a], &nodes[b].node.get_our_node_id(), channel_value, 42);
1318         nodes[a].node.funding_transaction_generated(&temporary_channel_id, &nodes[b].node.get_our_node_id(), tx.clone()).unwrap();
1319         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()));
1320         check_added_monitors!(nodes[b], 1);
1321
1322         let cs_funding_signed = get_event_msg!(nodes[b], MessageSendEvent::SendFundingSigned, nodes[a].node.get_our_node_id());
1323         expect_channel_pending_event(&nodes[b], &nodes[a].node.get_our_node_id());
1324
1325         nodes[a].node.handle_funding_signed(&nodes[b].node.get_our_node_id(), &cs_funding_signed);
1326         expect_channel_pending_event(&nodes[a], &nodes[b].node.get_our_node_id());
1327         check_added_monitors!(nodes[a], 1);
1328
1329         assert_eq!(nodes[a].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1330         assert_eq!(nodes[a].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
1331         nodes[a].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1332
1333         let conf_height = core::cmp::max(nodes[a].best_block_info().1 + 1, nodes[b].best_block_info().1 + 1);
1334         confirm_transaction_at(&nodes[a], &tx, conf_height);
1335         connect_blocks(&nodes[a], CHAN_CONFIRM_DEPTH - 1);
1336         confirm_transaction_at(&nodes[b], &tx, conf_height);
1337         connect_blocks(&nodes[b], CHAN_CONFIRM_DEPTH - 1);
1338         let as_channel_ready = get_event_msg!(nodes[a], MessageSendEvent::SendChannelReady, nodes[b].node.get_our_node_id());
1339         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()));
1340         expect_channel_ready_event(&nodes[a], &nodes[b].node.get_our_node_id());
1341         let as_update = get_event_msg!(nodes[a], MessageSendEvent::SendChannelUpdate, nodes[b].node.get_our_node_id());
1342         nodes[b].node.handle_channel_ready(&nodes[a].node.get_our_node_id(), &as_channel_ready);
1343         expect_channel_ready_event(&nodes[b], &nodes[a].node.get_our_node_id());
1344         let bs_update = get_event_msg!(nodes[b], MessageSendEvent::SendChannelUpdate, nodes[a].node.get_our_node_id());
1345
1346         nodes[a].node.handle_channel_update(&nodes[b].node.get_our_node_id(), &bs_update);
1347         nodes[b].node.handle_channel_update(&nodes[a].node.get_our_node_id(), &as_update);
1348
1349         let mut found_a = false;
1350         for chan in nodes[a].node.list_usable_channels() {
1351                 if chan.channel_id == as_channel_ready.channel_id {
1352                         assert!(!found_a);
1353                         found_a = true;
1354                         assert!(!chan.is_public);
1355                 }
1356         }
1357         assert!(found_a);
1358
1359         let mut found_b = false;
1360         for chan in nodes[b].node.list_usable_channels() {
1361                 if chan.channel_id == as_channel_ready.channel_id {
1362                         assert!(!found_b);
1363                         found_b = true;
1364                         assert!(!chan.is_public);
1365                 }
1366         }
1367         assert!(found_b);
1368
1369         (as_channel_ready, tx)
1370 }
1371
1372 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) {
1373         for node in nodes {
1374                 assert!(node.gossip_sync.handle_channel_announcement(ann).unwrap());
1375                 node.gossip_sync.handle_channel_update(upd_1).unwrap();
1376                 node.gossip_sync.handle_channel_update(upd_2).unwrap();
1377
1378                 // Note that channel_updates are also delivered to ChannelManagers to ensure we have
1379                 // forwarding info for local channels even if its not accepted in the network graph.
1380                 node.node.handle_channel_update(&nodes[a].node.get_our_node_id(), &upd_1);
1381                 node.node.handle_channel_update(&nodes[b].node.get_our_node_id(), &upd_2);
1382         }
1383 }
1384
1385 pub fn do_check_spends<F: Fn(&bitcoin::blockdata::transaction::OutPoint) -> Option<TxOut>>(tx: &Transaction, get_output: F) {
1386         for outp in tx.output.iter() {
1387                 assert!(outp.value >= outp.script_pubkey.dust_value().to_sat(), "Spending tx output didn't meet dust limit");
1388         }
1389         let mut total_value_in = 0;
1390         for input in tx.input.iter() {
1391                 total_value_in += get_output(&input.previous_output).unwrap().value;
1392         }
1393         let mut total_value_out = 0;
1394         for output in tx.output.iter() {
1395                 total_value_out += output.value;
1396         }
1397         let min_fee = (tx.weight() as u64 + 3) / 4; // One sat per vbyte (ie per weight/4, rounded up)
1398         // Input amount - output amount = fee, so check that out + min_fee is smaller than input
1399         assert!(total_value_out + min_fee <= total_value_in);
1400         tx.verify(get_output).unwrap();
1401 }
1402
1403 #[macro_export]
1404 macro_rules! check_spends {
1405         ($tx: expr, $($spends_txn: expr),*) => {
1406                 {
1407                         $(
1408                         for outp in $spends_txn.output.iter() {
1409                                 assert!(outp.value >= outp.script_pubkey.dust_value().to_sat(), "Input tx output didn't meet dust limit");
1410                         }
1411                         )*
1412                         let get_output = |out_point: &bitcoin::blockdata::transaction::OutPoint| {
1413                                 $(
1414                                         if out_point.txid == $spends_txn.txid() {
1415                                                 return $spends_txn.output.get(out_point.vout as usize).cloned()
1416                                         }
1417                                 )*
1418                                 None
1419                         };
1420                         $crate::ln::functional_test_utils::do_check_spends(&$tx, get_output);
1421                 }
1422         }
1423 }
1424
1425 macro_rules! get_closing_signed_broadcast {
1426         ($node: expr, $dest_pubkey: expr) => {
1427                 {
1428                         let events = $node.get_and_clear_pending_msg_events();
1429                         assert!(events.len() == 1 || events.len() == 2);
1430                         (match events[events.len() - 1] {
1431                                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
1432                                         assert_eq!(msg.contents.flags & 2, 2);
1433                                         msg.clone()
1434                                 },
1435                                 _ => panic!("Unexpected event"),
1436                         }, if events.len() == 2 {
1437                                 match events[0] {
1438                                         MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
1439                                                 assert_eq!(*node_id, $dest_pubkey);
1440                                                 Some(msg.clone())
1441                                         },
1442                                         _ => panic!("Unexpected event"),
1443                                 }
1444                         } else { None })
1445                 }
1446         }
1447 }
1448
1449 #[cfg(test)]
1450 macro_rules! check_warn_msg {
1451         ($node: expr, $recipient_node_id: expr, $chan_id: expr) => {{
1452                 let msg_events = $node.node.get_and_clear_pending_msg_events();
1453                 assert_eq!(msg_events.len(), 1);
1454                 match msg_events[0] {
1455                         MessageSendEvent::HandleError { action: ErrorAction::SendWarningMessage { ref msg, log_level: _ }, node_id } => {
1456                                 assert_eq!(node_id, $recipient_node_id);
1457                                 assert_eq!(msg.channel_id, $chan_id);
1458                                 msg.data.clone()
1459                         },
1460                         _ => panic!("Unexpected event"),
1461                 }
1462         }}
1463 }
1464
1465 /// Check that a channel's closing channel update has been broadcasted, and optionally
1466 /// check whether an error message event has occurred.
1467 pub fn check_closed_broadcast(node: &Node, num_channels: usize, with_error_msg: bool) -> Vec<msgs::ErrorMessage> {
1468         let msg_events = node.node.get_and_clear_pending_msg_events();
1469         assert_eq!(msg_events.len(), if with_error_msg { num_channels * 2 } else { num_channels });
1470         msg_events.into_iter().filter_map(|msg_event| {
1471                 match msg_event {
1472                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
1473                                 assert_eq!(msg.contents.flags & 2, 2);
1474                                 None
1475                         },
1476                         MessageSendEvent::HandleError { action: msgs::ErrorAction::SendErrorMessage { msg }, node_id: _ } => {
1477                                 assert!(with_error_msg);
1478                                 // TODO: Check node_id
1479                                 Some(msg)
1480                         },
1481                         MessageSendEvent::HandleError { action: msgs::ErrorAction::DisconnectPeer { msg }, node_id: _ } => {
1482                                 assert!(with_error_msg);
1483                                 // TODO: Check node_id
1484                                 Some(msg.unwrap())
1485                         },
1486                         _ => panic!("Unexpected event"),
1487                 }
1488         }).collect()
1489 }
1490
1491 /// Check that a channel's closing channel update has been broadcasted, and optionally
1492 /// check whether an error message event has occurred.
1493 ///
1494 /// Don't use this, use the identically-named function instead.
1495 #[macro_export]
1496 macro_rules! check_closed_broadcast {
1497         ($node: expr, $with_error_msg: expr) => {
1498                 $crate::ln::functional_test_utils::check_closed_broadcast(&$node, 1, $with_error_msg).pop()
1499         }
1500 }
1501
1502 /// Check that a channel's closing channel events has been issued
1503 pub fn check_closed_event(node: &Node, events_count: usize, expected_reason: ClosureReason, is_check_discard_funding: bool,
1504         expected_counterparty_node_ids: &[PublicKey], expected_channel_capacity: u64) {
1505         let events = node.node.get_and_clear_pending_events();
1506         assert_eq!(events.len(), events_count, "{:?}", events);
1507         let mut issues_discard_funding = false;
1508         for event in events {
1509                 match event {
1510                         Event::ChannelClosed { ref reason, counterparty_node_id,
1511                                 channel_capacity_sats, .. } => {
1512                                 assert_eq!(*reason, expected_reason);
1513                                 assert!(expected_counterparty_node_ids.iter().any(|id| id == &counterparty_node_id.unwrap()));
1514                                 assert_eq!(channel_capacity_sats.unwrap(), expected_channel_capacity);
1515                         },
1516                         Event::DiscardFunding { .. } => {
1517                                 issues_discard_funding = true;
1518                         }
1519                         _ => panic!("Unexpected event"),
1520                 }
1521         }
1522         assert_eq!(is_check_discard_funding, issues_discard_funding);
1523 }
1524
1525 /// Check that a channel's closing channel events has been issued
1526 ///
1527 /// Don't use this, use the identically-named function instead.
1528 #[macro_export]
1529 macro_rules! check_closed_event {
1530         ($node: expr, $events: expr, $reason: expr, $counterparty_node_ids: expr, $channel_capacity: expr) => {
1531                 check_closed_event!($node, $events, $reason, false, $counterparty_node_ids, $channel_capacity);
1532         };
1533         ($node: expr, $events: expr, $reason: expr, $is_check_discard_funding: expr, $counterparty_node_ids: expr, $channel_capacity: expr) => {
1534                 $crate::ln::functional_test_utils::check_closed_event(&$node, $events, $reason,
1535                         $is_check_discard_funding, &$counterparty_node_ids, $channel_capacity);
1536         }
1537 }
1538
1539 pub fn handle_bump_htlc_event(node: &Node, count: usize) {
1540         let events = node.chain_monitor.chain_monitor.get_and_clear_pending_events();
1541         assert_eq!(events.len(), count);
1542         for event in events {
1543                 match event {
1544                         Event::BumpTransaction(bump_event) => {
1545                                 if let BumpTransactionEvent::HTLCResolution { .. } = &bump_event {}
1546                                 else { panic!(); }
1547                                 node.bump_tx_handler.handle_event(&bump_event);
1548                         },
1549                         _ => panic!(),
1550                 }
1551         }
1552 }
1553
1554 pub fn close_channel<'a, 'b, 'c>(outbound_node: &Node<'a, 'b, 'c>, inbound_node: &Node<'a, 'b, 'c>, channel_id: &ChannelId, funding_tx: Transaction, close_inbound_first: bool) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, Transaction) {
1555         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) };
1556         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) };
1557         let (tx_a, tx_b);
1558
1559         node_a.close_channel(channel_id, &node_b.get_our_node_id()).unwrap();
1560         node_b.handle_shutdown(&node_a.get_our_node_id(), &get_event_msg!(struct_a, MessageSendEvent::SendShutdown, node_b.get_our_node_id()));
1561
1562         let events_1 = node_b.get_and_clear_pending_msg_events();
1563         assert!(events_1.len() >= 1);
1564         let shutdown_b = match events_1[0] {
1565                 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
1566                         assert_eq!(node_id, &node_a.get_our_node_id());
1567                         msg.clone()
1568                 },
1569                 _ => panic!("Unexpected event"),
1570         };
1571
1572         let closing_signed_b = if !close_inbound_first {
1573                 assert_eq!(events_1.len(), 1);
1574                 None
1575         } else {
1576                 Some(match events_1[1] {
1577                         MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
1578                                 assert_eq!(node_id, &node_a.get_our_node_id());
1579                                 msg.clone()
1580                         },
1581                         _ => panic!("Unexpected event"),
1582                 })
1583         };
1584
1585         node_a.handle_shutdown(&node_b.get_our_node_id(), &shutdown_b);
1586         let (as_update, bs_update) = if close_inbound_first {
1587                 assert!(node_a.get_and_clear_pending_msg_events().is_empty());
1588                 node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap());
1589
1590                 node_b.handle_closing_signed(&node_a.get_our_node_id(), &get_event_msg!(struct_a, MessageSendEvent::SendClosingSigned, node_b.get_our_node_id()));
1591                 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
1592                 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
1593                 let (bs_update, closing_signed_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
1594
1595                 node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap());
1596                 let (as_update, none_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
1597                 assert!(none_a.is_none());
1598                 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
1599                 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
1600                 (as_update, bs_update)
1601         } else {
1602                 let closing_signed_a = get_event_msg!(struct_a, MessageSendEvent::SendClosingSigned, node_b.get_our_node_id());
1603
1604                 node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a);
1605                 node_a.handle_closing_signed(&node_b.get_our_node_id(), &get_event_msg!(struct_b, MessageSendEvent::SendClosingSigned, node_a.get_our_node_id()));
1606
1607                 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
1608                 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
1609                 let (as_update, closing_signed_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
1610
1611                 node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap());
1612                 let (bs_update, none_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
1613                 assert!(none_b.is_none());
1614                 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
1615                 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
1616                 (as_update, bs_update)
1617         };
1618         assert_eq!(tx_a, tx_b);
1619         check_spends!(tx_a, funding_tx);
1620
1621         (as_update, bs_update, tx_a)
1622 }
1623
1624 pub struct SendEvent {
1625         pub node_id: PublicKey,
1626         pub msgs: Vec<msgs::UpdateAddHTLC>,
1627         pub commitment_msg: msgs::CommitmentSigned,
1628 }
1629 impl SendEvent {
1630         pub fn from_commitment_update(node_id: PublicKey, updates: msgs::CommitmentUpdate) -> SendEvent {
1631                 assert!(updates.update_fulfill_htlcs.is_empty());
1632                 assert!(updates.update_fail_htlcs.is_empty());
1633                 assert!(updates.update_fail_malformed_htlcs.is_empty());
1634                 assert!(updates.update_fee.is_none());
1635                 SendEvent { node_id, msgs: updates.update_add_htlcs, commitment_msg: updates.commitment_signed }
1636         }
1637
1638         pub fn from_event(event: MessageSendEvent) -> SendEvent {
1639                 match event {
1640                         MessageSendEvent::UpdateHTLCs { node_id, updates } => SendEvent::from_commitment_update(node_id, updates),
1641                         _ => panic!("Unexpected event type!"),
1642                 }
1643         }
1644
1645         pub fn from_node<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>) -> SendEvent {
1646                 let mut events = node.node.get_and_clear_pending_msg_events();
1647                 assert_eq!(events.len(), 1);
1648                 SendEvent::from_event(events.pop().unwrap())
1649         }
1650 }
1651
1652 #[macro_export]
1653 /// Don't use this, use the identically-named function instead.
1654 macro_rules! expect_pending_htlcs_forwardable_conditions {
1655         ($node: expr, $expected_failures: expr) => {
1656                 $crate::ln::functional_test_utils::expect_pending_htlcs_forwardable_conditions($node.node.get_and_clear_pending_events(), &$expected_failures);
1657         }
1658 }
1659
1660 #[macro_export]
1661 macro_rules! expect_htlc_handling_failed_destinations {
1662         ($events: expr, $expected_failures: expr) => {{
1663                 for event in $events {
1664                         match event {
1665                                 $crate::events::Event::PendingHTLCsForwardable { .. } => { },
1666                                 $crate::events::Event::HTLCHandlingFailed { ref failed_next_destination, .. } => {
1667                                         assert!($expected_failures.contains(&failed_next_destination))
1668                                 },
1669                                 _ => panic!("Unexpected destination"),
1670                         }
1671                 }
1672         }}
1673 }
1674
1675 /// Checks that an [`Event::PendingHTLCsForwardable`] is available in the given events and, if
1676 /// there are any [`Event::HTLCHandlingFailed`] events their [`HTLCDestination`] is included in the
1677 /// `expected_failures` set.
1678 pub fn expect_pending_htlcs_forwardable_conditions(events: Vec<Event>, expected_failures: &[HTLCDestination]) {
1679         match events[0] {
1680                 Event::PendingHTLCsForwardable { .. } => { },
1681                 _ => panic!("Unexpected event {:?}", events),
1682         };
1683
1684         let count = expected_failures.len() + 1;
1685         assert_eq!(events.len(), count);
1686
1687         if expected_failures.len() > 0 {
1688                 expect_htlc_handling_failed_destinations!(events, expected_failures)
1689         }
1690 }
1691
1692 #[macro_export]
1693 /// Clears (and ignores) a PendingHTLCsForwardable event
1694 ///
1695 /// Don't use this, call [`expect_pending_htlcs_forwardable_conditions()`] with an empty failure
1696 /// set instead.
1697 macro_rules! expect_pending_htlcs_forwardable_ignore {
1698         ($node: expr) => {
1699                 $crate::ln::functional_test_utils::expect_pending_htlcs_forwardable_conditions($node.node.get_and_clear_pending_events(), &[]);
1700         }
1701 }
1702
1703 #[macro_export]
1704 /// Clears (and ignores) PendingHTLCsForwardable and HTLCHandlingFailed events
1705 ///
1706 /// Don't use this, call [`expect_pending_htlcs_forwardable_conditions()`] instead.
1707 macro_rules! expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore {
1708         ($node: expr, $expected_failures: expr) => {
1709                 $crate::ln::functional_test_utils::expect_pending_htlcs_forwardable_conditions($node.node.get_and_clear_pending_events(), &$expected_failures);
1710         }
1711 }
1712
1713 #[macro_export]
1714 /// Handles a PendingHTLCsForwardable event
1715 macro_rules! expect_pending_htlcs_forwardable {
1716         ($node: expr) => {{
1717                 $crate::ln::functional_test_utils::expect_pending_htlcs_forwardable_conditions($node.node.get_and_clear_pending_events(), &[]);
1718                 $node.node.process_pending_htlc_forwards();
1719
1720                 // Ensure process_pending_htlc_forwards is idempotent.
1721                 $node.node.process_pending_htlc_forwards();
1722         }};
1723 }
1724
1725 #[macro_export]
1726 /// Handles a PendingHTLCsForwardable and HTLCHandlingFailed event
1727 macro_rules! expect_pending_htlcs_forwardable_and_htlc_handling_failed {
1728         ($node: expr, $expected_failures: expr) => {{
1729                 $crate::ln::functional_test_utils::expect_pending_htlcs_forwardable_conditions($node.node.get_and_clear_pending_events(), &$expected_failures);
1730                 $node.node.process_pending_htlc_forwards();
1731
1732                 // Ensure process_pending_htlc_forwards is idempotent.
1733                 $node.node.process_pending_htlc_forwards();
1734         }}
1735 }
1736
1737 #[cfg(test)]
1738 macro_rules! expect_pending_htlcs_forwardable_from_events {
1739         ($node: expr, $events: expr, $ignore: expr) => {{
1740                 assert_eq!($events.len(), 1);
1741                 match $events[0] {
1742                         Event::PendingHTLCsForwardable { .. } => { },
1743                         _ => panic!("Unexpected event"),
1744                 };
1745                 if $ignore {
1746                         $node.node.process_pending_htlc_forwards();
1747
1748                         // Ensure process_pending_htlc_forwards is idempotent.
1749                         $node.node.process_pending_htlc_forwards();
1750                 }
1751         }}
1752 }
1753
1754 #[macro_export]
1755 /// Performs the "commitment signed dance" - the series of message exchanges which occur after a
1756 /// commitment update.
1757 macro_rules! commitment_signed_dance {
1758         ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */) => {
1759                 $crate::ln::functional_test_utils::do_commitment_signed_dance(&$node_a, &$node_b, &$commitment_signed, $fail_backwards, true);
1760         };
1761         ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */, true /* return last RAA */) => {
1762                 $crate::ln::functional_test_utils::do_main_commitment_signed_dance(&$node_a, &$node_b, $fail_backwards)
1763         };
1764         ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */, false /* return extra message */, true /* return last RAA */) => {
1765                 {
1766                         $crate::ln::functional_test_utils::check_added_monitors(&$node_a, 0);
1767                         assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
1768                         $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed);
1769                         check_added_monitors(&$node_a, 1);
1770                         let (extra_msg_option, bs_revoke_and_ack) = $crate::ln::functional_test_utils::do_main_commitment_signed_dance(&$node_a, &$node_b, $fail_backwards);
1771                         assert!(extra_msg_option.is_none());
1772                         bs_revoke_and_ack
1773                 }
1774         };
1775         ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, false /* no extra message */, $incl_claim: expr) => {
1776                 assert!($crate::ln::functional_test_utils::commitment_signed_dance_through_cp_raa(&$node_a, &$node_b, $fail_backwards, $incl_claim).is_none());
1777         };
1778         ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr) => {
1779                 $crate::ln::functional_test_utils::do_commitment_signed_dance(&$node_a, &$node_b, &$commitment_signed, $fail_backwards, false);
1780         }
1781 }
1782
1783 /// Runs the commitment_signed dance after the initial commitment_signed is delivered through to
1784 /// the initiator's `revoke_and_ack` response. i.e. [`do_main_commitment_signed_dance`] plus the
1785 /// `revoke_and_ack` response to it.
1786 ///
1787 /// An HTLC claim on one channel blocks the RAA channel monitor update for the outbound edge
1788 /// channel until the inbound edge channel preimage monitor update completes. Thus, when checking
1789 /// for channel monitor updates, we need to know if an `update_fulfill_htlc` was included in the
1790 /// the commitment we're exchanging. `includes_claim` provides that information.
1791 ///
1792 /// Returns any additional message `node_b` generated in addition to the `revoke_and_ack` response.
1793 pub fn commitment_signed_dance_through_cp_raa(node_a: &Node<'_, '_, '_>, node_b: &Node<'_, '_, '_>, fail_backwards: bool, includes_claim: bool) -> Option<MessageSendEvent> {
1794         let (extra_msg_option, bs_revoke_and_ack) = do_main_commitment_signed_dance(node_a, node_b, fail_backwards);
1795         node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &bs_revoke_and_ack);
1796         check_added_monitors(node_a, if includes_claim { 0 } else { 1 });
1797         extra_msg_option
1798 }
1799
1800 /// Does the main logic in the commitment_signed dance. After the first `commitment_signed` has
1801 /// been delivered, this method picks up and delivers the response `revoke_and_ack` and
1802 /// `commitment_signed`, returning the recipient's `revoke_and_ack` and any extra message it may
1803 /// have included.
1804 pub fn do_main_commitment_signed_dance(node_a: &Node<'_, '_, '_>, node_b: &Node<'_, '_, '_>, fail_backwards: bool) -> (Option<MessageSendEvent>, msgs::RevokeAndACK) {
1805         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(node_a, node_b.node.get_our_node_id());
1806         check_added_monitors!(node_b, 0);
1807         assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
1808         node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &as_revoke_and_ack);
1809         assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
1810         check_added_monitors!(node_b, 1);
1811         node_b.node.handle_commitment_signed(&node_a.node.get_our_node_id(), &as_commitment_signed);
1812         let (bs_revoke_and_ack, extra_msg_option) = {
1813                 let mut events = node_b.node.get_and_clear_pending_msg_events();
1814                 assert!(events.len() <= 2);
1815                 let node_a_event = remove_first_msg_event_to_node(&node_a.node.get_our_node_id(), &mut events);
1816                 (match node_a_event {
1817                         MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
1818                                 assert_eq!(*node_id, node_a.node.get_our_node_id());
1819                                 (*msg).clone()
1820                         },
1821                         _ => panic!("Unexpected event"),
1822                 }, events.get(0).map(|e| e.clone()))
1823         };
1824         check_added_monitors!(node_b, 1);
1825         if fail_backwards {
1826                 assert!(node_a.node.get_and_clear_pending_events().is_empty());
1827                 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
1828         }
1829         (extra_msg_option, bs_revoke_and_ack)
1830 }
1831
1832 /// Runs a full commitment_signed dance, delivering a commitment_signed, the responding
1833 /// `revoke_and_ack` and `commitment_signed`, and then the final `revoke_and_ack` response.
1834 ///
1835 /// If `skip_last_step` is unset, also checks for the payment failure update for the previous hop
1836 /// on failure or that no new messages are left over on success.
1837 pub fn do_commitment_signed_dance(node_a: &Node<'_, '_, '_>, node_b: &Node<'_, '_, '_>, commitment_signed: &msgs::CommitmentSigned, fail_backwards: bool, skip_last_step: bool) {
1838         check_added_monitors!(node_a, 0);
1839         assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
1840         node_a.node.handle_commitment_signed(&node_b.node.get_our_node_id(), commitment_signed);
1841         check_added_monitors!(node_a, 1);
1842
1843         // If this commitment signed dance was due to a claim, don't check for an RAA monitor update.
1844         let got_claim = node_a.node.test_raa_monitor_updates_held(node_b.node.get_our_node_id(), commitment_signed.channel_id);
1845         if fail_backwards { assert!(!got_claim); }
1846         commitment_signed_dance!(node_a, node_b, (), fail_backwards, true, false, got_claim);
1847
1848         if skip_last_step { return; }
1849
1850         if fail_backwards {
1851                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(node_a,
1852                         vec![crate::events::HTLCDestination::NextHopChannel{ node_id: Some(node_b.node.get_our_node_id()), channel_id: commitment_signed.channel_id }]);
1853                 check_added_monitors!(node_a, 1);
1854
1855                 let node_a_per_peer_state = node_a.node.per_peer_state.read().unwrap();
1856                 let mut number_of_msg_events = 0;
1857                 for (cp_id, peer_state_mutex) in node_a_per_peer_state.iter() {
1858                         let peer_state = peer_state_mutex.lock().unwrap();
1859                         let cp_pending_msg_events = &peer_state.pending_msg_events;
1860                         number_of_msg_events += cp_pending_msg_events.len();
1861                         if cp_pending_msg_events.len() == 1 {
1862                                 if let MessageSendEvent::UpdateHTLCs { .. } = cp_pending_msg_events[0] {
1863                                         assert_ne!(*cp_id, node_b.node.get_our_node_id());
1864                                 } else { panic!("Unexpected event"); }
1865                         }
1866                 }
1867                 // Expecting the failure backwards event to the previous hop (not `node_b`)
1868                 assert_eq!(number_of_msg_events, 1);
1869         } else {
1870                 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
1871         }
1872 }
1873
1874 /// Get a payment preimage and hash.
1875 pub fn get_payment_preimage_hash(recipient: &Node, min_value_msat: Option<u64>, min_final_cltv_expiry_delta: Option<u16>) -> (PaymentPreimage, PaymentHash, PaymentSecret) {
1876         let mut payment_count = recipient.network_payment_count.borrow_mut();
1877         let payment_preimage = PaymentPreimage([*payment_count; 32]);
1878         *payment_count += 1;
1879         let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner());
1880         let payment_secret = recipient.node.create_inbound_payment_for_hash(payment_hash, min_value_msat, 7200, min_final_cltv_expiry_delta).unwrap();
1881         (payment_preimage, payment_hash, payment_secret)
1882 }
1883
1884 /// Get a payment preimage and hash.
1885 ///
1886 /// Don't use this, use the identically-named function instead.
1887 #[macro_export]
1888 macro_rules! get_payment_preimage_hash {
1889         ($dest_node: expr) => {
1890                 get_payment_preimage_hash!($dest_node, None)
1891         };
1892         ($dest_node: expr, $min_value_msat: expr) => {
1893                 crate::get_payment_preimage_hash!($dest_node, $min_value_msat, None)
1894         };
1895         ($dest_node: expr, $min_value_msat: expr, $min_final_cltv_expiry_delta: expr) => {
1896                 $crate::ln::functional_test_utils::get_payment_preimage_hash(&$dest_node, $min_value_msat, $min_final_cltv_expiry_delta)
1897         };
1898 }
1899
1900 /// Gets a route from the given sender to the node described in `payment_params`.
1901 pub fn get_route(send_node: &Node, route_params: &RouteParameters) -> Result<Route, msgs::LightningError> {
1902         let scorer = TestScorer::new();
1903         let keys_manager = TestKeysInterface::new(&[0u8; 32], bitcoin::network::constants::Network::Testnet);
1904         let random_seed_bytes = keys_manager.get_secure_random_bytes();
1905         router::get_route(
1906                 &send_node.node.get_our_node_id(), route_params, &send_node.network_graph.read_only(),
1907                 Some(&send_node.node.list_usable_channels().iter().collect::<Vec<_>>()),
1908                 send_node.logger, &scorer, &Default::default(), &random_seed_bytes
1909         )
1910 }
1911
1912 /// Gets a route from the given sender to the node described in `payment_params`.
1913 ///
1914 /// Don't use this, use the identically-named function instead.
1915 #[macro_export]
1916 macro_rules! get_route {
1917         ($send_node: expr, $payment_params: expr, $recv_value: expr) => {{
1918                 let route_params = $crate::routing::router::RouteParameters::from_payment_params_and_value($payment_params, $recv_value);
1919                 $crate::ln::functional_test_utils::get_route(&$send_node, &route_params)
1920         }}
1921 }
1922
1923 #[cfg(test)]
1924 #[macro_export]
1925 macro_rules! get_route_and_payment_hash {
1926         ($send_node: expr, $recv_node: expr, $recv_value: expr) => {{
1927                 let payment_params = $crate::routing::router::PaymentParameters::from_node_id($recv_node.node.get_our_node_id(), TEST_FINAL_CLTV)
1928                         .with_bolt11_features($recv_node.node.bolt11_invoice_features()).unwrap();
1929                 $crate::get_route_and_payment_hash!($send_node, $recv_node, payment_params, $recv_value)
1930         }};
1931         ($send_node: expr, $recv_node: expr, $payment_params: expr, $recv_value: expr) => {{
1932                 $crate::get_route_and_payment_hash!($send_node, $recv_node, $payment_params, $recv_value, None)
1933         }};
1934         ($send_node: expr, $recv_node: expr, $payment_params: expr, $recv_value: expr, $max_total_routing_fee_msat: expr) => {{
1935                 let mut route_params = $crate::routing::router::RouteParameters::from_payment_params_and_value($payment_params, $recv_value);
1936                 route_params.max_total_routing_fee_msat = $max_total_routing_fee_msat;
1937                 let (payment_preimage, payment_hash, payment_secret) =
1938                         $crate::ln::functional_test_utils::get_payment_preimage_hash(&$recv_node, Some($recv_value), None);
1939                 let route = $crate::ln::functional_test_utils::get_route(&$send_node, &route_params);
1940                 (route.unwrap(), payment_hash, payment_preimage, payment_secret)
1941         }}
1942 }
1943
1944 pub fn check_payment_claimable(
1945         event: &Event, expected_payment_hash: PaymentHash, expected_payment_secret: PaymentSecret,
1946         expected_recv_value: u64, expected_payment_preimage: Option<PaymentPreimage>,
1947         expected_receiver_node_id: PublicKey,
1948 ) {
1949         match event {
1950                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, .. } => {
1951                         assert_eq!(expected_payment_hash, *payment_hash);
1952                         assert_eq!(expected_recv_value, *amount_msat);
1953                         assert_eq!(expected_receiver_node_id, receiver_node_id.unwrap());
1954                         match purpose {
1955                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1956                                         assert_eq!(&expected_payment_preimage, payment_preimage);
1957                                         assert_eq!(expected_payment_secret, *payment_secret);
1958                                 },
1959                                 _ => {},
1960                         }
1961                 },
1962                 _ => panic!("Unexpected event"),
1963         }
1964 }
1965
1966 #[macro_export]
1967 #[cfg(any(test, ldk_bench, feature = "_test_utils"))]
1968 macro_rules! expect_payment_claimable {
1969         ($node: expr, $expected_payment_hash: expr, $expected_payment_secret: expr, $expected_recv_value: expr) => {
1970                 expect_payment_claimable!($node, $expected_payment_hash, $expected_payment_secret, $expected_recv_value, None, $node.node.get_our_node_id())
1971         };
1972         ($node: expr, $expected_payment_hash: expr, $expected_payment_secret: expr, $expected_recv_value: expr, $expected_payment_preimage: expr, $expected_receiver_node_id: expr) => {
1973                 let events = $node.node.get_and_clear_pending_events();
1974                 assert_eq!(events.len(), 1);
1975                 $crate::ln::functional_test_utils::check_payment_claimable(&events[0], $expected_payment_hash, $expected_payment_secret, $expected_recv_value, $expected_payment_preimage, $expected_receiver_node_id)
1976         };
1977 }
1978
1979 #[macro_export]
1980 #[cfg(any(test, ldk_bench, feature = "_test_utils"))]
1981 macro_rules! expect_payment_claimed {
1982         ($node: expr, $expected_payment_hash: expr, $expected_recv_value: expr) => {
1983                 let events = $node.node.get_and_clear_pending_events();
1984                 assert_eq!(events.len(), 1);
1985                 match events[0] {
1986                         $crate::events::Event::PaymentClaimed { ref payment_hash, amount_msat, .. } => {
1987                                 assert_eq!($expected_payment_hash, *payment_hash);
1988                                 assert_eq!($expected_recv_value, amount_msat);
1989                         },
1990                         _ => panic!("Unexpected event"),
1991                 }
1992         }
1993 }
1994
1995 pub fn expect_payment_sent<CM: AChannelManager, H: NodeHolder<CM=CM>>(node: &H,
1996         expected_payment_preimage: PaymentPreimage, expected_fee_msat_opt: Option<Option<u64>>,
1997         expect_per_path_claims: bool, expect_post_ev_mon_update: bool,
1998 ) {
1999         let events = node.node().get_and_clear_pending_events();
2000         let expected_payment_hash = PaymentHash(
2001                 bitcoin::hashes::sha256::Hash::hash(&expected_payment_preimage.0).into_inner());
2002         if expect_per_path_claims {
2003                 assert!(events.len() > 1);
2004         } else {
2005                 assert_eq!(events.len(), 1);
2006         }
2007         if expect_post_ev_mon_update {
2008                 check_added_monitors(node, 1);
2009         }
2010         let expected_payment_id = match events[0] {
2011                 Event::PaymentSent { ref payment_id, ref payment_preimage, ref payment_hash, ref fee_paid_msat } => {
2012                         assert_eq!(expected_payment_preimage, *payment_preimage);
2013                         assert_eq!(expected_payment_hash, *payment_hash);
2014                         if let Some(expected_fee_msat) = expected_fee_msat_opt {
2015                                 assert_eq!(*fee_paid_msat, expected_fee_msat);
2016                         } else {
2017                                 assert!(fee_paid_msat.is_some());
2018                         }
2019                         payment_id.unwrap()
2020                 },
2021                 _ => panic!("Unexpected event"),
2022         };
2023         if expect_per_path_claims {
2024                 for i in 1..events.len() {
2025                         match events[i] {
2026                                 Event::PaymentPathSuccessful { payment_id, payment_hash, .. } => {
2027                                         assert_eq!(payment_id, expected_payment_id);
2028                                         assert_eq!(payment_hash, Some(expected_payment_hash));
2029                                 },
2030                                 _ => panic!("Unexpected event"),
2031                         }
2032                 }
2033         }
2034 }
2035
2036 #[macro_export]
2037 macro_rules! expect_payment_sent {
2038         ($node: expr, $expected_payment_preimage: expr) => {
2039                 $crate::expect_payment_sent!($node, $expected_payment_preimage, None::<u64>, true);
2040         };
2041         ($node: expr, $expected_payment_preimage: expr, $expected_fee_msat_opt: expr) => {
2042                 $crate::expect_payment_sent!($node, $expected_payment_preimage, $expected_fee_msat_opt, true);
2043         };
2044         ($node: expr, $expected_payment_preimage: expr, $expected_fee_msat_opt: expr, $expect_paths: expr) => {
2045                 $crate::ln::functional_test_utils::expect_payment_sent(&$node, $expected_payment_preimage,
2046                         $expected_fee_msat_opt.map(|o| Some(o)), $expect_paths, true);
2047         }
2048 }
2049
2050 #[cfg(test)]
2051 #[macro_export]
2052 macro_rules! expect_payment_path_successful {
2053         ($node: expr) => {
2054                 let events = $node.node.get_and_clear_pending_events();
2055                 assert_eq!(events.len(), 1);
2056                 match events[0] {
2057                         $crate::events::Event::PaymentPathSuccessful { .. } => {},
2058                         _ => panic!("Unexpected event"),
2059                 }
2060         }
2061 }
2062
2063 pub fn expect_payment_forwarded<CM: AChannelManager, H: NodeHolder<CM=CM>>(
2064         event: Event, node: &H, prev_node: &H, next_node: &H, expected_fee: Option<u64>,
2065         upstream_force_closed: bool, downstream_force_closed: bool
2066 ) {
2067         match event {
2068                 Event::PaymentForwarded {
2069                         fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id,
2070                         outbound_amount_forwarded_msat: _
2071                 } => {
2072                         assert_eq!(fee_earned_msat, expected_fee);
2073                         if !upstream_force_closed {
2074                                 // Is the event prev_channel_id in one of the channels between the two nodes?
2075                                 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()));
2076                         }
2077                         // We check for force closures since a force closed channel is removed from the
2078                         // node's channel list
2079                         if !downstream_force_closed {
2080                                 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()));
2081                         }
2082                         assert_eq!(claim_from_onchain_tx, downstream_force_closed);
2083                 },
2084                 _ => panic!("Unexpected event"),
2085         }
2086 }
2087
2088 macro_rules! expect_payment_forwarded {
2089         ($node: expr, $prev_node: expr, $next_node: expr, $expected_fee: expr, $upstream_force_closed: expr, $downstream_force_closed: expr) => {
2090                 let mut events = $node.node.get_and_clear_pending_events();
2091                 assert_eq!(events.len(), 1);
2092                 $crate::ln::functional_test_utils::expect_payment_forwarded(
2093                         events.pop().unwrap(), &$node, &$prev_node, &$next_node, $expected_fee,
2094                         $upstream_force_closed, $downstream_force_closed);
2095         }
2096 }
2097
2098 #[cfg(test)]
2099 #[macro_export]
2100 macro_rules! expect_channel_shutdown_state {
2101         ($node: expr, $chan_id: expr, $state: path) => {
2102                 let chan_details = $node.node.list_channels().into_iter().filter(|cd| cd.channel_id == $chan_id).collect::<Vec<ChannelDetails>>();
2103                 assert_eq!(chan_details.len(), 1);
2104                 assert_eq!(chan_details[0].channel_shutdown_state, Some($state));
2105         }
2106 }
2107
2108 #[cfg(any(test, ldk_bench, feature = "_test_utils"))]
2109 pub fn expect_channel_pending_event<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, expected_counterparty_node_id: &PublicKey) {
2110         let events = node.node.get_and_clear_pending_events();
2111         assert_eq!(events.len(), 1);
2112         match events[0] {
2113                 crate::events::Event::ChannelPending { ref counterparty_node_id, .. } => {
2114                         assert_eq!(*expected_counterparty_node_id, *counterparty_node_id);
2115                 },
2116                 _ => panic!("Unexpected event"),
2117         }
2118 }
2119
2120 #[cfg(any(test, ldk_bench, feature = "_test_utils"))]
2121 pub fn expect_channel_ready_event<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, expected_counterparty_node_id: &PublicKey) {
2122         let events = node.node.get_and_clear_pending_events();
2123         assert_eq!(events.len(), 1);
2124         match events[0] {
2125                 crate::events::Event::ChannelReady{ ref counterparty_node_id, .. } => {
2126                         assert_eq!(*expected_counterparty_node_id, *counterparty_node_id);
2127                 },
2128                 _ => panic!("Unexpected event"),
2129         }
2130 }
2131
2132 pub struct PaymentFailedConditions<'a> {
2133         pub(crate) expected_htlc_error_data: Option<(u16, &'a [u8])>,
2134         pub(crate) expected_blamed_scid: Option<u64>,
2135         pub(crate) expected_blamed_chan_closed: Option<bool>,
2136         pub(crate) expected_mpp_parts_remain: bool,
2137 }
2138
2139 impl<'a> PaymentFailedConditions<'a> {
2140         pub fn new() -> Self {
2141                 Self {
2142                         expected_htlc_error_data: None,
2143                         expected_blamed_scid: None,
2144                         expected_blamed_chan_closed: None,
2145                         expected_mpp_parts_remain: false,
2146                 }
2147         }
2148         pub fn mpp_parts_remain(mut self) -> Self {
2149                 self.expected_mpp_parts_remain = true;
2150                 self
2151         }
2152         pub fn blamed_scid(mut self, scid: u64) -> Self {
2153                 self.expected_blamed_scid = Some(scid);
2154                 self
2155         }
2156         pub fn blamed_chan_closed(mut self, closed: bool) -> Self {
2157                 self.expected_blamed_chan_closed = Some(closed);
2158                 self
2159         }
2160         pub fn expected_htlc_error_data(mut self, code: u16, data: &'a [u8]) -> Self {
2161                 self.expected_htlc_error_data = Some((code, data));
2162                 self
2163         }
2164 }
2165
2166 #[cfg(test)]
2167 macro_rules! expect_payment_failed_with_update {
2168         ($node: expr, $expected_payment_hash: expr, $payment_failed_permanently: expr, $scid: expr, $chan_closed: expr) => {
2169                 $crate::ln::functional_test_utils::expect_payment_failed_conditions(
2170                         &$node, $expected_payment_hash, $payment_failed_permanently,
2171                         $crate::ln::functional_test_utils::PaymentFailedConditions::new()
2172                                 .blamed_scid($scid).blamed_chan_closed($chan_closed));
2173         }
2174 }
2175
2176 #[cfg(test)]
2177 macro_rules! expect_payment_failed {
2178         ($node: expr, $expected_payment_hash: expr, $payment_failed_permanently: expr $(, $expected_error_code: expr, $expected_error_data: expr)*) => {
2179                 #[allow(unused_mut)]
2180                 let mut conditions = $crate::ln::functional_test_utils::PaymentFailedConditions::new();
2181                 $(
2182                         conditions = conditions.expected_htlc_error_data($expected_error_code, &$expected_error_data);
2183                 )*
2184                 $crate::ln::functional_test_utils::expect_payment_failed_conditions(&$node, $expected_payment_hash, $payment_failed_permanently, conditions);
2185         };
2186 }
2187
2188 pub fn expect_payment_failed_conditions_event<'a, 'b, 'c, 'd, 'e>(
2189         payment_failed_events: Vec<Event>, expected_payment_hash: PaymentHash,
2190         expected_payment_failed_permanently: bool, conditions: PaymentFailedConditions<'e>
2191 ) {
2192         if conditions.expected_mpp_parts_remain { assert_eq!(payment_failed_events.len(), 1); } else { assert_eq!(payment_failed_events.len(), 2); }
2193         let expected_payment_id = match &payment_failed_events[0] {
2194                 Event::PaymentPathFailed { payment_hash, payment_failed_permanently, payment_id, failure,
2195                         #[cfg(test)]
2196                         error_code,
2197                         #[cfg(test)]
2198                         error_data, .. } => {
2199                         assert_eq!(*payment_hash, expected_payment_hash, "unexpected payment_hash");
2200                         assert_eq!(*payment_failed_permanently, expected_payment_failed_permanently, "unexpected payment_failed_permanently value");
2201                         #[cfg(test)]
2202                         {
2203                                 assert!(error_code.is_some(), "expected error_code.is_some() = true");
2204                                 assert!(error_data.is_some(), "expected error_data.is_some() = true");
2205                                 if let Some((code, data)) = conditions.expected_htlc_error_data {
2206                                         assert_eq!(error_code.unwrap(), code, "unexpected error code");
2207                                         assert_eq!(&error_data.as_ref().unwrap()[..], data, "unexpected error data");
2208                                 }
2209                         }
2210
2211                         if let Some(chan_closed) = conditions.expected_blamed_chan_closed {
2212                                 if let PathFailure::OnPath { network_update: Some(upd) } = failure {
2213                                         match upd {
2214                                                 NetworkUpdate::ChannelUpdateMessage { ref msg } if !chan_closed => {
2215                                                         if let Some(scid) = conditions.expected_blamed_scid {
2216                                                                 assert_eq!(msg.contents.short_channel_id, scid);
2217                                                         }
2218                                                         const CHAN_DISABLED_FLAG: u8 = 2;
2219                                                         assert_eq!(msg.contents.flags & CHAN_DISABLED_FLAG, 0);
2220                                                 },
2221                                                 NetworkUpdate::ChannelFailure { short_channel_id, is_permanent } if chan_closed => {
2222                                                         if let Some(scid) = conditions.expected_blamed_scid {
2223                                                                 assert_eq!(*short_channel_id, scid);
2224                                                         }
2225                                                         assert!(is_permanent);
2226                                                 },
2227                                                 _ => panic!("Unexpected update type"),
2228                                         }
2229                                 } else { panic!("Expected network update"); }
2230                         }
2231
2232                         payment_id.unwrap()
2233                 },
2234                 _ => panic!("Unexpected event"),
2235         };
2236         if !conditions.expected_mpp_parts_remain {
2237                 match &payment_failed_events[1] {
2238                         Event::PaymentFailed { ref payment_hash, ref payment_id, ref reason } => {
2239                                 assert_eq!(*payment_hash, expected_payment_hash, "unexpected second payment_hash");
2240                                 assert_eq!(*payment_id, expected_payment_id);
2241                                 assert_eq!(reason.unwrap(), if expected_payment_failed_permanently {
2242                                         PaymentFailureReason::RecipientRejected
2243                                 } else {
2244                                         PaymentFailureReason::RetriesExhausted
2245                                 });
2246                         }
2247                         _ => panic!("Unexpected second event"),
2248                 }
2249         }
2250 }
2251
2252 pub fn expect_payment_failed_conditions<'a, 'b, 'c, 'd, 'e>(
2253         node: &'a Node<'b, 'c, 'd>, expected_payment_hash: PaymentHash, expected_payment_failed_permanently: bool,
2254         conditions: PaymentFailedConditions<'e>
2255 ) {
2256         let events = node.node.get_and_clear_pending_events();
2257         expect_payment_failed_conditions_event(events, expected_payment_hash, expected_payment_failed_permanently, conditions);
2258 }
2259
2260 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 {
2261         let payment_id = PaymentId(origin_node.keys_manager.backing.get_secure_random_bytes());
2262         origin_node.node.send_payment_with_route(&route, our_payment_hash,
2263                 RecipientOnionFields::secret_only(our_payment_secret), payment_id).unwrap();
2264         check_added_monitors!(origin_node, expected_paths.len());
2265         pass_along_route(origin_node, expected_paths, recv_value, our_payment_hash, our_payment_secret);
2266         payment_id
2267 }
2268
2269 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_claimable_expected: bool, clear_recipient_events: bool, expected_preimage: Option<PaymentPreimage>) -> Option<Event> {
2270         let mut payment_event = SendEvent::from_event(ev);
2271         let mut prev_node = origin_node;
2272         let mut event = None;
2273
2274         for (idx, &node) in expected_path.iter().enumerate() {
2275                 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
2276
2277                 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
2278                 check_added_monitors!(node, 0);
2279                 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
2280
2281                 expect_pending_htlcs_forwardable!(node);
2282
2283                 if idx == expected_path.len() - 1 && clear_recipient_events {
2284                         let events_2 = node.node.get_and_clear_pending_events();
2285                         if payment_claimable_expected {
2286                                 assert_eq!(events_2.len(), 1);
2287                                 match &events_2[0] {
2288                                         Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat,
2289                                                 receiver_node_id, ref via_channel_id, ref via_user_channel_id,
2290                                                 claim_deadline, onion_fields, ..
2291                                         } => {
2292                                                 assert_eq!(our_payment_hash, *payment_hash);
2293                                                 assert_eq!(node.node.get_our_node_id(), receiver_node_id.unwrap());
2294                                                 assert!(onion_fields.is_some());
2295                                                 match &purpose {
2296                                                         PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2297                                                                 assert_eq!(expected_preimage, *payment_preimage);
2298                                                                 assert_eq!(our_payment_secret.unwrap(), *payment_secret);
2299                                                                 assert_eq!(Some(*payment_secret), onion_fields.as_ref().unwrap().payment_secret);
2300                                                         },
2301                                                         PaymentPurpose::SpontaneousPayment(payment_preimage) => {
2302                                                                 assert_eq!(expected_preimage.unwrap(), *payment_preimage);
2303                                                                 assert_eq!(our_payment_secret, onion_fields.as_ref().unwrap().payment_secret);
2304                                                         },
2305                                                 }
2306                                                 assert_eq!(*amount_msat, recv_value);
2307                                                 assert!(node.node.list_channels().iter().any(|details| details.channel_id == via_channel_id.unwrap()));
2308                                                 assert!(node.node.list_channels().iter().any(|details| details.user_channel_id == via_user_channel_id.unwrap()));
2309                                                 assert!(claim_deadline.unwrap() > node.best_block_info().1);
2310                                         },
2311                                         _ => panic!("Unexpected event"),
2312                                 }
2313                                 event = Some(events_2[0].clone());
2314                         } else {
2315                                 assert!(events_2.is_empty());
2316                         }
2317                 } else if idx != expected_path.len() - 1 {
2318                         let mut events_2 = node.node.get_and_clear_pending_msg_events();
2319                         assert_eq!(events_2.len(), 1);
2320                         check_added_monitors!(node, 1);
2321                         payment_event = SendEvent::from_event(events_2.remove(0));
2322                         assert_eq!(payment_event.msgs.len(), 1);
2323                 }
2324
2325                 prev_node = node;
2326         }
2327         event
2328 }
2329
2330 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_claimable_expected: bool, expected_preimage: Option<PaymentPreimage>) -> Option<Event> {
2331         do_pass_along_path(origin_node, expected_path, recv_value, our_payment_hash, our_payment_secret, ev, payment_claimable_expected, true, expected_preimage)
2332 }
2333
2334 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) {
2335         let mut events = origin_node.node.get_and_clear_pending_msg_events();
2336         assert_eq!(events.len(), expected_route.len());
2337         for (path_idx, expected_path) in expected_route.iter().enumerate() {
2338                 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
2339                 // Once we've gotten through all the HTLCs, the last one should result in a
2340                 // PaymentClaimable (but each previous one should not!), .
2341                 let expect_payment = path_idx == expected_route.len() - 1;
2342                 pass_along_path(origin_node, expected_path, recv_value, our_payment_hash.clone(), Some(our_payment_secret), ev, expect_payment, None);
2343         }
2344 }
2345
2346 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) {
2347         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(expected_route.last().unwrap());
2348         let payment_id = send_along_route_with_secret(origin_node, route, &[expected_route], recv_value, our_payment_hash, our_payment_secret);
2349         (our_payment_preimage, our_payment_hash, our_payment_secret, payment_id)
2350 }
2351
2352 pub fn do_claim_payment_along_route<'a, 'b, 'c>(
2353         origin_node: &Node<'a, 'b, 'c>, expected_paths: &[&[&Node<'a, 'b, 'c>]], skip_last: bool,
2354         our_payment_preimage: PaymentPreimage
2355 ) -> u64 {
2356         let extra_fees = vec![0; expected_paths.len()];
2357         do_claim_payment_along_route_with_extra_penultimate_hop_fees(origin_node, expected_paths,
2358                 &extra_fees[..], skip_last, our_payment_preimage)
2359 }
2360
2361 pub fn do_claim_payment_along_route_with_extra_penultimate_hop_fees<'a, 'b, 'c>(
2362         origin_node: &Node<'a, 'b, 'c>, expected_paths: &[&[&Node<'a, 'b, 'c>]], expected_extra_fees:
2363         &[u32], skip_last: bool, our_payment_preimage: PaymentPreimage
2364 ) -> u64 {
2365         assert_eq!(expected_paths.len(), expected_extra_fees.len());
2366         for path in expected_paths.iter() {
2367                 assert_eq!(path.last().unwrap().node.get_our_node_id(), expected_paths[0].last().unwrap().node.get_our_node_id());
2368         }
2369         expected_paths[0].last().unwrap().node.claim_funds(our_payment_preimage);
2370         pass_claimed_payment_along_route(origin_node, expected_paths, expected_extra_fees, skip_last, our_payment_preimage)
2371 }
2372
2373 pub fn pass_claimed_payment_along_route<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_paths: &[&[&Node<'a, 'b, 'c>]], expected_extra_fees: &[u32], skip_last: bool, our_payment_preimage: PaymentPreimage) -> u64 {
2374         let claim_event = expected_paths[0].last().unwrap().node.get_and_clear_pending_events();
2375         assert_eq!(claim_event.len(), 1);
2376         match claim_event[0] {
2377                 Event::PaymentClaimed {
2378                         purpose: PaymentPurpose::SpontaneousPayment(preimage),
2379                         amount_msat,
2380                         ref htlcs,
2381                         .. }
2382                 | Event::PaymentClaimed {
2383                         purpose: PaymentPurpose::InvoicePayment { payment_preimage: Some(preimage), ..},
2384                         ref htlcs,
2385                         amount_msat,
2386                         ..
2387                 } => {
2388                         assert_eq!(preimage, our_payment_preimage);
2389                         assert_eq!(htlcs.len(), expected_paths.len());  // One per path.
2390                         assert_eq!(htlcs.iter().map(|h| h.value_msat).sum::<u64>(), amount_msat);
2391                         expected_paths.iter().zip(htlcs).for_each(|(path, htlc)| check_claimed_htlc_channel(origin_node, path, htlc));
2392                 },
2393                 Event::PaymentClaimed {
2394                         purpose: PaymentPurpose::InvoicePayment { .. },
2395                         payment_hash,
2396                         amount_msat,
2397                         ref htlcs,
2398                         ..
2399                 } => {
2400                         assert_eq!(&payment_hash.0, &Sha256::hash(&our_payment_preimage.0)[..]);
2401                         assert_eq!(htlcs.len(), expected_paths.len());  // One per path.
2402                         assert_eq!(htlcs.iter().map(|h| h.value_msat).sum::<u64>(), amount_msat);
2403                         expected_paths.iter().zip(htlcs).for_each(|(path, htlc)| check_claimed_htlc_channel(origin_node, path, htlc));
2404                 }
2405                 _ => panic!(),
2406         }
2407
2408         check_added_monitors!(expected_paths[0].last().unwrap(), expected_paths.len());
2409
2410         let mut expected_total_fee_msat = 0;
2411
2412         macro_rules! msgs_from_ev {
2413                 ($ev: expr) => {
2414                         match $ev {
2415                                 &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 } } => {
2416                                         assert!(update_add_htlcs.is_empty());
2417                                         assert_eq!(update_fulfill_htlcs.len(), 1);
2418                                         assert!(update_fail_htlcs.is_empty());
2419                                         assert!(update_fail_malformed_htlcs.is_empty());
2420                                         assert!(update_fee.is_none());
2421                                         ((update_fulfill_htlcs[0].clone(), commitment_signed.clone()), node_id.clone())
2422                                 },
2423                                 _ => panic!("Unexpected event"),
2424                         }
2425                 }
2426         }
2427         let mut per_path_msgs: Vec<((msgs::UpdateFulfillHTLC, msgs::CommitmentSigned), PublicKey)> = Vec::with_capacity(expected_paths.len());
2428         let mut events = expected_paths[0].last().unwrap().node.get_and_clear_pending_msg_events();
2429         assert_eq!(events.len(), expected_paths.len());
2430
2431         if events.len() == 1 {
2432                 per_path_msgs.push(msgs_from_ev!(&events[0]));
2433         } else {
2434                 for expected_path in expected_paths.iter() {
2435                         // For MPP payments, we always want the message to the first node in the path.
2436                         let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
2437                         per_path_msgs.push(msgs_from_ev!(&ev));
2438                 }
2439         }
2440
2441         for (i, (expected_route, (path_msgs, next_hop))) in expected_paths.iter().zip(per_path_msgs.drain(..)).enumerate() {
2442                 let mut next_msgs = Some(path_msgs);
2443                 let mut expected_next_node = next_hop;
2444
2445                 macro_rules! last_update_fulfill_dance {
2446                         ($node: expr, $prev_node: expr) => {
2447                                 {
2448                                         $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0);
2449                                         check_added_monitors!($node, 0);
2450                                         assert!($node.node.get_and_clear_pending_msg_events().is_empty());
2451                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
2452                                 }
2453                         }
2454                 }
2455                 macro_rules! mid_update_fulfill_dance {
2456                         ($idx: expr, $node: expr, $prev_node: expr, $next_node: expr, $new_msgs: expr) => {
2457                                 {
2458                                         $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0);
2459                                         let mut fee = {
2460                                                 let per_peer_state = $node.node.per_peer_state.read().unwrap();
2461                                                 let peer_state = per_peer_state.get(&$prev_node.node.get_our_node_id())
2462                                                         .unwrap().lock().unwrap();
2463                                                 let channel = peer_state.channel_by_id.get(&next_msgs.as_ref().unwrap().0.channel_id).unwrap();
2464                                                 if let Some(prev_config) = channel.context().prev_config() {
2465                                                         prev_config.forwarding_fee_base_msat
2466                                                 } else {
2467                                                         channel.context().config().forwarding_fee_base_msat
2468                                                 }
2469                                         };
2470                                         if $idx == 1 { fee += expected_extra_fees[i]; }
2471                                         expect_payment_forwarded!(*$node, $next_node, $prev_node, Some(fee as u64), false, false);
2472                                         expected_total_fee_msat += fee as u64;
2473                                         check_added_monitors!($node, 1);
2474                                         let new_next_msgs = if $new_msgs {
2475                                                 let events = $node.node.get_and_clear_pending_msg_events();
2476                                                 assert_eq!(events.len(), 1);
2477                                                 let (res, nexthop) = msgs_from_ev!(&events[0]);
2478                                                 expected_next_node = nexthop;
2479                                                 Some(res)
2480                                         } else {
2481                                                 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
2482                                                 None
2483                                         };
2484                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
2485                                         next_msgs = new_next_msgs;
2486                                 }
2487                         }
2488                 }
2489
2490                 let mut prev_node = expected_route.last().unwrap();
2491                 for (idx, node) in expected_route.iter().rev().enumerate().skip(1) {
2492                         assert_eq!(expected_next_node, node.node.get_our_node_id());
2493                         let update_next_msgs = !skip_last || idx != expected_route.len() - 1;
2494                         if next_msgs.is_some() {
2495                                 // Since we are traversing in reverse, next_node is actually the previous node
2496                                 let next_node: &Node;
2497                                 if idx == expected_route.len() - 1 {
2498                                         next_node = origin_node;
2499                                 } else {
2500                                         next_node = expected_route[expected_route.len() - 1 - idx - 1];
2501                                 }
2502                                 mid_update_fulfill_dance!(idx, node, prev_node, next_node, update_next_msgs);
2503                         } else {
2504                                 assert!(!update_next_msgs);
2505                                 assert!(node.node.get_and_clear_pending_msg_events().is_empty());
2506                         }
2507                         if !skip_last && idx == expected_route.len() - 1 {
2508                                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
2509                         }
2510
2511                         prev_node = node;
2512                 }
2513
2514                 if !skip_last {
2515                         last_update_fulfill_dance!(origin_node, expected_route.first().unwrap());
2516                 }
2517         }
2518
2519         // Ensure that claim_funds is idempotent.
2520         expected_paths[0].last().unwrap().node.claim_funds(our_payment_preimage);
2521         assert!(expected_paths[0].last().unwrap().node.get_and_clear_pending_msg_events().is_empty());
2522         check_added_monitors!(expected_paths[0].last().unwrap(), 0);
2523
2524         expected_total_fee_msat
2525 }
2526 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) {
2527         let expected_total_fee_msat = do_claim_payment_along_route(origin_node, expected_paths, skip_last, our_payment_preimage);
2528         if !skip_last {
2529                 expect_payment_sent!(origin_node, our_payment_preimage, Some(expected_total_fee_msat));
2530         }
2531 }
2532
2533 pub fn claim_payment<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_route: &[&Node<'a, 'b, 'c>], our_payment_preimage: PaymentPreimage) {
2534         claim_payment_along_route(origin_node, &[expected_route], false, our_payment_preimage);
2535 }
2536
2537 pub const TEST_FINAL_CLTV: u32 = 70;
2538
2539 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, PaymentId) {
2540         let payment_params = PaymentParameters::from_node_id(expected_route.last().unwrap().node.get_our_node_id(), TEST_FINAL_CLTV)
2541                 .with_bolt11_features(expected_route.last().unwrap().node.bolt11_invoice_features()).unwrap();
2542         let route_params = RouteParameters::from_payment_params_and_value(payment_params, recv_value);
2543         let route = get_route(origin_node, &route_params).unwrap();
2544         assert_eq!(route.paths.len(), 1);
2545         assert_eq!(route.paths[0].hops.len(), expected_route.len());
2546         for (node, hop) in expected_route.iter().zip(route.paths[0].hops.iter()) {
2547                 assert_eq!(hop.pubkey, node.node.get_our_node_id());
2548         }
2549
2550         let res = send_along_route(origin_node, route, expected_route, recv_value);
2551         (res.0, res.1, res.2, res.3)
2552 }
2553
2554 pub fn route_over_limit<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_route: &[&Node<'a, 'b, 'c>], recv_value: u64)  {
2555         let payment_params = PaymentParameters::from_node_id(expected_route.last().unwrap().node.get_our_node_id(), TEST_FINAL_CLTV)
2556                 .with_bolt11_features(expected_route.last().unwrap().node.bolt11_invoice_features()).unwrap();
2557         let route_params = RouteParameters::from_payment_params_and_value(payment_params, recv_value);
2558         let network_graph = origin_node.network_graph.read_only();
2559         let scorer = test_utils::TestScorer::new();
2560         let seed = [0u8; 32];
2561         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
2562         let random_seed_bytes = keys_manager.get_secure_random_bytes();
2563         let route = router::get_route(&origin_node.node.get_our_node_id(), &route_params, &network_graph,
2564                 None, origin_node.logger, &scorer, &Default::default(), &random_seed_bytes).unwrap();
2565         assert_eq!(route.paths.len(), 1);
2566         assert_eq!(route.paths[0].hops.len(), expected_route.len());
2567         for (node, hop) in expected_route.iter().zip(route.paths[0].hops.iter()) {
2568                 assert_eq!(hop.pubkey, node.node.get_our_node_id());
2569         }
2570
2571         let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(expected_route.last().unwrap());
2572         unwrap_send_err!(origin_node.node.send_payment_with_route(&route, our_payment_hash,
2573                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)),
2574                 true, APIError::ChannelUnavailable { ref err },
2575                 assert!(err.contains("Cannot send value that would put us over the max HTLC value in flight our peer will accept")));
2576 }
2577
2578 pub fn send_payment<'a, 'b, 'c>(origin: &Node<'a, 'b, 'c>, expected_route: &[&Node<'a, 'b, 'c>], recv_value: u64) -> (PaymentPreimage, PaymentHash, PaymentSecret, PaymentId) {
2579         let res = route_payment(&origin, expected_route, recv_value);
2580         claim_payment(&origin, expected_route, res.0);
2581         res
2582 }
2583
2584 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) {
2585         for path in expected_paths.iter() {
2586                 assert_eq!(path.last().unwrap().node.get_our_node_id(), expected_paths[0].last().unwrap().node.get_our_node_id());
2587         }
2588         expected_paths[0].last().unwrap().node.fail_htlc_backwards(&our_payment_hash);
2589         let expected_destinations: Vec<HTLCDestination> = repeat(HTLCDestination::FailedPayment { payment_hash: our_payment_hash }).take(expected_paths.len()).collect();
2590         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(expected_paths[0].last().unwrap(), expected_destinations);
2591
2592         pass_failed_payment_back(origin_node, expected_paths, skip_last, our_payment_hash, PaymentFailureReason::RecipientRejected);
2593 }
2594
2595 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, expected_fail_reason: PaymentFailureReason) {
2596         let mut expected_paths: Vec<_> = expected_paths_slice.iter().collect();
2597         check_added_monitors!(expected_paths[0].last().unwrap(), expected_paths.len());
2598
2599         let mut per_path_msgs: Vec<((msgs::UpdateFailHTLC, msgs::CommitmentSigned), PublicKey)> = Vec::with_capacity(expected_paths.len());
2600         let events = expected_paths[0].last().unwrap().node.get_and_clear_pending_msg_events();
2601         assert_eq!(events.len(), expected_paths.len());
2602         for ev in events.iter() {
2603                 let (update_fail, commitment_signed, node_id) = match ev {
2604                         &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 } } => {
2605                                 assert!(update_add_htlcs.is_empty());
2606                                 assert!(update_fulfill_htlcs.is_empty());
2607                                 assert_eq!(update_fail_htlcs.len(), 1);
2608                                 assert!(update_fail_malformed_htlcs.is_empty());
2609                                 assert!(update_fee.is_none());
2610                                 (update_fail_htlcs[0].clone(), commitment_signed.clone(), node_id.clone())
2611                         },
2612                         _ => panic!("Unexpected event"),
2613                 };
2614                 per_path_msgs.push(((update_fail, commitment_signed), node_id));
2615         }
2616         per_path_msgs.sort_unstable_by(|(_, node_id_a), (_, node_id_b)| node_id_a.cmp(node_id_b));
2617         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()));
2618
2619         for (i, (expected_route, (path_msgs, next_hop))) in expected_paths.iter().zip(per_path_msgs.drain(..)).enumerate() {
2620                 let mut next_msgs = Some(path_msgs);
2621                 let mut expected_next_node = next_hop;
2622                 let mut prev_node = expected_route.last().unwrap();
2623
2624                 for (idx, node) in expected_route.iter().rev().enumerate().skip(1) {
2625                         assert_eq!(expected_next_node, node.node.get_our_node_id());
2626                         let update_next_node = !skip_last || idx != expected_route.len() - 1;
2627                         if next_msgs.is_some() {
2628                                 node.node.handle_update_fail_htlc(&prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0);
2629                                 commitment_signed_dance!(node, prev_node, next_msgs.as_ref().unwrap().1, update_next_node);
2630                                 if !update_next_node {
2631                                         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 }]);
2632                                 }
2633                         }
2634                         let events = node.node.get_and_clear_pending_msg_events();
2635                         if update_next_node {
2636                                 assert_eq!(events.len(), 1);
2637                                 match events[0] {
2638                                         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 } } => {
2639                                                 assert!(update_add_htlcs.is_empty());
2640                                                 assert!(update_fulfill_htlcs.is_empty());
2641                                                 assert_eq!(update_fail_htlcs.len(), 1);
2642                                                 assert!(update_fail_malformed_htlcs.is_empty());
2643                                                 assert!(update_fee.is_none());
2644                                                 expected_next_node = node_id.clone();
2645                                                 next_msgs = Some((update_fail_htlcs[0].clone(), commitment_signed.clone()));
2646                                         },
2647                                         _ => panic!("Unexpected event"),
2648                                 }
2649                         } else {
2650                                 assert!(events.is_empty());
2651                         }
2652                         if !skip_last && idx == expected_route.len() - 1 {
2653                                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
2654                         }
2655
2656                         prev_node = node;
2657                 }
2658
2659                 if !skip_last {
2660                         let prev_node = expected_route.first().unwrap();
2661                         origin_node.node.handle_update_fail_htlc(&prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0);
2662                         check_added_monitors!(origin_node, 0);
2663                         assert!(origin_node.node.get_and_clear_pending_msg_events().is_empty());
2664                         commitment_signed_dance!(origin_node, prev_node, next_msgs.as_ref().unwrap().1, false);
2665                         let events = origin_node.node.get_and_clear_pending_events();
2666                         if i == expected_paths.len() - 1 { assert_eq!(events.len(), 2); } else { assert_eq!(events.len(), 1); }
2667
2668                         let expected_payment_id = match events[0] {
2669                                 Event::PaymentPathFailed { payment_hash, payment_failed_permanently, ref path, ref payment_id, .. } => {
2670                                         assert_eq!(payment_hash, our_payment_hash);
2671                                         assert!(payment_failed_permanently);
2672                                         for (idx, hop) in expected_route.iter().enumerate() {
2673                                                 assert_eq!(hop.node.get_our_node_id(), path.hops[idx].pubkey);
2674                                         }
2675                                         payment_id.unwrap()
2676                                 },
2677                                 _ => panic!("Unexpected event"),
2678                         };
2679                         if i == expected_paths.len() - 1 {
2680                                 match events[1] {
2681                                         Event::PaymentFailed { ref payment_hash, ref payment_id, ref reason } => {
2682                                                 assert_eq!(*payment_hash, our_payment_hash, "unexpected second payment_hash");
2683                                                 assert_eq!(*payment_id, expected_payment_id);
2684                                                 assert_eq!(reason.unwrap(), expected_fail_reason);
2685                                         }
2686                                         _ => panic!("Unexpected second event"),
2687                                 }
2688                         }
2689                 }
2690         }
2691
2692         // Ensure that fail_htlc_backwards is idempotent.
2693         expected_paths[0].last().unwrap().node.fail_htlc_backwards(&our_payment_hash);
2694         assert!(expected_paths[0].last().unwrap().node.get_and_clear_pending_events().is_empty());
2695         assert!(expected_paths[0].last().unwrap().node.get_and_clear_pending_msg_events().is_empty());
2696         check_added_monitors!(expected_paths[0].last().unwrap(), 0);
2697 }
2698
2699 pub fn fail_payment<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_path: &[&Node<'a, 'b, 'c>], our_payment_hash: PaymentHash)  {
2700         fail_payment_along_route(origin_node, &[&expected_path[..]], false, our_payment_hash);
2701 }
2702
2703 pub fn create_chanmon_cfgs(node_count: usize) -> Vec<TestChanMonCfg> {
2704         let mut chan_mon_cfgs = Vec::new();
2705         for i in 0..node_count {
2706                 let tx_broadcaster = test_utils::TestBroadcaster::new(Network::Testnet);
2707                 let fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
2708                 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
2709                 let logger = test_utils::TestLogger::with_id(format!("node {}", i));
2710                 let persister = test_utils::TestPersister::new();
2711                 let seed = [i as u8; 32];
2712                 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
2713                 let scorer = RwLock::new(test_utils::TestScorer::new());
2714
2715                 chan_mon_cfgs.push(TestChanMonCfg { tx_broadcaster, fee_estimator, chain_source, logger, persister, keys_manager, scorer });
2716         }
2717
2718         chan_mon_cfgs
2719 }
2720
2721 pub fn create_node_cfgs<'a>(node_count: usize, chanmon_cfgs: &'a Vec<TestChanMonCfg>) -> Vec<NodeCfg<'a>> {
2722         create_node_cfgs_with_persisters(node_count, chanmon_cfgs, chanmon_cfgs.iter().map(|c| &c.persister).collect())
2723 }
2724
2725 pub fn create_node_cfgs_with_persisters<'a>(node_count: usize, chanmon_cfgs: &'a Vec<TestChanMonCfg>, persisters: Vec<&'a impl Persist<TestChannelSigner>>) -> Vec<NodeCfg<'a>> {
2726         let mut nodes = Vec::new();
2727
2728         for i in 0..node_count {
2729                 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, persisters[i], &chanmon_cfgs[i].keys_manager);
2730                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[i].logger));
2731                 let seed = [i as u8; 32];
2732                 nodes.push(NodeCfg {
2733                         chain_source: &chanmon_cfgs[i].chain_source,
2734                         logger: &chanmon_cfgs[i].logger,
2735                         tx_broadcaster: &chanmon_cfgs[i].tx_broadcaster,
2736                         fee_estimator: &chanmon_cfgs[i].fee_estimator,
2737                         router: test_utils::TestRouter::new(network_graph.clone(), &chanmon_cfgs[i].scorer),
2738                         chain_monitor,
2739                         keys_manager: &chanmon_cfgs[i].keys_manager,
2740                         node_seed: seed,
2741                         network_graph,
2742                         override_init_features: Rc::new(RefCell::new(None)),
2743                 });
2744         }
2745
2746         nodes
2747 }
2748
2749 pub fn test_default_channel_config() -> UserConfig {
2750         let mut default_config = UserConfig::default();
2751         // Set cltv_expiry_delta slightly lower to keep the final CLTV values inside one byte in our
2752         // tests so that our script-length checks don't fail (see ACCEPTED_HTLC_SCRIPT_WEIGHT).
2753         default_config.channel_config.cltv_expiry_delta = MIN_CLTV_EXPIRY_DELTA;
2754         default_config.channel_handshake_config.announced_channel = true;
2755         default_config.channel_handshake_limits.force_announced_channel_preference = false;
2756         // When most of our tests were written, the default HTLC minimum was fixed at 1000.
2757         // It now defaults to 1, so we simply set it to the expected value here.
2758         default_config.channel_handshake_config.our_htlc_minimum_msat = 1000;
2759         // When most of our tests were written, we didn't have the notion of a `max_dust_htlc_exposure_msat`,
2760         // to avoid interfering with tests we bump it to 50_000_000 msat (assuming the default test
2761         // feerate of 253).
2762         default_config.channel_config.max_dust_htlc_exposure =
2763                 MaxDustHTLCExposure::FeeRateMultiplier(50_000_000 / 253);
2764         default_config
2765 }
2766
2767 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, &'a test_utils::TestKeysInterface, &'a test_utils::TestKeysInterface, &'b test_utils::TestFeeEstimator, &'a test_utils::TestRouter<'b>, &'b test_utils::TestLogger>> {
2768         let mut chanmgrs = Vec::new();
2769         for i in 0..node_count {
2770                 let network = Network::Testnet;
2771                 let genesis_block = bitcoin::blockdata::constants::genesis_block(network);
2772                 let params = ChainParameters {
2773                         network,
2774                         best_block: BestBlock::from_network(network),
2775                 };
2776                 let node = ChannelManager::new(cfgs[i].fee_estimator, &cfgs[i].chain_monitor, cfgs[i].tx_broadcaster, &cfgs[i].router, cfgs[i].logger, cfgs[i].keys_manager,
2777                         cfgs[i].keys_manager, cfgs[i].keys_manager, if node_config[i].is_some() { node_config[i].clone().unwrap() } else { test_default_channel_config() }, params, genesis_block.header.time);
2778                 chanmgrs.push(node);
2779         }
2780
2781         chanmgrs
2782 }
2783
2784 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, &'b test_utils::TestKeysInterface, &'b test_utils::TestKeysInterface, &'c test_utils::TestFeeEstimator, &'c test_utils::TestRouter, &'c test_utils::TestLogger>>) -> Vec<Node<'a, 'b, 'c>> {
2785         let mut nodes = Vec::new();
2786         let chan_count = Rc::new(RefCell::new(0));
2787         let payment_count = Rc::new(RefCell::new(0));
2788         let connect_style = Rc::new(RefCell::new(ConnectStyle::random_style()));
2789
2790         for i in 0..node_count {
2791                 let gossip_sync = P2PGossipSync::new(cfgs[i].network_graph.as_ref(), None, cfgs[i].logger);
2792                 let wallet_source = Arc::new(test_utils::TestWalletSource::new(SecretKey::from_slice(&[i as u8 + 1; 32]).unwrap()));
2793                 nodes.push(Node{
2794                         chain_source: cfgs[i].chain_source, tx_broadcaster: cfgs[i].tx_broadcaster,
2795                         fee_estimator: cfgs[i].fee_estimator, router: &cfgs[i].router,
2796                         chain_monitor: &cfgs[i].chain_monitor, keys_manager: &cfgs[i].keys_manager,
2797                         node: &chan_mgrs[i], network_graph: cfgs[i].network_graph.as_ref(), gossip_sync,
2798                         node_seed: cfgs[i].node_seed, network_chan_count: chan_count.clone(),
2799                         network_payment_count: payment_count.clone(), logger: cfgs[i].logger,
2800                         blocks: Arc::clone(&cfgs[i].tx_broadcaster.blocks),
2801                         connect_style: Rc::clone(&connect_style),
2802                         override_init_features: Rc::clone(&cfgs[i].override_init_features),
2803                         wallet_source: Arc::clone(&wallet_source),
2804                         bump_tx_handler: BumpTransactionEventHandler::new(
2805                                 cfgs[i].tx_broadcaster, Arc::new(Wallet::new(Arc::clone(&wallet_source), cfgs[i].logger)),
2806                                 &cfgs[i].keys_manager, cfgs[i].logger,
2807                         ),
2808                 })
2809         }
2810
2811         for i in 0..node_count {
2812                 for j in (i+1)..node_count {
2813                         nodes[i].node.peer_connected(&nodes[j].node.get_our_node_id(), &msgs::Init {
2814                                 features: nodes[j].override_init_features.borrow().clone().unwrap_or_else(|| nodes[j].node.init_features()),
2815                                 networks: None,
2816                                 remote_network_address: None,
2817                         }, true).unwrap();
2818                         nodes[j].node.peer_connected(&nodes[i].node.get_our_node_id(), &msgs::Init {
2819                                 features: nodes[i].override_init_features.borrow().clone().unwrap_or_else(|| nodes[i].node.init_features()),
2820                                 networks: None,
2821                                 remote_network_address: None,
2822                         }, false).unwrap();
2823                 }
2824         }
2825
2826         nodes
2827 }
2828
2829 // Note that the following only works for CLTV values up to 128
2830 pub const ACCEPTED_HTLC_SCRIPT_WEIGHT: usize = 137; // Here we have a diff due to HTLC CLTV expiry being < 2^15 in test
2831 pub const ACCEPTED_HTLC_SCRIPT_WEIGHT_ANCHORS: usize = 140; // Here we have a diff due to HTLC CLTV expiry being < 2^15 in test
2832
2833 #[derive(PartialEq)]
2834 pub enum HTLCType { NONE, TIMEOUT, SUCCESS }
2835 /// Tests that the given node has broadcast transactions for the given Channel
2836 ///
2837 /// First checks that the latest holder commitment tx has been broadcast, unless an explicit
2838 /// commitment_tx is provided, which may be used to test that a remote commitment tx was
2839 /// broadcast and the revoked outputs were claimed.
2840 ///
2841 /// Next tests that there is (or is not) a transaction that spends the commitment transaction
2842 /// that appears to be the type of HTLC transaction specified in has_htlc_tx.
2843 ///
2844 /// All broadcast transactions must be accounted for in one of the above three types of we'll
2845 /// also fail.
2846 pub fn test_txn_broadcast<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, chan: &(msgs::ChannelUpdate, msgs::ChannelUpdate, ChannelId, Transaction), commitment_tx: Option<Transaction>, has_htlc_tx: HTLCType) -> Vec<Transaction>  {
2847         let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2848         let mut txn_seen = HashSet::new();
2849         node_txn.retain(|tx| txn_seen.insert(tx.txid()));
2850         assert!(node_txn.len() >= if commitment_tx.is_some() { 0 } else { 1 } + if has_htlc_tx == HTLCType::NONE { 0 } else { 1 });
2851
2852         let mut res = Vec::with_capacity(2);
2853         node_txn.retain(|tx| {
2854                 if tx.input.len() == 1 && tx.input[0].previous_output.txid == chan.3.txid() {
2855                         check_spends!(tx, chan.3);
2856                         if commitment_tx.is_none() {
2857                                 res.push(tx.clone());
2858                         }
2859                         false
2860                 } else { true }
2861         });
2862         if let Some(explicit_tx) = commitment_tx {
2863                 res.push(explicit_tx.clone());
2864         }
2865
2866         assert_eq!(res.len(), 1);
2867
2868         if has_htlc_tx != HTLCType::NONE {
2869                 node_txn.retain(|tx| {
2870                         if tx.input.len() == 1 && tx.input[0].previous_output.txid == res[0].txid() {
2871                                 check_spends!(tx, res[0]);
2872                                 if has_htlc_tx == HTLCType::TIMEOUT {
2873                                         assert!(tx.lock_time.0 != 0);
2874                                 } else {
2875                                         assert!(tx.lock_time.0 == 0);
2876                                 }
2877                                 res.push(tx.clone());
2878                                 false
2879                         } else { true }
2880                 });
2881                 assert!(res.len() == 2 || res.len() == 3);
2882                 if res.len() == 3 {
2883                         assert_eq!(res[1], res[2]);
2884                 }
2885         }
2886
2887         assert!(node_txn.is_empty());
2888         res
2889 }
2890
2891 /// Tests that the given node has broadcast a claim transaction against the provided revoked
2892 /// HTLC transaction.
2893 pub fn test_revoked_htlc_claim_txn_broadcast<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, revoked_tx: Transaction, commitment_revoked_tx: Transaction)  {
2894         let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2895         // We may issue multiple claiming transaction on revoked outputs due to block rescan
2896         // for revoked htlc outputs
2897         if node_txn.len() != 1 && node_txn.len() != 2 && node_txn.len() != 3 { assert!(false); }
2898         node_txn.retain(|tx| {
2899                 if tx.input.len() == 1 && tx.input[0].previous_output.txid == revoked_tx.txid() {
2900                         check_spends!(tx, revoked_tx);
2901                         false
2902                 } else { true }
2903         });
2904         node_txn.retain(|tx| {
2905                 check_spends!(tx, commitment_revoked_tx);
2906                 false
2907         });
2908         assert!(node_txn.is_empty());
2909 }
2910
2911 pub fn check_preimage_claim<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, prev_txn: &Vec<Transaction>) -> Vec<Transaction>  {
2912         let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2913         let mut txn_seen = HashSet::new();
2914         node_txn.retain(|tx| txn_seen.insert(tx.txid()));
2915
2916         let mut found_prev = false;
2917         for prev_tx in prev_txn {
2918                 for tx in &*node_txn {
2919                         if tx.input[0].previous_output.txid == prev_tx.txid() {
2920                                 check_spends!(tx, prev_tx);
2921                                 let mut iter = tx.input[0].witness.iter();
2922                                 iter.next().expect("expected 3 witness items");
2923                                 iter.next().expect("expected 3 witness items");
2924                                 assert!(iter.next().expect("expected 3 witness items").len() > 106); // must spend an htlc output
2925                                 assert_eq!(tx.input.len(), 1); // must spend a commitment tx
2926
2927                                 found_prev = true;
2928                                 break;
2929                         }
2930                 }
2931         }
2932         assert!(found_prev);
2933
2934         let mut res = Vec::new();
2935         mem::swap(&mut *node_txn, &mut res);
2936         res
2937 }
2938
2939 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)  {
2940         let events_1 = nodes[a].node.get_and_clear_pending_msg_events();
2941         assert_eq!(events_1.len(), 2);
2942         let as_update = match events_1[0] {
2943                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2944                         msg.clone()
2945                 },
2946                 _ => panic!("Unexpected event"),
2947         };
2948         match events_1[1] {
2949                 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
2950                         assert_eq!(node_id, nodes[b].node.get_our_node_id());
2951                         assert_eq!(msg.data, expected_error);
2952                         if needs_err_handle {
2953                                 nodes[b].node.handle_error(&nodes[a].node.get_our_node_id(), msg);
2954                         }
2955                 },
2956                 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::DisconnectPeer { ref msg } } => {
2957                         assert_eq!(node_id, nodes[b].node.get_our_node_id());
2958                         assert_eq!(msg.as_ref().unwrap().data, expected_error);
2959                         if needs_err_handle {
2960                                 nodes[b].node.handle_error(&nodes[a].node.get_our_node_id(), msg.as_ref().unwrap());
2961                         }
2962                 },
2963                 _ => panic!("Unexpected event"),
2964         }
2965
2966         let events_2 = nodes[b].node.get_and_clear_pending_msg_events();
2967         assert_eq!(events_2.len(), if needs_err_handle { 1 } else { 2 });
2968         let bs_update = match events_2[0] {
2969                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2970                         msg.clone()
2971                 },
2972                 _ => panic!("Unexpected event"),
2973         };
2974         if !needs_err_handle {
2975                 match events_2[1] {
2976                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
2977                                 assert_eq!(node_id, nodes[a].node.get_our_node_id());
2978                                 assert_eq!(msg.data, expected_error);
2979                         },
2980                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::DisconnectPeer { ref msg } } => {
2981                                 assert_eq!(node_id, nodes[a].node.get_our_node_id());
2982                                 assert_eq!(msg.as_ref().unwrap().data, expected_error);
2983                         },
2984                         _ => panic!("Unexpected event"),
2985                 }
2986         }
2987
2988         for node in nodes {
2989                 node.gossip_sync.handle_channel_update(&as_update).unwrap();
2990                 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
2991         }
2992 }
2993
2994 pub fn get_announce_close_broadcast_events<'a, 'b, 'c>(nodes: &Vec<Node<'a, 'b, 'c>>, a: usize, b: usize)  {
2995         handle_announce_close_broadcast_events(nodes, a, b, false, "Channel closed because commitment or closing transaction was confirmed on chain.");
2996 }
2997
2998 #[cfg(test)]
2999 macro_rules! get_channel_value_stat {
3000         ($node: expr, $counterparty_node: expr, $channel_id: expr) => {{
3001                 let peer_state_lock = $node.node.per_peer_state.read().unwrap();
3002                 let chan_lock = peer_state_lock.get(&$counterparty_node.node.get_our_node_id()).unwrap().lock().unwrap();
3003                 let chan = chan_lock.channel_by_id.get(&$channel_id).map(
3004                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
3005                 ).flatten().unwrap();
3006                 chan.get_value_stat()
3007         }}
3008 }
3009
3010 macro_rules! get_chan_reestablish_msgs {
3011         ($src_node: expr, $dst_node: expr) => {
3012                 {
3013                         let mut announcements = $crate::prelude::HashSet::new();
3014                         let mut res = Vec::with_capacity(1);
3015                         for msg in $src_node.node.get_and_clear_pending_msg_events() {
3016                                 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
3017                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
3018                                         res.push(msg.clone());
3019                                 } else if let MessageSendEvent::SendChannelAnnouncement { ref node_id, ref msg, .. } = msg {
3020                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
3021                                         announcements.insert(msg.contents.short_channel_id);
3022                                 } else {
3023                                         panic!("Unexpected event")
3024                                 }
3025                         }
3026                         assert!(announcements.is_empty());
3027                         res
3028                 }
3029         }
3030 }
3031
3032 macro_rules! handle_chan_reestablish_msgs {
3033         ($src_node: expr, $dst_node: expr) => {
3034                 {
3035                         let msg_events = $src_node.node.get_and_clear_pending_msg_events();
3036                         let mut idx = 0;
3037                         let channel_ready = if let Some(&MessageSendEvent::SendChannelReady { ref node_id, ref msg }) = msg_events.get(0) {
3038                                 idx += 1;
3039                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
3040                                 Some(msg.clone())
3041                         } else {
3042                                 None
3043                         };
3044
3045                         if let Some(&MessageSendEvent::SendAnnouncementSignatures { ref node_id, msg: _ }) = msg_events.get(idx) {
3046                                 idx += 1;
3047                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
3048                         }
3049
3050                         let mut had_channel_update = false; // ChannelUpdate may be now or later, but not both
3051                         if let Some(&MessageSendEvent::SendChannelUpdate { ref node_id, .. }) = msg_events.get(idx) {
3052                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
3053                                 idx += 1;
3054                                 had_channel_update = true;
3055                         }
3056
3057                         let mut revoke_and_ack = None;
3058                         let mut commitment_update = None;
3059                         let order = if let Some(ev) = msg_events.get(idx) {
3060                                 match ev {
3061                                         &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
3062                                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
3063                                                 revoke_and_ack = Some(msg.clone());
3064                                                 idx += 1;
3065                                                 RAACommitmentOrder::RevokeAndACKFirst
3066                                         },
3067                                         &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3068                                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
3069                                                 commitment_update = Some(updates.clone());
3070                                                 idx += 1;
3071                                                 RAACommitmentOrder::CommitmentFirst
3072                                         },
3073                                         _ => RAACommitmentOrder::CommitmentFirst,
3074                                 }
3075                         } else {
3076                                 RAACommitmentOrder::CommitmentFirst
3077                         };
3078
3079                         if let Some(ev) = msg_events.get(idx) {
3080                                 match ev {
3081                                         &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
3082                                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
3083                                                 assert!(revoke_and_ack.is_none());
3084                                                 revoke_and_ack = Some(msg.clone());
3085                                                 idx += 1;
3086                                         },
3087                                         &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3088                                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
3089                                                 assert!(commitment_update.is_none());
3090                                                 commitment_update = Some(updates.clone());
3091                                                 idx += 1;
3092                                         },
3093                                         _ => {},
3094                                 }
3095                         }
3096
3097                         if let Some(&MessageSendEvent::SendChannelUpdate { ref node_id, .. }) = msg_events.get(idx) {
3098                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
3099                                 idx += 1;
3100                                 assert!(!had_channel_update);
3101                         }
3102
3103                         assert_eq!(msg_events.len(), idx);
3104
3105                         (channel_ready, revoke_and_ack, commitment_update, order)
3106                 }
3107         }
3108 }
3109
3110 pub struct ReconnectArgs<'a, 'b, 'c, 'd> {
3111         pub node_a: &'a Node<'b, 'c, 'd>,
3112         pub node_b: &'a Node<'b, 'c, 'd>,
3113         pub send_channel_ready: (bool, bool),
3114         pub pending_responding_commitment_signed: (bool, bool),
3115         /// Indicates that the pending responding commitment signed will be a dup for the recipient,
3116         /// and no monitor update is expected
3117         pub pending_responding_commitment_signed_dup_monitor: (bool, bool),
3118         pub pending_htlc_adds: (usize, usize),
3119         pub pending_htlc_claims: (usize, usize),
3120         pub pending_htlc_fails: (usize, usize),
3121         pub pending_cell_htlc_claims: (usize, usize),
3122         pub pending_cell_htlc_fails: (usize, usize),
3123         pub pending_raa: (bool, bool),
3124 }
3125
3126 impl<'a, 'b, 'c, 'd> ReconnectArgs<'a, 'b, 'c, 'd> {
3127         pub fn new(node_a: &'a Node<'b, 'c, 'd>, node_b: &'a Node<'b, 'c, 'd>) -> Self {
3128                 Self {
3129                         node_a,
3130                         node_b,
3131                         send_channel_ready: (false, false),
3132                         pending_responding_commitment_signed: (false, false),
3133                         pending_responding_commitment_signed_dup_monitor: (false, false),
3134                         pending_htlc_adds: (0, 0),
3135                         pending_htlc_claims: (0, 0),
3136                         pending_htlc_fails: (0, 0),
3137                         pending_cell_htlc_claims: (0, 0),
3138                         pending_cell_htlc_fails: (0, 0),
3139                         pending_raa: (false, false),
3140                 }
3141         }
3142 }
3143
3144 /// pending_htlc_adds includes both the holding cell and in-flight update_add_htlcs, whereas
3145 /// for claims/fails they are separated out.
3146 pub fn reconnect_nodes<'a, 'b, 'c, 'd>(args: ReconnectArgs<'a, 'b, 'c, 'd>) {
3147         let ReconnectArgs {
3148                 node_a, node_b, send_channel_ready, pending_htlc_adds, pending_htlc_claims, pending_htlc_fails,
3149                 pending_cell_htlc_claims, pending_cell_htlc_fails, pending_raa,
3150                 pending_responding_commitment_signed, pending_responding_commitment_signed_dup_monitor,
3151         } = args;
3152         node_a.node.peer_connected(&node_b.node.get_our_node_id(), &msgs::Init {
3153                 features: node_b.node.init_features(), networks: None, remote_network_address: None
3154         }, true).unwrap();
3155         let reestablish_1 = get_chan_reestablish_msgs!(node_a, node_b);
3156         node_b.node.peer_connected(&node_a.node.get_our_node_id(), &msgs::Init {
3157                 features: node_a.node.init_features(), networks: None, remote_network_address: None
3158         }, false).unwrap();
3159         let reestablish_2 = get_chan_reestablish_msgs!(node_b, node_a);
3160
3161         if send_channel_ready.0 {
3162                 // If a expects a channel_ready, it better not think it has received a revoke_and_ack
3163                 // from b
3164                 for reestablish in reestablish_1.iter() {
3165                         assert_eq!(reestablish.next_remote_commitment_number, 0);
3166                 }
3167         }
3168         if send_channel_ready.1 {
3169                 // If b expects a channel_ready, it better not think it has received a revoke_and_ack
3170                 // from a
3171                 for reestablish in reestablish_2.iter() {
3172                         assert_eq!(reestablish.next_remote_commitment_number, 0);
3173                 }
3174         }
3175         if send_channel_ready.0 || send_channel_ready.1 {
3176                 // If we expect any channel_ready's, both sides better have set
3177                 // next_holder_commitment_number to 1
3178                 for reestablish in reestablish_1.iter() {
3179                         assert_eq!(reestablish.next_local_commitment_number, 1);
3180                 }
3181                 for reestablish in reestablish_2.iter() {
3182                         assert_eq!(reestablish.next_local_commitment_number, 1);
3183                 }
3184         }
3185
3186         let mut resp_1 = Vec::new();
3187         for msg in reestablish_1 {
3188                 node_b.node.handle_channel_reestablish(&node_a.node.get_our_node_id(), &msg);
3189                 resp_1.push(handle_chan_reestablish_msgs!(node_b, node_a));
3190         }
3191         if pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
3192                 check_added_monitors!(node_b, 1);
3193         } else {
3194                 check_added_monitors!(node_b, 0);
3195         }
3196
3197         let mut resp_2 = Vec::new();
3198         for msg in reestablish_2 {
3199                 node_a.node.handle_channel_reestablish(&node_b.node.get_our_node_id(), &msg);
3200                 resp_2.push(handle_chan_reestablish_msgs!(node_a, node_b));
3201         }
3202         if pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
3203                 check_added_monitors!(node_a, 1);
3204         } else {
3205                 check_added_monitors!(node_a, 0);
3206         }
3207
3208         // We don't yet support both needing updates, as that would require a different commitment dance:
3209         assert!((pending_htlc_adds.0 == 0 && pending_htlc_claims.0 == 0 && pending_htlc_fails.0 == 0 &&
3210                          pending_cell_htlc_claims.0 == 0 && pending_cell_htlc_fails.0 == 0) ||
3211                         (pending_htlc_adds.1 == 0 && pending_htlc_claims.1 == 0 && pending_htlc_fails.1 == 0 &&
3212                          pending_cell_htlc_claims.1 == 0 && pending_cell_htlc_fails.1 == 0));
3213
3214         for chan_msgs in resp_1.drain(..) {
3215                 if send_channel_ready.0 {
3216                         node_a.node.handle_channel_ready(&node_b.node.get_our_node_id(), &chan_msgs.0.unwrap());
3217                         let announcement_event = node_a.node.get_and_clear_pending_msg_events();
3218                         if !announcement_event.is_empty() {
3219                                 assert_eq!(announcement_event.len(), 1);
3220                                 if let MessageSendEvent::SendChannelUpdate { .. } = announcement_event[0] {
3221                                         //TODO: Test announcement_sigs re-sending
3222                                 } else { panic!("Unexpected event! {:?}", announcement_event[0]); }
3223                         }
3224                 } else {
3225                         assert!(chan_msgs.0.is_none());
3226                 }
3227                 if pending_raa.0 {
3228                         assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
3229                         node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap());
3230                         assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
3231                         check_added_monitors!(node_a, 1);
3232                 } else {
3233                         assert!(chan_msgs.1.is_none());
3234                 }
3235                 if pending_htlc_adds.0 != 0 || pending_htlc_claims.0 != 0 || pending_htlc_fails.0 != 0 ||
3236                         pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 ||
3237                         pending_responding_commitment_signed.0
3238                 {
3239                         let commitment_update = chan_msgs.2.unwrap();
3240                         assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.0);
3241                         assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
3242                         assert_eq!(commitment_update.update_fail_htlcs.len(), pending_htlc_fails.0 + pending_cell_htlc_fails.0);
3243                         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
3244                         for update_add in commitment_update.update_add_htlcs {
3245                                 node_a.node.handle_update_add_htlc(&node_b.node.get_our_node_id(), &update_add);
3246                         }
3247                         for update_fulfill in commitment_update.update_fulfill_htlcs {
3248                                 node_a.node.handle_update_fulfill_htlc(&node_b.node.get_our_node_id(), &update_fulfill);
3249                         }
3250                         for update_fail in commitment_update.update_fail_htlcs {
3251                                 node_a.node.handle_update_fail_htlc(&node_b.node.get_our_node_id(), &update_fail);
3252                         }
3253
3254                         if !pending_responding_commitment_signed.0 {
3255                                 commitment_signed_dance!(node_a, node_b, commitment_update.commitment_signed, false);
3256                         } else {
3257                                 node_a.node.handle_commitment_signed(&node_b.node.get_our_node_id(), &commitment_update.commitment_signed);
3258                                 check_added_monitors!(node_a, 1);
3259                                 let as_revoke_and_ack = get_event_msg!(node_a, MessageSendEvent::SendRevokeAndACK, node_b.node.get_our_node_id());
3260                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
3261                                 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &as_revoke_and_ack);
3262                                 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
3263                                 check_added_monitors!(node_b, if pending_responding_commitment_signed_dup_monitor.0 { 0 } else { 1 });
3264                         }
3265                 } else {
3266                         assert!(chan_msgs.2.is_none());
3267                 }
3268         }
3269
3270         for chan_msgs in resp_2.drain(..) {
3271                 if send_channel_ready.1 {
3272                         node_b.node.handle_channel_ready(&node_a.node.get_our_node_id(), &chan_msgs.0.unwrap());
3273                         let announcement_event = node_b.node.get_and_clear_pending_msg_events();
3274                         if !announcement_event.is_empty() {
3275                                 assert_eq!(announcement_event.len(), 1);
3276                                 match announcement_event[0] {
3277                                         MessageSendEvent::SendChannelUpdate { .. } => {},
3278                                         MessageSendEvent::SendAnnouncementSignatures { .. } => {},
3279                                         _ => panic!("Unexpected event {:?}!", announcement_event[0]),
3280                                 }
3281                         }
3282                 } else {
3283                         assert!(chan_msgs.0.is_none());
3284                 }
3285                 if pending_raa.1 {
3286                         assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
3287                         node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap());
3288                         assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
3289                         check_added_monitors!(node_b, 1);
3290                 } else {
3291                         assert!(chan_msgs.1.is_none());
3292                 }
3293                 if pending_htlc_adds.1 != 0 || pending_htlc_claims.1 != 0 || pending_htlc_fails.1 != 0 ||
3294                         pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 ||
3295                         pending_responding_commitment_signed.1
3296                 {
3297                         let commitment_update = chan_msgs.2.unwrap();
3298                         assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.1);
3299                         assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.1 + pending_cell_htlc_claims.1);
3300                         assert_eq!(commitment_update.update_fail_htlcs.len(), pending_htlc_fails.1 + pending_cell_htlc_fails.1);
3301                         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
3302                         for update_add in commitment_update.update_add_htlcs {
3303                                 node_b.node.handle_update_add_htlc(&node_a.node.get_our_node_id(), &update_add);
3304                         }
3305                         for update_fulfill in commitment_update.update_fulfill_htlcs {
3306                                 node_b.node.handle_update_fulfill_htlc(&node_a.node.get_our_node_id(), &update_fulfill);
3307                         }
3308                         for update_fail in commitment_update.update_fail_htlcs {
3309                                 node_b.node.handle_update_fail_htlc(&node_a.node.get_our_node_id(), &update_fail);
3310                         }
3311
3312                         if !pending_responding_commitment_signed.1 {
3313                                 commitment_signed_dance!(node_b, node_a, commitment_update.commitment_signed, false);
3314                         } else {
3315                                 node_b.node.handle_commitment_signed(&node_a.node.get_our_node_id(), &commitment_update.commitment_signed);
3316                                 check_added_monitors!(node_b, 1);
3317                                 let bs_revoke_and_ack = get_event_msg!(node_b, MessageSendEvent::SendRevokeAndACK, node_a.node.get_our_node_id());
3318                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
3319                                 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &bs_revoke_and_ack);
3320                                 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
3321                                 check_added_monitors!(node_a, if pending_responding_commitment_signed_dup_monitor.1 { 0 } else { 1 });
3322                         }
3323                 } else {
3324                         assert!(chan_msgs.2.is_none());
3325                 }
3326         }
3327 }
3328
3329 /// Initiates channel opening and creates a single batch funding transaction.
3330 /// This will go through the open_channel / accept_channel flow, and return the batch funding
3331 /// transaction with corresponding funding_created messages.
3332 pub fn create_batch_channel_funding<'a, 'b, 'c>(
3333         funding_node: &Node<'a, 'b, 'c>,
3334         params: &[(&Node<'a, 'b, 'c>, u64, u64, u128, Option<UserConfig>)],
3335 ) -> (Transaction, Vec<msgs::FundingCreated>) {
3336         let mut tx_outs = Vec::new();
3337         let mut temp_chan_ids = Vec::new();
3338         let mut funding_created_msgs = Vec::new();
3339
3340         for (other_node, channel_value_satoshis, push_msat, user_channel_id, override_config) in params {
3341                 // Initialize channel opening.
3342                 let temp_chan_id = funding_node.node.create_channel(
3343                         other_node.node.get_our_node_id(), *channel_value_satoshis, *push_msat, *user_channel_id,
3344                         *override_config,
3345                 ).unwrap();
3346                 let open_channel_msg = get_event_msg!(funding_node, MessageSendEvent::SendOpenChannel, other_node.node.get_our_node_id());
3347                 other_node.node.handle_open_channel(&funding_node.node.get_our_node_id(), &open_channel_msg);
3348                 let accept_channel_msg = get_event_msg!(other_node, MessageSendEvent::SendAcceptChannel, funding_node.node.get_our_node_id());
3349                 funding_node.node.handle_accept_channel(&other_node.node.get_our_node_id(), &accept_channel_msg);
3350
3351                 // Create the corresponding funding output.
3352                 let events = funding_node.node.get_and_clear_pending_events();
3353                 assert_eq!(events.len(), 1);
3354                 match events[0] {
3355                         Event::FundingGenerationReady {
3356                                 ref temporary_channel_id,
3357                                 ref counterparty_node_id,
3358                                 channel_value_satoshis: ref event_channel_value_satoshis,
3359                                 ref output_script,
3360                                 user_channel_id: ref event_user_channel_id
3361                         } => {
3362                                 assert_eq!(temporary_channel_id, &temp_chan_id);
3363                                 assert_eq!(counterparty_node_id, &other_node.node.get_our_node_id());
3364                                 assert_eq!(channel_value_satoshis, event_channel_value_satoshis);
3365                                 assert_eq!(user_channel_id, event_user_channel_id);
3366                                 tx_outs.push(TxOut {
3367                                         value: *channel_value_satoshis, script_pubkey: output_script.clone(),
3368                                 });
3369                         },
3370                         _ => panic!("Unexpected event"),
3371                 };
3372                 temp_chan_ids.push((temp_chan_id, other_node.node.get_our_node_id()));
3373         }
3374
3375         // Compose the batch funding transaction and give it to the ChannelManager.
3376         let tx = Transaction {
3377                 version: 2,
3378                 lock_time: PackedLockTime::ZERO,
3379                 input: Vec::new(),
3380                 output: tx_outs,
3381         };
3382         assert!(funding_node.node.batch_funding_transaction_generated(
3383                 temp_chan_ids.iter().map(|(a, b)| (a, b)).collect::<Vec<_>>().as_slice(),
3384                 tx.clone(),
3385         ).is_ok());
3386         check_added_monitors!(funding_node, 0);
3387         let events = funding_node.node.get_and_clear_pending_msg_events();
3388         assert_eq!(events.len(), params.len());
3389         for (other_node, ..) in params {
3390                 let funding_created = events
3391                         .iter()
3392                         .find_map(|event| match event {
3393                                 MessageSendEvent::SendFundingCreated { node_id, msg } if node_id == &other_node.node.get_our_node_id() => Some(msg.clone()),
3394                                 _ => None,
3395                         })
3396                         .unwrap();
3397                 funding_created_msgs.push(funding_created);
3398         }
3399         return (tx, funding_created_msgs);
3400 }