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