1 // This file is Copyright its original authors, visible in version control
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
10 //! A bunch of useful utilities for building networks of nodes and exchanging messages between
11 //! nodes for functional tests.
13 use crate::chain::{BestBlock, ChannelMonitorUpdateStatus, Confirm, Listen, Watch, chainmonitor::Persist};
14 use crate::sign::EntropySource;
15 use crate::chain::channelmonitor::ChannelMonitor;
16 use crate::chain::transaction::OutPoint;
17 use crate::events::{ClaimedHTLC, ClosureReason, Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentPurpose, PaymentFailureReason};
18 use crate::events::bump_transaction::{BumpTransactionEvent, BumpTransactionEventHandler, Wallet, WalletSource};
19 use crate::ln::{ChannelId, PaymentPreimage, PaymentHash, PaymentSecret};
20 use crate::ln::channelmanager::{AChannelManager, ChainParameters, ChannelManager, ChannelManagerReadArgs, RAACommitmentOrder, PaymentSendFailure, RecipientOnionFields, PaymentId, MIN_CLTV_EXPIRY_DELTA};
21 use crate::routing::gossip::{P2PGossipSync, NetworkGraph, NetworkUpdate};
22 use crate::routing::router::{self, PaymentParameters, Route, RouteParameters};
23 use crate::ln::features::InitFeatures;
25 use crate::ln::msgs::{ChannelMessageHandler,RoutingMessageHandler};
26 use crate::util::test_channel_signer::TestChannelSigner;
27 use crate::util::scid_utils;
28 use crate::util::test_utils;
29 use crate::util::test_utils::{panicking, TestChainMonitor, TestScorer, TestKeysInterface};
30 use crate::util::errors::APIError;
31 use crate::util::config::{UserConfig, MaxDustHTLCExposure};
32 use crate::util::ser::{ReadableArgs, Writeable};
34 use crate::util::logger::Logger;
36 use bitcoin::blockdata::block::{Block, BlockHeader};
37 use bitcoin::blockdata::transaction::{Transaction, TxOut};
38 use bitcoin::hash_types::BlockHash;
39 use bitcoin::hashes::sha256::Hash as Sha256;
40 use bitcoin::hashes::Hash as _;
41 use bitcoin::network::constants::Network;
42 use bitcoin::secp256k1::{PublicKey, SecretKey};
45 use crate::prelude::*;
46 use core::cell::RefCell;
48 use crate::sync::{Arc, Mutex, LockTestExt, RwLock};
50 use core::iter::repeat;
51 use bitcoin::{PackedLockTime, TxIn, TxMerkleNode};
53 pub const CHAN_CONFIRM_DEPTH: u32 = 10;
55 /// Mine the given transaction in the next block and then mine CHAN_CONFIRM_DEPTH - 1 blocks on
56 /// top, giving the given transaction CHAN_CONFIRM_DEPTH confirmations.
58 /// Returns the SCID a channel confirmed in the given transaction will have, assuming the funding
59 /// output is the 1st output in the transaction.
60 pub fn confirm_transaction<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, tx: &Transaction) -> u64 {
61 let scid = confirm_transaction_at(node, tx, node.best_block_info().1 + 1);
62 connect_blocks(node, CHAN_CONFIRM_DEPTH - 1);
65 /// Mine a single block containing the given transaction
67 /// Returns the SCID a channel confirmed in the given transaction will have, assuming the funding
68 /// output is the 1st output in the transaction.
69 pub fn mine_transaction<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, tx: &Transaction) -> u64 {
70 let height = node.best_block_info().1 + 1;
71 confirm_transaction_at(node, tx, height)
73 /// Mine a single block containing the given transactions
74 pub fn mine_transactions<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, txn: &[&Transaction]) {
75 let height = node.best_block_info().1 + 1;
76 confirm_transactions_at(node, txn, height);
78 /// Mine a single block containing the given transaction without extra consistency checks which may
79 /// impact ChannelManager state.
80 pub fn mine_transaction_without_consistency_checks<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, tx: &Transaction) {
81 let height = node.best_block_info().1 + 1;
82 let mut block = Block {
83 header: BlockHeader { version: 0x20000000, prev_blockhash: node.best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: height, bits: 42, nonce: 42 },
86 for _ in 0..*node.network_chan_count.borrow() { // Make sure we don't end up with channels at the same short id by offsetting by chan_count
87 block.txdata.push(Transaction { version: 0, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: Vec::new() });
89 block.txdata.push((*tx).clone());
90 do_connect_block_without_consistency_checks(node, block, false);
92 /// Mine the given transaction at the given height, mining blocks as required to build to that
95 /// Returns the SCID a channel confirmed in the given transaction will have, assuming the funding
96 /// output is the 1st output in the transaction.
97 pub fn confirm_transactions_at<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, txn: &[&Transaction], conf_height: u32) -> u64 {
98 let first_connect_height = node.best_block_info().1 + 1;
99 assert!(first_connect_height <= conf_height);
100 if conf_height > first_connect_height {
101 connect_blocks(node, conf_height - first_connect_height);
103 let mut txdata = Vec::new();
104 for _ in 0..*node.network_chan_count.borrow() { // Make sure we don't end up with channels at the same short id by offsetting by chan_count
105 txdata.push(Transaction { version: 0, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: Vec::new() });
108 txdata.push((*tx).clone());
110 let block = create_dummy_block(node.best_block_hash(), conf_height, txdata);
111 connect_block(node, &block);
112 scid_utils::scid_from_parts(conf_height as u64, block.txdata.len() as u64 - 1, 0).unwrap()
114 pub fn confirm_transaction_at<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, tx: &Transaction, conf_height: u32) -> u64 {
115 confirm_transactions_at(node, &[tx], conf_height)
118 /// The possible ways we may notify a ChannelManager of a new block
119 #[derive(Clone, Copy, Debug, PartialEq)]
120 pub enum ConnectStyle {
121 /// Calls `best_block_updated` first, detecting transactions in the block only after receiving
122 /// the header and height information.
124 /// The same as `BestBlockFirst`, however when we have multiple blocks to connect, we only
125 /// make a single `best_block_updated` call.
126 BestBlockFirstSkippingBlocks,
127 /// The same as `BestBlockFirst` when connecting blocks. During disconnection only
128 /// `transaction_unconfirmed` is called.
129 BestBlockFirstReorgsOnlyTip,
130 /// Calls `transactions_confirmed` first, detecting transactions in the block before updating
131 /// the header and height information.
133 /// The same as `TransactionsFirst`, however when we have multiple blocks to connect, we only
134 /// make a single `best_block_updated` call.
135 TransactionsFirstSkippingBlocks,
136 /// The same as `TransactionsFirst`, however when we have multiple blocks to connect, we only
137 /// make a single `best_block_updated` call. Further, we call `transactions_confirmed` multiple
138 /// times to ensure it's idempotent.
139 TransactionsDuplicativelyFirstSkippingBlocks,
140 /// The same as `TransactionsFirst`, however when we have multiple blocks to connect, we only
141 /// make a single `best_block_updated` call. Further, we call `transactions_confirmed` multiple
142 /// times to ensure it's idempotent.
143 HighlyRedundantTransactionsFirstSkippingBlocks,
144 /// The same as `TransactionsFirst` when connecting blocks. During disconnection only
145 /// `transaction_unconfirmed` is called.
146 TransactionsFirstReorgsOnlyTip,
147 /// Provides the full block via the `chain::Listen` interface. In the current code this is
148 /// equivalent to `TransactionsFirst` with some additional assertions.
153 pub fn skips_blocks(&self) -> bool {
155 ConnectStyle::BestBlockFirst => false,
156 ConnectStyle::BestBlockFirstSkippingBlocks => true,
157 ConnectStyle::BestBlockFirstReorgsOnlyTip => true,
158 ConnectStyle::TransactionsFirst => false,
159 ConnectStyle::TransactionsFirstSkippingBlocks => true,
160 ConnectStyle::TransactionsDuplicativelyFirstSkippingBlocks => true,
161 ConnectStyle::HighlyRedundantTransactionsFirstSkippingBlocks => true,
162 ConnectStyle::TransactionsFirstReorgsOnlyTip => true,
163 ConnectStyle::FullBlockViaListen => false,
167 pub fn updates_best_block_first(&self) -> bool {
169 ConnectStyle::BestBlockFirst => true,
170 ConnectStyle::BestBlockFirstSkippingBlocks => true,
171 ConnectStyle::BestBlockFirstReorgsOnlyTip => true,
172 ConnectStyle::TransactionsFirst => false,
173 ConnectStyle::TransactionsFirstSkippingBlocks => false,
174 ConnectStyle::TransactionsDuplicativelyFirstSkippingBlocks => false,
175 ConnectStyle::HighlyRedundantTransactionsFirstSkippingBlocks => false,
176 ConnectStyle::TransactionsFirstReorgsOnlyTip => false,
177 ConnectStyle::FullBlockViaListen => false,
181 fn random_style() -> ConnectStyle {
182 #[cfg(feature = "std")] {
183 use core::hash::{BuildHasher, Hasher};
184 // Get a random value using the only std API to do so - the DefaultHasher
185 let rand_val = std::collections::hash_map::RandomState::new().build_hasher().finish();
186 let res = match rand_val % 9 {
187 0 => ConnectStyle::BestBlockFirst,
188 1 => ConnectStyle::BestBlockFirstSkippingBlocks,
189 2 => ConnectStyle::BestBlockFirstReorgsOnlyTip,
190 3 => ConnectStyle::TransactionsFirst,
191 4 => ConnectStyle::TransactionsFirstSkippingBlocks,
192 5 => ConnectStyle::TransactionsDuplicativelyFirstSkippingBlocks,
193 6 => ConnectStyle::HighlyRedundantTransactionsFirstSkippingBlocks,
194 7 => ConnectStyle::TransactionsFirstReorgsOnlyTip,
195 8 => ConnectStyle::FullBlockViaListen,
198 eprintln!("Using Block Connection Style: {:?}", res);
201 #[cfg(not(feature = "std"))] {
202 ConnectStyle::FullBlockViaListen
207 pub fn create_dummy_header(prev_blockhash: BlockHash, time: u32) -> BlockHeader {
209 version: 0x2000_0000,
211 merkle_root: TxMerkleNode::all_zeros(),
218 pub fn create_dummy_block(prev_blockhash: BlockHash, time: u32, txdata: Vec<Transaction>) -> Block {
219 Block { header: create_dummy_header(prev_blockhash, time), txdata }
222 pub fn connect_blocks<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, depth: u32) -> BlockHash {
223 let skip_intermediaries = node.connect_style.borrow().skips_blocks();
225 let height = node.best_block_info().1 + 1;
226 let mut block = create_dummy_block(node.best_block_hash(), height, Vec::new());
229 let prev_blockhash = block.header.block_hash();
230 do_connect_block_with_consistency_checks(node, block, skip_intermediaries);
231 block = create_dummy_block(prev_blockhash, height + i, Vec::new());
233 let hash = block.header.block_hash();
234 do_connect_block_with_consistency_checks(node, block, false);
238 pub fn connect_block<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, block: &Block) {
239 do_connect_block_with_consistency_checks(node, block.clone(), false);
242 fn call_claimable_balances<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>) {
243 // Ensure `get_claimable_balances`' self-tests never panic
244 for funding_outpoint in node.chain_monitor.chain_monitor.list_monitors() {
245 node.chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances();
249 fn do_connect_block_with_consistency_checks<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, block: Block, skip_intermediaries: bool) {
250 call_claimable_balances(node);
251 do_connect_block_without_consistency_checks(node, block, skip_intermediaries);
252 call_claimable_balances(node);
253 node.node.test_process_background_events();
256 fn do_connect_block_without_consistency_checks<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, block: Block, skip_intermediaries: bool) {
257 let height = node.best_block_info().1 + 1;
258 #[cfg(feature = "std")] {
259 eprintln!("Connecting block using Block Connection Style: {:?}", *node.connect_style.borrow());
261 // Update the block internally before handing it over to LDK, to ensure our assertions regarding
262 // transaction broadcast are correct.
263 node.blocks.lock().unwrap().push((block.clone(), height));
264 if !skip_intermediaries {
265 let txdata: Vec<_> = block.txdata.iter().enumerate().collect();
266 match *node.connect_style.borrow() {
267 ConnectStyle::BestBlockFirst|ConnectStyle::BestBlockFirstSkippingBlocks|ConnectStyle::BestBlockFirstReorgsOnlyTip => {
268 node.chain_monitor.chain_monitor.best_block_updated(&block.header, height);
269 call_claimable_balances(node);
270 node.chain_monitor.chain_monitor.transactions_confirmed(&block.header, &txdata, height);
271 node.node.best_block_updated(&block.header, height);
272 node.node.transactions_confirmed(&block.header, &txdata, height);
274 ConnectStyle::TransactionsFirst|ConnectStyle::TransactionsFirstSkippingBlocks|
275 ConnectStyle::TransactionsDuplicativelyFirstSkippingBlocks|ConnectStyle::HighlyRedundantTransactionsFirstSkippingBlocks|
276 ConnectStyle::TransactionsFirstReorgsOnlyTip => {
277 if *node.connect_style.borrow() == ConnectStyle::HighlyRedundantTransactionsFirstSkippingBlocks {
278 let mut connections = Vec::new();
279 for (block, height) in node.blocks.lock().unwrap().iter() {
280 if !block.txdata.is_empty() {
281 // Reconnect all transactions we've ever seen to ensure transaction connection
282 // is *really* idempotent. This is a somewhat likely deployment for some
283 // esplora implementations of chain sync which try to reduce state and
284 // complexity as much as possible.
286 // Sadly we have to clone the block here to maintain lockorder. In the
287 // future we should consider Arc'ing the blocks to avoid this.
288 connections.push((block.clone(), *height));
291 for (old_block, height) in connections {
292 node.chain_monitor.chain_monitor.transactions_confirmed(&old_block.header,
293 &old_block.txdata.iter().enumerate().collect::<Vec<_>>(), height);
296 node.chain_monitor.chain_monitor.transactions_confirmed(&block.header, &txdata, height);
297 if *node.connect_style.borrow() == ConnectStyle::TransactionsDuplicativelyFirstSkippingBlocks {
298 node.chain_monitor.chain_monitor.transactions_confirmed(&block.header, &txdata, height);
300 call_claimable_balances(node);
301 node.chain_monitor.chain_monitor.best_block_updated(&block.header, height);
302 node.node.transactions_confirmed(&block.header, &txdata, height);
303 node.node.best_block_updated(&block.header, height);
305 ConnectStyle::FullBlockViaListen => {
306 node.chain_monitor.chain_monitor.block_connected(&block, height);
307 node.node.block_connected(&block, height);
312 for tx in &block.txdata {
313 for input in &tx.input {
314 node.wallet_source.remove_utxo(input.previous_output);
316 let wallet_script = node.wallet_source.get_change_script().unwrap();
317 for (idx, output) in tx.output.iter().enumerate() {
318 if output.script_pubkey == wallet_script {
319 let outpoint = bitcoin::OutPoint { txid: tx.txid(), vout: idx as u32 };
320 node.wallet_source.add_utxo(outpoint, output.value);
326 pub fn disconnect_blocks<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, count: u32) {
327 call_claimable_balances(node);
328 #[cfg(feature = "std")] {
329 eprintln!("Disconnecting {} blocks using Block Connection Style: {:?}", count, *node.connect_style.borrow());
332 let orig = node.blocks.lock().unwrap().pop().unwrap();
333 assert!(orig.1 > 0); // Cannot disconnect genesis
334 let prev = node.blocks.lock().unwrap().last().unwrap().clone();
336 match *node.connect_style.borrow() {
337 ConnectStyle::FullBlockViaListen => {
338 node.chain_monitor.chain_monitor.block_disconnected(&orig.0.header, orig.1);
339 Listen::block_disconnected(node.node, &orig.0.header, orig.1);
341 ConnectStyle::BestBlockFirstSkippingBlocks|ConnectStyle::TransactionsFirstSkippingBlocks|
342 ConnectStyle::HighlyRedundantTransactionsFirstSkippingBlocks|ConnectStyle::TransactionsDuplicativelyFirstSkippingBlocks => {
344 node.chain_monitor.chain_monitor.best_block_updated(&prev.0.header, prev.1);
345 node.node.best_block_updated(&prev.0.header, prev.1);
348 ConnectStyle::BestBlockFirstReorgsOnlyTip|ConnectStyle::TransactionsFirstReorgsOnlyTip => {
349 for tx in orig.0.txdata {
350 node.chain_monitor.chain_monitor.transaction_unconfirmed(&tx.txid());
351 node.node.transaction_unconfirmed(&tx.txid());
355 node.chain_monitor.chain_monitor.best_block_updated(&prev.0.header, prev.1);
356 node.node.best_block_updated(&prev.0.header, prev.1);
359 call_claimable_balances(node);
363 pub fn disconnect_all_blocks<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>) {
364 let count = node.blocks.lock().unwrap().len() as u32 - 1;
365 disconnect_blocks(node, count);
368 pub struct TestChanMonCfg {
369 pub tx_broadcaster: test_utils::TestBroadcaster,
370 pub fee_estimator: test_utils::TestFeeEstimator,
371 pub chain_source: test_utils::TestChainSource,
372 pub persister: test_utils::TestPersister,
373 pub logger: test_utils::TestLogger,
374 pub keys_manager: test_utils::TestKeysInterface,
375 pub scorer: RwLock<test_utils::TestScorer>,
378 pub struct NodeCfg<'a> {
379 pub chain_source: &'a test_utils::TestChainSource,
380 pub tx_broadcaster: &'a test_utils::TestBroadcaster,
381 pub fee_estimator: &'a test_utils::TestFeeEstimator,
382 pub router: test_utils::TestRouter<'a>,
383 pub chain_monitor: test_utils::TestChainMonitor<'a>,
384 pub keys_manager: &'a test_utils::TestKeysInterface,
385 pub logger: &'a test_utils::TestLogger,
386 pub network_graph: Arc<NetworkGraph<&'a test_utils::TestLogger>>,
387 pub node_seed: [u8; 32],
388 pub override_init_features: Rc<RefCell<Option<InitFeatures>>>,
391 type TestChannelManager<'node_cfg, 'chan_mon_cfg> = ChannelManager<
392 &'node_cfg TestChainMonitor<'chan_mon_cfg>,
393 &'chan_mon_cfg test_utils::TestBroadcaster,
394 &'node_cfg test_utils::TestKeysInterface,
395 &'node_cfg test_utils::TestKeysInterface,
396 &'node_cfg test_utils::TestKeysInterface,
397 &'chan_mon_cfg test_utils::TestFeeEstimator,
398 &'node_cfg test_utils::TestRouter<'chan_mon_cfg>,
399 &'chan_mon_cfg test_utils::TestLogger,
402 pub struct Node<'chan_man, 'node_cfg: 'chan_man, 'chan_mon_cfg: 'node_cfg> {
403 pub chain_source: &'chan_mon_cfg test_utils::TestChainSource,
404 pub tx_broadcaster: &'chan_mon_cfg test_utils::TestBroadcaster,
405 pub fee_estimator: &'chan_mon_cfg test_utils::TestFeeEstimator,
406 pub router: &'node_cfg test_utils::TestRouter<'chan_mon_cfg>,
407 pub chain_monitor: &'node_cfg test_utils::TestChainMonitor<'chan_mon_cfg>,
408 pub keys_manager: &'chan_mon_cfg test_utils::TestKeysInterface,
409 pub node: &'chan_man TestChannelManager<'node_cfg, 'chan_mon_cfg>,
410 pub network_graph: &'node_cfg NetworkGraph<&'chan_mon_cfg test_utils::TestLogger>,
411 pub gossip_sync: P2PGossipSync<&'node_cfg NetworkGraph<&'chan_mon_cfg test_utils::TestLogger>, &'chan_mon_cfg test_utils::TestChainSource, &'chan_mon_cfg test_utils::TestLogger>,
412 pub node_seed: [u8; 32],
413 pub network_payment_count: Rc<RefCell<u8>>,
414 pub network_chan_count: Rc<RefCell<u32>>,
415 pub logger: &'chan_mon_cfg test_utils::TestLogger,
416 pub blocks: Arc<Mutex<Vec<(Block, u32)>>>,
417 pub connect_style: Rc<RefCell<ConnectStyle>>,
418 pub override_init_features: Rc<RefCell<Option<InitFeatures>>>,
419 pub wallet_source: Arc<test_utils::TestWalletSource>,
420 pub bump_tx_handler: BumpTransactionEventHandler<
421 &'chan_mon_cfg test_utils::TestBroadcaster,
422 Arc<Wallet<Arc<test_utils::TestWalletSource>, &'chan_mon_cfg test_utils::TestLogger>>,
423 &'chan_mon_cfg test_utils::TestKeysInterface,
424 &'chan_mon_cfg test_utils::TestLogger,
427 #[cfg(feature = "std")]
428 impl<'a, 'b, 'c> std::panic::UnwindSafe for Node<'a, 'b, 'c> {}
429 #[cfg(feature = "std")]
430 impl<'a, 'b, 'c> std::panic::RefUnwindSafe for Node<'a, 'b, 'c> {}
431 impl<'a, 'b, 'c> Node<'a, 'b, 'c> {
432 pub fn best_block_hash(&self) -> BlockHash {
433 self.blocks.lock().unwrap().last().unwrap().0.block_hash()
435 pub fn best_block_info(&self) -> (BlockHash, u32) {
436 self.blocks.lock().unwrap().last().map(|(a, b)| (a.block_hash(), *b)).unwrap()
438 pub fn get_block_header(&self, height: u32) -> BlockHeader {
439 self.blocks.lock().unwrap()[height as usize].0.header
441 /// Changes the channel signer's availability for the specified peer and channel.
443 /// When `available` is set to `true`, the channel signer will behave normally. When set to
444 /// `false`, the channel signer will act like an off-line remote signer and will return `Err` for
445 /// several of the signing methods. Currently, only `get_per_commitment_point` and
446 /// `release_commitment_secret` are affected by this setting.
448 pub fn set_channel_signer_available(&self, peer_id: &PublicKey, chan_id: &ChannelId, available: bool) {
449 let per_peer_state = self.node.per_peer_state.read().unwrap();
450 let chan_lock = per_peer_state.get(peer_id).unwrap().lock().unwrap();
452 match chan_lock.channel_by_id.get(chan_id) {
453 Some(phase) => phase.context().get_signer(),
454 None => panic!("Couldn't find a channel with id {}", chan_id),
457 log_debug!(self.logger, "Setting channel signer for {} as available={}", chan_id, available);
458 signer.as_ecdsa().unwrap().set_available(available);
462 /// If we need an unsafe pointer to a `Node` (ie to reference it in a thread
463 /// pre-std::thread::scope), this provides that with `Sync`. Note that accessing some of the fields
464 /// in the `Node` are not safe to use (i.e. the ones behind an `Rc`), but that's left to the caller
466 pub struct NodePtr(pub *const Node<'static, 'static, 'static>);
468 pub fn from_node<'a, 'b: 'a, 'c: 'b>(node: &Node<'a, 'b, 'c>) -> Self {
469 Self((node as *const Node<'a, 'b, 'c>).cast())
472 unsafe impl Send for NodePtr {}
473 unsafe impl Sync for NodePtr {}
476 pub trait NodeHolder {
477 type CM: AChannelManager;
478 fn node(&self) -> &ChannelManager<
479 <Self::CM as AChannelManager>::M,
480 <Self::CM as AChannelManager>::T,
481 <Self::CM as AChannelManager>::ES,
482 <Self::CM as AChannelManager>::NS,
483 <Self::CM as AChannelManager>::SP,
484 <Self::CM as AChannelManager>::F,
485 <Self::CM as AChannelManager>::R,
486 <Self::CM as AChannelManager>::L>;
487 fn chain_monitor(&self) -> Option<&test_utils::TestChainMonitor>;
489 impl<H: NodeHolder> NodeHolder for &H {
491 fn node(&self) -> &ChannelManager<
492 <Self::CM as AChannelManager>::M,
493 <Self::CM as AChannelManager>::T,
494 <Self::CM as AChannelManager>::ES,
495 <Self::CM as AChannelManager>::NS,
496 <Self::CM as AChannelManager>::SP,
497 <Self::CM as AChannelManager>::F,
498 <Self::CM as AChannelManager>::R,
499 <Self::CM as AChannelManager>::L> { (*self).node() }
500 fn chain_monitor(&self) -> Option<&test_utils::TestChainMonitor> { (*self).chain_monitor() }
502 impl<'a, 'b: 'a, 'c: 'b> NodeHolder for Node<'a, 'b, 'c> {
503 type CM = TestChannelManager<'b, 'c>;
504 fn node(&self) -> &TestChannelManager<'b, 'c> { &self.node }
505 fn chain_monitor(&self) -> Option<&test_utils::TestChainMonitor> { Some(self.chain_monitor) }
508 impl<'a, 'b, 'c> Drop for Node<'a, 'b, 'c> {
511 // Check that we processed all pending events
512 let msg_events = self.node.get_and_clear_pending_msg_events();
513 if !msg_events.is_empty() {
514 panic!("Had excess message events on node {}: {:?}", self.logger.id, msg_events);
516 let events = self.node.get_and_clear_pending_events();
517 if !events.is_empty() {
518 panic!("Had excess events on node {}: {:?}", self.logger.id, events);
520 let added_monitors = self.chain_monitor.added_monitors.lock().unwrap().split_off(0);
521 if !added_monitors.is_empty() {
522 panic!("Had {} excess added monitors on node {}", added_monitors.len(), self.logger.id);
525 // Check that if we serialize the network graph, we can deserialize it again.
526 let network_graph = {
527 let mut w = test_utils::TestVecWriter(Vec::new());
528 self.network_graph.write(&mut w).unwrap();
529 let network_graph_deser = <NetworkGraph<_>>::read(&mut io::Cursor::new(&w.0), self.logger).unwrap();
530 assert!(network_graph_deser == *self.network_graph);
531 let gossip_sync = P2PGossipSync::new(
532 &network_graph_deser, Some(self.chain_source), self.logger
534 let mut chan_progress = 0;
536 let orig_announcements = self.gossip_sync.get_next_channel_announcement(chan_progress);
537 let deserialized_announcements = gossip_sync.get_next_channel_announcement(chan_progress);
538 assert!(orig_announcements == deserialized_announcements);
539 chan_progress = match orig_announcements {
540 Some(announcement) => announcement.0.contents.short_channel_id + 1,
544 let mut node_progress = None;
546 let orig_announcements = self.gossip_sync.get_next_node_announcement(node_progress.as_ref());
547 let deserialized_announcements = gossip_sync.get_next_node_announcement(node_progress.as_ref());
548 assert!(orig_announcements == deserialized_announcements);
549 node_progress = match orig_announcements {
550 Some(announcement) => Some(announcement.contents.node_id),
557 // Check that if we serialize and then deserialize all our channel monitors we get the
558 // same set of outputs to watch for on chain as we have now. Note that if we write
559 // tests that fully close channels and remove the monitors at some point this may break.
560 let feeest = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
561 let mut deserialized_monitors = Vec::new();
563 for outpoint in self.chain_monitor.chain_monitor.list_monitors() {
564 let mut w = test_utils::TestVecWriter(Vec::new());
565 self.chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut w).unwrap();
566 let (_, deserialized_monitor) = <(BlockHash, ChannelMonitor<TestChannelSigner>)>::read(
567 &mut io::Cursor::new(&w.0), (self.keys_manager, self.keys_manager)).unwrap();
568 deserialized_monitors.push(deserialized_monitor);
572 let broadcaster = test_utils::TestBroadcaster {
573 txn_broadcasted: Mutex::new(self.tx_broadcaster.txn_broadcasted.lock().unwrap().clone()),
574 blocks: Arc::new(Mutex::new(self.tx_broadcaster.blocks.lock().unwrap().clone())),
577 // Before using all the new monitors to check the watch outpoints, use the full set of
578 // them to ensure we can write and reload our ChannelManager.
580 let mut channel_monitors = HashMap::new();
581 for monitor in deserialized_monitors.iter_mut() {
582 channel_monitors.insert(monitor.get_funding_txo().0, monitor);
585 let scorer = RwLock::new(test_utils::TestScorer::new());
586 let mut w = test_utils::TestVecWriter(Vec::new());
587 self.node.write(&mut w).unwrap();
588 <(BlockHash, ChannelManager<&test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestRouter, &test_utils::TestLogger>)>::read(&mut io::Cursor::new(w.0), ChannelManagerReadArgs {
589 default_config: *self.node.get_current_default_configuration(),
590 entropy_source: self.keys_manager,
591 node_signer: self.keys_manager,
592 signer_provider: self.keys_manager,
593 fee_estimator: &test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
594 router: &test_utils::TestRouter::new(Arc::new(network_graph), &scorer),
595 chain_monitor: self.chain_monitor,
596 tx_broadcaster: &broadcaster,
597 logger: &self.logger,
602 let persister = test_utils::TestPersister::new();
603 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
604 let chain_monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &broadcaster, &self.logger, &feeest, &persister, &self.keys_manager);
605 for deserialized_monitor in deserialized_monitors.drain(..) {
606 if chain_monitor.watch_channel(deserialized_monitor.get_funding_txo().0, deserialized_monitor) != Ok(ChannelMonitorUpdateStatus::Completed) {
610 assert_eq!(*chain_source.watched_txn.unsafe_well_ordered_double_lock_self(), *self.chain_source.watched_txn.unsafe_well_ordered_double_lock_self());
611 assert_eq!(*chain_source.watched_outputs.unsafe_well_ordered_double_lock_self(), *self.chain_source.watched_outputs.unsafe_well_ordered_double_lock_self());
616 pub fn create_chan_between_nodes<'a, 'b, 'c: 'd, 'd>(node_a: &'a Node<'b, 'c, 'd>, node_b: &'a Node<'b, 'c, 'd>) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, ChannelId, Transaction) {
617 create_chan_between_nodes_with_value(node_a, node_b, 100000, 10001)
620 pub fn create_chan_between_nodes_with_value<'a, 'b, 'c: 'd, 'd>(node_a: &'a Node<'b, 'c, 'd>, node_b: &'a Node<'b, 'c, 'd>, channel_value: u64, push_msat: u64) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, ChannelId, Transaction) {
621 let (channel_ready, channel_id, tx) = create_chan_between_nodes_with_value_a(node_a, node_b, channel_value, push_msat);
622 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(node_a, node_b, &channel_ready);
623 (announcement, as_update, bs_update, channel_id, tx)
626 /// Gets an RAA and CS which were sent in response to a commitment update
627 pub fn get_revoke_commit_msgs<CM: AChannelManager, H: NodeHolder<CM=CM>>(node: &H, recipient: &PublicKey) -> (msgs::RevokeAndACK, msgs::CommitmentSigned) {
628 let events = node.node().get_and_clear_pending_msg_events();
629 assert_eq!(events.len(), 2);
631 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
632 assert_eq!(node_id, recipient);
635 _ => panic!("Unexpected event"),
637 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
638 assert_eq!(node_id, recipient);
639 assert!(updates.update_add_htlcs.is_empty());
640 assert!(updates.update_fulfill_htlcs.is_empty());
641 assert!(updates.update_fail_htlcs.is_empty());
642 assert!(updates.update_fail_malformed_htlcs.is_empty());
643 assert!(updates.update_fee.is_none());
644 updates.commitment_signed.clone()
646 _ => panic!("Unexpected event"),
651 /// Gets an RAA and CS which were sent in response to a commitment update
653 /// Don't use this, use the identically-named function instead.
654 macro_rules! get_revoke_commit_msgs {
655 ($node: expr, $node_id: expr) => {
656 $crate::ln::functional_test_utils::get_revoke_commit_msgs(&$node, &$node_id)
660 /// Get an specific event message from the pending events queue.
662 macro_rules! get_event_msg {
663 ($node: expr, $event_type: path, $node_id: expr) => {
665 let events = $node.node.get_and_clear_pending_msg_events();
666 assert_eq!(events.len(), 1);
668 $event_type { ref node_id, ref msg } => {
669 assert_eq!(*node_id, $node_id);
672 _ => panic!("Unexpected event"),
678 /// Get an error message from the pending events queue.
679 pub fn get_err_msg(node: &Node, recipient: &PublicKey) -> msgs::ErrorMessage {
680 let events = node.node.get_and_clear_pending_msg_events();
681 assert_eq!(events.len(), 1);
683 MessageSendEvent::HandleError {
684 action: msgs::ErrorAction::SendErrorMessage { ref msg }, ref node_id
686 assert_eq!(node_id, recipient);
689 MessageSendEvent::HandleError {
690 action: msgs::ErrorAction::DisconnectPeer { ref msg }, ref node_id
692 assert_eq!(node_id, recipient);
693 msg.as_ref().unwrap().clone()
695 _ => panic!("Unexpected event"),
699 /// Get a specific event from the pending events queue.
701 macro_rules! get_event {
702 ($node: expr, $event_type: path) => {
704 let mut events = $node.node.get_and_clear_pending_events();
705 assert_eq!(events.len(), 1);
706 let ev = events.pop().unwrap();
708 $event_type { .. } => {
711 _ => panic!("Unexpected event"),
717 /// Gets an UpdateHTLCs MessageSendEvent
718 pub fn get_htlc_update_msgs(node: &Node, recipient: &PublicKey) -> msgs::CommitmentUpdate {
719 let events = node.node.get_and_clear_pending_msg_events();
720 assert_eq!(events.len(), 1);
722 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
723 assert_eq!(node_id, recipient);
726 _ => panic!("Unexpected event"),
731 /// Gets an UpdateHTLCs MessageSendEvent
733 /// Don't use this, use the identically-named function instead.
734 macro_rules! get_htlc_update_msgs {
735 ($node: expr, $node_id: expr) => {
736 $crate::ln::functional_test_utils::get_htlc_update_msgs(&$node, &$node_id)
740 /// Fetches the first `msg_event` to the passed `node_id` in the passed `msg_events` vec.
741 /// Returns the `msg_event`.
743 /// Note that even though `BroadcastChannelAnnouncement` and `BroadcastChannelUpdate`
744 /// `msg_events` are stored under specific peers, this function does not fetch such `msg_events` as
745 /// such messages are intended to all peers.
746 pub fn remove_first_msg_event_to_node(msg_node_id: &PublicKey, msg_events: &mut Vec<MessageSendEvent>) -> MessageSendEvent {
747 let ev_index = msg_events.iter().position(|e| { match e {
748 MessageSendEvent::SendAcceptChannel { node_id, .. } => {
749 node_id == msg_node_id
751 MessageSendEvent::SendOpenChannel { node_id, .. } => {
752 node_id == msg_node_id
754 MessageSendEvent::SendFundingCreated { node_id, .. } => {
755 node_id == msg_node_id
757 MessageSendEvent::SendFundingSigned { node_id, .. } => {
758 node_id == msg_node_id
760 MessageSendEvent::SendChannelReady { node_id, .. } => {
761 node_id == msg_node_id
763 MessageSendEvent::SendAnnouncementSignatures { node_id, .. } => {
764 node_id == msg_node_id
766 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
767 node_id == msg_node_id
769 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
770 node_id == msg_node_id
772 MessageSendEvent::SendClosingSigned { node_id, .. } => {
773 node_id == msg_node_id
775 MessageSendEvent::SendShutdown { node_id, .. } => {
776 node_id == msg_node_id
778 MessageSendEvent::SendChannelReestablish { node_id, .. } => {
779 node_id == msg_node_id
781 MessageSendEvent::SendChannelAnnouncement { node_id, .. } => {
782 node_id == msg_node_id
784 MessageSendEvent::BroadcastChannelAnnouncement { .. } => {
787 MessageSendEvent::BroadcastChannelUpdate { .. } => {
790 MessageSendEvent::BroadcastNodeAnnouncement { .. } => {
793 MessageSendEvent::SendChannelUpdate { node_id, .. } => {
794 node_id == msg_node_id
796 MessageSendEvent::HandleError { node_id, .. } => {
797 node_id == msg_node_id
799 MessageSendEvent::SendChannelRangeQuery { node_id, .. } => {
800 node_id == msg_node_id
802 MessageSendEvent::SendShortIdsQuery { node_id, .. } => {
803 node_id == msg_node_id
805 MessageSendEvent::SendReplyChannelRange { node_id, .. } => {
806 node_id == msg_node_id
808 MessageSendEvent::SendGossipTimestampFilter { node_id, .. } => {
809 node_id == msg_node_id
811 MessageSendEvent::SendAcceptChannelV2 { node_id, .. } => {
812 node_id == msg_node_id
814 MessageSendEvent::SendOpenChannelV2 { node_id, .. } => {
815 node_id == msg_node_id
817 MessageSendEvent::SendTxAddInput { node_id, .. } => {
818 node_id == msg_node_id
820 MessageSendEvent::SendTxAddOutput { node_id, .. } => {
821 node_id == msg_node_id
823 MessageSendEvent::SendTxRemoveInput { node_id, .. } => {
824 node_id == msg_node_id
826 MessageSendEvent::SendTxRemoveOutput { node_id, .. } => {
827 node_id == msg_node_id
829 MessageSendEvent::SendTxComplete { node_id, .. } => {
830 node_id == msg_node_id
832 MessageSendEvent::SendTxSignatures { node_id, .. } => {
833 node_id == msg_node_id
835 MessageSendEvent::SendTxInitRbf { node_id, .. } => {
836 node_id == msg_node_id
838 MessageSendEvent::SendTxAckRbf { node_id, .. } => {
839 node_id == msg_node_id
841 MessageSendEvent::SendTxAbort { node_id, .. } => {
842 node_id == msg_node_id
845 if ev_index.is_some() {
846 msg_events.remove(ev_index.unwrap())
848 panic!("Couldn't find any MessageSendEvent to the node!")
853 macro_rules! get_channel_ref {
854 ($node: expr, $counterparty_node: expr, $per_peer_state_lock: ident, $peer_state_lock: ident, $channel_id: expr) => {
856 $per_peer_state_lock = $node.node.per_peer_state.read().unwrap();
857 $peer_state_lock = $per_peer_state_lock.get(&$counterparty_node.node.get_our_node_id()).unwrap().lock().unwrap();
858 $peer_state_lock.channel_by_id.get_mut(&$channel_id).unwrap()
864 macro_rules! get_feerate {
865 ($node: expr, $counterparty_node: expr, $channel_id: expr) => {
867 let mut per_peer_state_lock;
868 let mut peer_state_lock;
869 let phase = get_channel_ref!($node, $counterparty_node, per_peer_state_lock, peer_state_lock, $channel_id);
870 phase.context().get_feerate_sat_per_1000_weight()
876 macro_rules! get_channel_type_features {
877 ($node: expr, $counterparty_node: expr, $channel_id: expr) => {
879 let mut per_peer_state_lock;
880 let mut peer_state_lock;
881 let chan = get_channel_ref!($node, $counterparty_node, per_peer_state_lock, peer_state_lock, $channel_id);
882 chan.context().get_channel_type().clone()
887 /// Returns a channel monitor given a channel id, making some naive assumptions
889 macro_rules! get_monitor {
890 ($node: expr, $channel_id: expr) => {
892 use bitcoin::hashes::Hash;
893 let mut monitor = None;
894 // Assume funding vout is either 0 or 1 blindly
896 if let Ok(mon) = $node.chain_monitor.chain_monitor.get_monitor(
897 $crate::chain::transaction::OutPoint {
898 txid: bitcoin::Txid::from_slice(&$channel_id.0[..]).unwrap(), index
910 /// Returns any local commitment transactions for the channel.
912 macro_rules! get_local_commitment_txn {
913 ($node: expr, $channel_id: expr) => {
915 $crate::get_monitor!($node, $channel_id).unsafe_get_latest_holder_commitment_txn(&$node.logger)
920 /// Check the error from attempting a payment.
922 macro_rules! unwrap_send_err {
923 ($res: expr, $all_failed: expr, $type: pat, $check: expr) => {
925 &Err(PaymentSendFailure::AllFailedResendSafe(ref fails)) if $all_failed => {
926 assert_eq!(fails.len(), 1);
932 &Err(PaymentSendFailure::PartialFailure { ref results, .. }) if !$all_failed => {
933 assert_eq!(results.len(), 1);
935 Err($type) => { $check },
944 /// Check whether N channel monitor(s) have been added.
945 pub fn check_added_monitors<CM: AChannelManager, H: NodeHolder<CM=CM>>(node: &H, count: usize) {
946 if let Some(chain_monitor) = node.chain_monitor() {
947 let mut added_monitors = chain_monitor.added_monitors.lock().unwrap();
948 assert_eq!(added_monitors.len(), count);
949 added_monitors.clear();
953 /// Check whether N channel monitor(s) have been added.
955 /// Don't use this, use the identically-named function instead.
957 macro_rules! check_added_monitors {
958 ($node: expr, $count: expr) => {
959 $crate::ln::functional_test_utils::check_added_monitors(&$node, $count);
963 /// Checks whether the claimed HTLC for the specified path has the correct channel information.
965 /// This will panic if the path is empty, if the HTLC's channel ID is not actually a channel that
966 /// connects the final two nodes in the path, or if the `user_channel_id` is incorrect.
967 pub fn check_claimed_htlc_channel<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, path: &[&Node<'a, 'b, 'c>], htlc: &ClaimedHTLC) {
968 let mut nodes = path.iter().rev();
969 let dest = nodes.next().expect("path should have a destination").node;
970 let prev = nodes.next().unwrap_or(&origin_node).node;
971 let dest_channels = dest.list_channels();
972 let ch = dest_channels.iter().find(|ch| ch.channel_id == htlc.channel_id)
973 .expect("HTLC's channel should be one of destination node's channels");
974 assert_eq!(htlc.user_channel_id, ch.user_channel_id);
975 assert_eq!(ch.counterparty.node_id, prev.get_our_node_id());
978 pub fn _reload_node<'a, 'b, 'c>(node: &'a Node<'a, 'b, 'c>, default_config: UserConfig, chanman_encoded: &[u8], monitors_encoded: &[&[u8]]) -> TestChannelManager<'b, 'c> {
979 let mut monitors_read = Vec::with_capacity(monitors_encoded.len());
980 for encoded in monitors_encoded {
981 let mut monitor_read = &encoded[..];
982 let (_, monitor) = <(BlockHash, ChannelMonitor<TestChannelSigner>)>
983 ::read(&mut monitor_read, (node.keys_manager, node.keys_manager)).unwrap();
984 assert!(monitor_read.is_empty());
985 monitors_read.push(monitor);
988 let mut node_read = &chanman_encoded[..];
989 let (_, node_deserialized) = {
990 let mut channel_monitors = HashMap::new();
991 for monitor in monitors_read.iter_mut() {
992 assert!(channel_monitors.insert(monitor.get_funding_txo().0, monitor).is_none());
994 <(BlockHash, TestChannelManager<'b, 'c>)>::read(&mut node_read, ChannelManagerReadArgs {
996 entropy_source: node.keys_manager,
997 node_signer: node.keys_manager,
998 signer_provider: node.keys_manager,
999 fee_estimator: node.fee_estimator,
1000 router: node.router,
1001 chain_monitor: node.chain_monitor,
1002 tx_broadcaster: node.tx_broadcaster,
1003 logger: node.logger,
1007 assert!(node_read.is_empty());
1009 for monitor in monitors_read.drain(..) {
1010 assert_eq!(node.chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor),
1011 Ok(ChannelMonitorUpdateStatus::Completed));
1012 check_added_monitors!(node, 1);
1019 macro_rules! reload_node {
1020 ($node: expr, $new_config: expr, $chanman_encoded: expr, $monitors_encoded: expr, $persister: ident, $new_chain_monitor: ident, $new_channelmanager: ident) => {
1021 let chanman_encoded = $chanman_encoded;
1023 $persister = test_utils::TestPersister::new();
1024 $new_chain_monitor = test_utils::TestChainMonitor::new(Some($node.chain_source), $node.tx_broadcaster.clone(), $node.logger, $node.fee_estimator, &$persister, &$node.keys_manager);
1025 $node.chain_monitor = &$new_chain_monitor;
1027 $new_channelmanager = _reload_node(&$node, $new_config, &chanman_encoded, $monitors_encoded);
1028 $node.node = &$new_channelmanager;
1030 ($node: expr, $chanman_encoded: expr, $monitors_encoded: expr, $persister: ident, $new_chain_monitor: ident, $new_channelmanager: ident) => {
1031 reload_node!($node, $crate::util::config::UserConfig::default(), $chanman_encoded, $monitors_encoded, $persister, $new_chain_monitor, $new_channelmanager);
1035 pub fn create_funding_transaction<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>,
1036 expected_counterparty_node_id: &PublicKey, expected_chan_value: u64, expected_user_chan_id: u128)
1037 -> (ChannelId, Transaction, OutPoint)
1039 internal_create_funding_transaction(node, expected_counterparty_node_id, expected_chan_value, expected_user_chan_id, false)
1042 pub fn create_coinbase_funding_transaction<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>,
1043 expected_counterparty_node_id: &PublicKey, expected_chan_value: u64, expected_user_chan_id: u128)
1044 -> (ChannelId, Transaction, OutPoint)
1046 internal_create_funding_transaction(node, expected_counterparty_node_id, expected_chan_value, expected_user_chan_id, true)
1049 fn internal_create_funding_transaction<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>,
1050 expected_counterparty_node_id: &PublicKey, expected_chan_value: u64, expected_user_chan_id: u128,
1051 coinbase: bool) -> (ChannelId, Transaction, OutPoint) {
1052 let chan_id = *node.network_chan_count.borrow();
1054 let events = node.node.get_and_clear_pending_events();
1055 assert_eq!(events.len(), 1);
1057 Event::FundingGenerationReady { ref temporary_channel_id, ref counterparty_node_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
1058 assert_eq!(counterparty_node_id, expected_counterparty_node_id);
1059 assert_eq!(*channel_value_satoshis, expected_chan_value);
1060 assert_eq!(user_channel_id, expected_user_chan_id);
1062 let input = if coinbase {
1064 previous_output: bitcoin::OutPoint::null(),
1065 ..Default::default()
1071 let tx = Transaction { version: chan_id as i32, lock_time: PackedLockTime::ZERO, input, output: vec![TxOut {
1072 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
1074 let funding_outpoint = OutPoint { txid: tx.txid(), index: 0 };
1075 (*temporary_channel_id, tx, funding_outpoint)
1077 _ => panic!("Unexpected event"),
1081 pub fn sign_funding_transaction<'a, 'b, 'c>(node_a: &Node<'a, 'b, 'c>, node_b: &Node<'a, 'b, 'c>, channel_value: u64, expected_temporary_channel_id: ChannelId) -> Transaction {
1082 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(node_a, &node_b.node.get_our_node_id(), channel_value, 42);
1083 assert_eq!(temporary_channel_id, expected_temporary_channel_id);
1085 assert!(node_a.node.funding_transaction_generated(&temporary_channel_id, &node_b.node.get_our_node_id(), tx.clone()).is_ok());
1086 check_added_monitors!(node_a, 0);
1088 let funding_created_msg = get_event_msg!(node_a, MessageSendEvent::SendFundingCreated, node_b.node.get_our_node_id());
1089 assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
1090 node_b.node.handle_funding_created(&node_a.node.get_our_node_id(), &funding_created_msg);
1092 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
1093 assert_eq!(added_monitors.len(), 1);
1094 assert_eq!(added_monitors[0].0, funding_output);
1095 added_monitors.clear();
1097 expect_channel_pending_event(&node_b, &node_a.node.get_our_node_id());
1099 node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id()));
1101 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
1102 assert_eq!(added_monitors.len(), 1);
1103 assert_eq!(added_monitors[0].0, funding_output);
1104 added_monitors.clear();
1106 expect_channel_pending_event(&node_a, &node_b.node.get_our_node_id());
1108 let events_4 = node_a.node.get_and_clear_pending_events();
1109 assert_eq!(events_4.len(), 0);
1111 assert_eq!(node_a.tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1112 assert_eq!(node_a.tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
1113 node_a.tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1115 // Ensure that funding_transaction_generated is idempotent.
1116 assert!(node_a.node.funding_transaction_generated(&temporary_channel_id, &node_b.node.get_our_node_id(), tx.clone()).is_err());
1117 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
1118 check_added_monitors!(node_a, 0);
1123 // Receiver must have been initialized with manually_accept_inbound_channels set to true.
1124 pub fn open_zero_conf_channel<'a, 'b, 'c, 'd>(initiator: &'a Node<'b, 'c, 'd>, receiver: &'a Node<'b, 'c, 'd>, initiator_config: Option<UserConfig>) -> (bitcoin::Transaction, ChannelId) {
1125 let initiator_channels = initiator.node.list_usable_channels().len();
1126 let receiver_channels = receiver.node.list_usable_channels().len();
1128 initiator.node.create_channel(receiver.node.get_our_node_id(), 100_000, 10_001, 42, initiator_config).unwrap();
1129 let open_channel = get_event_msg!(initiator, MessageSendEvent::SendOpenChannel, receiver.node.get_our_node_id());
1131 receiver.node.handle_open_channel(&initiator.node.get_our_node_id(), &open_channel);
1132 let events = receiver.node.get_and_clear_pending_events();
1133 assert_eq!(events.len(), 1);
1135 Event::OpenChannelRequest { temporary_channel_id, .. } => {
1136 receiver.node.accept_inbound_channel_from_trusted_peer_0conf(&temporary_channel_id, &initiator.node.get_our_node_id(), 0).unwrap();
1138 _ => panic!("Unexpected event"),
1141 let accept_channel = get_event_msg!(receiver, MessageSendEvent::SendAcceptChannel, initiator.node.get_our_node_id());
1142 assert_eq!(accept_channel.minimum_depth, 0);
1143 initiator.node.handle_accept_channel(&receiver.node.get_our_node_id(), &accept_channel);
1145 let (temporary_channel_id, tx, _) = create_funding_transaction(&initiator, &receiver.node.get_our_node_id(), 100_000, 42);
1146 initiator.node.funding_transaction_generated(&temporary_channel_id, &receiver.node.get_our_node_id(), tx.clone()).unwrap();
1147 let funding_created = get_event_msg!(initiator, MessageSendEvent::SendFundingCreated, receiver.node.get_our_node_id());
1149 receiver.node.handle_funding_created(&initiator.node.get_our_node_id(), &funding_created);
1150 check_added_monitors!(receiver, 1);
1151 let bs_signed_locked = receiver.node.get_and_clear_pending_msg_events();
1152 assert_eq!(bs_signed_locked.len(), 2);
1153 let as_channel_ready;
1154 match &bs_signed_locked[0] {
1155 MessageSendEvent::SendFundingSigned { node_id, msg } => {
1156 assert_eq!(*node_id, initiator.node.get_our_node_id());
1157 initiator.node.handle_funding_signed(&receiver.node.get_our_node_id(), &msg);
1158 expect_channel_pending_event(&initiator, &receiver.node.get_our_node_id());
1159 expect_channel_pending_event(&receiver, &initiator.node.get_our_node_id());
1160 check_added_monitors!(initiator, 1);
1162 assert_eq!(initiator.tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1163 assert_eq!(initiator.tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0)[0], tx);
1165 as_channel_ready = get_event_msg!(initiator, MessageSendEvent::SendChannelReady, receiver.node.get_our_node_id());
1167 _ => panic!("Unexpected event"),
1169 match &bs_signed_locked[1] {
1170 MessageSendEvent::SendChannelReady { node_id, msg } => {
1171 assert_eq!(*node_id, initiator.node.get_our_node_id());
1172 initiator.node.handle_channel_ready(&receiver.node.get_our_node_id(), &msg);
1173 expect_channel_ready_event(&initiator, &receiver.node.get_our_node_id());
1175 _ => panic!("Unexpected event"),
1178 receiver.node.handle_channel_ready(&initiator.node.get_our_node_id(), &as_channel_ready);
1179 expect_channel_ready_event(&receiver, &initiator.node.get_our_node_id());
1181 let as_channel_update = get_event_msg!(initiator, MessageSendEvent::SendChannelUpdate, receiver.node.get_our_node_id());
1182 let bs_channel_update = get_event_msg!(receiver, MessageSendEvent::SendChannelUpdate, initiator.node.get_our_node_id());
1184 initiator.node.handle_channel_update(&receiver.node.get_our_node_id(), &bs_channel_update);
1185 receiver.node.handle_channel_update(&initiator.node.get_our_node_id(), &as_channel_update);
1187 assert_eq!(initiator.node.list_usable_channels().len(), initiator_channels + 1);
1188 assert_eq!(receiver.node.list_usable_channels().len(), receiver_channels + 1);
1190 (tx, as_channel_ready.channel_id)
1193 pub fn create_chan_between_nodes_with_value_init<'a, 'b, 'c>(node_a: &Node<'a, 'b, 'c>, node_b: &Node<'a, 'b, 'c>, channel_value: u64, push_msat: u64) -> Transaction {
1194 let create_chan_id = node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
1195 let open_channel_msg = get_event_msg!(node_a, MessageSendEvent::SendOpenChannel, node_b.node.get_our_node_id());
1196 assert_eq!(open_channel_msg.temporary_channel_id, create_chan_id);
1197 assert_eq!(node_a.node.list_channels().iter().find(|channel| channel.channel_id == create_chan_id).unwrap().user_channel_id, 42);
1198 node_b.node.handle_open_channel(&node_a.node.get_our_node_id(), &open_channel_msg);
1199 if node_b.node.get_current_default_configuration().manually_accept_inbound_channels {
1200 let events = node_b.node.get_and_clear_pending_events();
1201 assert_eq!(events.len(), 1);
1203 Event::OpenChannelRequest { temporary_channel_id, counterparty_node_id, .. } =>
1204 node_b.node.accept_inbound_channel(temporary_channel_id, counterparty_node_id, 42).unwrap(),
1205 _ => panic!("Unexpected event"),
1208 let accept_channel_msg = get_event_msg!(node_b, MessageSendEvent::SendAcceptChannel, node_a.node.get_our_node_id());
1209 assert_eq!(accept_channel_msg.temporary_channel_id, create_chan_id);
1210 node_a.node.handle_accept_channel(&node_b.node.get_our_node_id(), &accept_channel_msg);
1211 assert_ne!(node_b.node.list_channels().iter().find(|channel| channel.channel_id == create_chan_id).unwrap().user_channel_id, 0);
1213 sign_funding_transaction(node_a, node_b, channel_value, create_chan_id)
1216 pub fn create_chan_between_nodes_with_value_confirm_first<'a, 'b, 'c, 'd>(node_recv: &'a Node<'b, 'c, 'c>, node_conf: &'a Node<'b, 'c, 'd>, tx: &Transaction, conf_height: u32) {
1217 confirm_transaction_at(node_conf, tx, conf_height);
1218 connect_blocks(node_conf, CHAN_CONFIRM_DEPTH - 1);
1219 node_recv.node.handle_channel_ready(&node_conf.node.get_our_node_id(), &get_event_msg!(node_conf, MessageSendEvent::SendChannelReady, node_recv.node.get_our_node_id()));
1222 pub fn create_chan_between_nodes_with_value_confirm_second<'a, 'b, 'c>(node_recv: &Node<'a, 'b, 'c>, node_conf: &Node<'a, 'b, 'c>) -> ((msgs::ChannelReady, msgs::AnnouncementSignatures), ChannelId) {
1224 let events_6 = node_conf.node.get_and_clear_pending_msg_events();
1225 assert_eq!(events_6.len(), 3);
1226 let announcement_sigs_idx = if let MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } = events_6[1] {
1227 assert_eq!(*node_id, node_recv.node.get_our_node_id());
1229 } else if let MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } = events_6[2] {
1230 assert_eq!(*node_id, node_recv.node.get_our_node_id());
1232 } else { panic!("Unexpected event: {:?}", events_6[1]); };
1233 ((match events_6[0] {
1234 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
1235 channel_id = msg.channel_id.clone();
1236 assert_eq!(*node_id, node_recv.node.get_our_node_id());
1239 _ => panic!("Unexpected event"),
1240 }, match events_6[announcement_sigs_idx] {
1241 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
1242 assert_eq!(*node_id, node_recv.node.get_our_node_id());
1245 _ => panic!("Unexpected event"),
1249 pub fn create_chan_between_nodes_with_value_confirm<'a, 'b, 'c: 'd, 'd>(node_a: &'a Node<'b, 'c, 'd>, node_b: &'a Node<'b, 'c, 'd>, tx: &Transaction) -> ((msgs::ChannelReady, msgs::AnnouncementSignatures), ChannelId) {
1250 let conf_height = core::cmp::max(node_a.best_block_info().1 + 1, node_b.best_block_info().1 + 1);
1251 create_chan_between_nodes_with_value_confirm_first(node_a, node_b, tx, conf_height);
1252 confirm_transaction_at(node_a, tx, conf_height);
1253 connect_blocks(node_a, CHAN_CONFIRM_DEPTH - 1);
1254 expect_channel_ready_event(&node_a, &node_b.node.get_our_node_id());
1255 create_chan_between_nodes_with_value_confirm_second(node_b, node_a)
1258 pub fn create_chan_between_nodes_with_value_a<'a, 'b, 'c: 'd, 'd>(node_a: &'a Node<'b, 'c, 'd>, node_b: &'a Node<'b, 'c, 'd>, channel_value: u64, push_msat: u64) -> ((msgs::ChannelReady, msgs::AnnouncementSignatures), ChannelId, Transaction) {
1259 let tx = create_chan_between_nodes_with_value_init(node_a, node_b, channel_value, push_msat);
1260 let (msgs, chan_id) = create_chan_between_nodes_with_value_confirm(node_a, node_b, &tx);
1264 pub fn create_chan_between_nodes_with_value_b<'a, 'b, 'c>(node_a: &Node<'a, 'b, 'c>, node_b: &Node<'a, 'b, 'c>, as_funding_msgs: &(msgs::ChannelReady, msgs::AnnouncementSignatures)) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate) {
1265 node_b.node.handle_channel_ready(&node_a.node.get_our_node_id(), &as_funding_msgs.0);
1266 let bs_announcement_sigs = get_event_msg!(node_b, MessageSendEvent::SendAnnouncementSignatures, node_a.node.get_our_node_id());
1267 node_b.node.handle_announcement_signatures(&node_a.node.get_our_node_id(), &as_funding_msgs.1);
1269 let events_7 = node_b.node.get_and_clear_pending_msg_events();
1270 assert_eq!(events_7.len(), 1);
1271 let (announcement, bs_update) = match events_7[0] {
1272 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
1273 (msg, update_msg.clone().unwrap())
1275 _ => panic!("Unexpected event"),
1278 node_a.node.handle_announcement_signatures(&node_b.node.get_our_node_id(), &bs_announcement_sigs);
1279 let events_8 = node_a.node.get_and_clear_pending_msg_events();
1280 assert_eq!(events_8.len(), 1);
1281 let as_update = match events_8[0] {
1282 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
1283 assert!(*announcement == *msg);
1284 let update_msg = update_msg.clone().unwrap();
1285 assert_eq!(update_msg.contents.short_channel_id, announcement.contents.short_channel_id);
1286 assert_eq!(update_msg.contents.short_channel_id, bs_update.contents.short_channel_id);
1289 _ => panic!("Unexpected event"),
1292 *node_a.network_chan_count.borrow_mut() += 1;
1294 expect_channel_ready_event(&node_b, &node_a.node.get_our_node_id());
1295 ((*announcement).clone(), as_update, bs_update)
1298 pub fn create_announced_chan_between_nodes<'a, 'b, 'c: 'd, 'd>(nodes: &'a Vec<Node<'b, 'c, 'd>>, a: usize, b: usize) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, ChannelId, Transaction) {
1299 create_announced_chan_between_nodes_with_value(nodes, a, b, 100000, 10001)
1302 pub fn create_announced_chan_between_nodes_with_value<'a, 'b, 'c: 'd, 'd>(nodes: &'a Vec<Node<'b, 'c, 'd>>, a: usize, b: usize, channel_value: u64, push_msat: u64) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, ChannelId, Transaction) {
1303 let chan_announcement = create_chan_between_nodes_with_value(&nodes[a], &nodes[b], channel_value, push_msat);
1304 update_nodes_with_chan_announce(nodes, a, b, &chan_announcement.0, &chan_announcement.1, &chan_announcement.2);
1305 (chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
1308 pub fn create_unannounced_chan_between_nodes_with_value<'a, 'b, 'c, 'd>(nodes: &'a Vec<Node<'b, 'c, 'd>>, a: usize, b: usize, channel_value: u64, push_msat: u64) -> (msgs::ChannelReady, Transaction) {
1309 let mut no_announce_cfg = test_default_channel_config();
1310 no_announce_cfg.channel_handshake_config.announced_channel = false;
1311 nodes[a].node.create_channel(nodes[b].node.get_our_node_id(), channel_value, push_msat, 42, Some(no_announce_cfg)).unwrap();
1312 let open_channel = get_event_msg!(nodes[a], MessageSendEvent::SendOpenChannel, nodes[b].node.get_our_node_id());
1313 nodes[b].node.handle_open_channel(&nodes[a].node.get_our_node_id(), &open_channel);
1314 let accept_channel = get_event_msg!(nodes[b], MessageSendEvent::SendAcceptChannel, nodes[a].node.get_our_node_id());
1315 nodes[a].node.handle_accept_channel(&nodes[b].node.get_our_node_id(), &accept_channel);
1317 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[a], &nodes[b].node.get_our_node_id(), channel_value, 42);
1318 nodes[a].node.funding_transaction_generated(&temporary_channel_id, &nodes[b].node.get_our_node_id(), tx.clone()).unwrap();
1319 nodes[b].node.handle_funding_created(&nodes[a].node.get_our_node_id(), &get_event_msg!(nodes[a], MessageSendEvent::SendFundingCreated, nodes[b].node.get_our_node_id()));
1320 check_added_monitors!(nodes[b], 1);
1322 let cs_funding_signed = get_event_msg!(nodes[b], MessageSendEvent::SendFundingSigned, nodes[a].node.get_our_node_id());
1323 expect_channel_pending_event(&nodes[b], &nodes[a].node.get_our_node_id());
1325 nodes[a].node.handle_funding_signed(&nodes[b].node.get_our_node_id(), &cs_funding_signed);
1326 expect_channel_pending_event(&nodes[a], &nodes[b].node.get_our_node_id());
1327 check_added_monitors!(nodes[a], 1);
1329 assert_eq!(nodes[a].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1330 assert_eq!(nodes[a].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
1331 nodes[a].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1333 let conf_height = core::cmp::max(nodes[a].best_block_info().1 + 1, nodes[b].best_block_info().1 + 1);
1334 confirm_transaction_at(&nodes[a], &tx, conf_height);
1335 connect_blocks(&nodes[a], CHAN_CONFIRM_DEPTH - 1);
1336 confirm_transaction_at(&nodes[b], &tx, conf_height);
1337 connect_blocks(&nodes[b], CHAN_CONFIRM_DEPTH - 1);
1338 let as_channel_ready = get_event_msg!(nodes[a], MessageSendEvent::SendChannelReady, nodes[b].node.get_our_node_id());
1339 nodes[a].node.handle_channel_ready(&nodes[b].node.get_our_node_id(), &get_event_msg!(nodes[b], MessageSendEvent::SendChannelReady, nodes[a].node.get_our_node_id()));
1340 expect_channel_ready_event(&nodes[a], &nodes[b].node.get_our_node_id());
1341 let as_update = get_event_msg!(nodes[a], MessageSendEvent::SendChannelUpdate, nodes[b].node.get_our_node_id());
1342 nodes[b].node.handle_channel_ready(&nodes[a].node.get_our_node_id(), &as_channel_ready);
1343 expect_channel_ready_event(&nodes[b], &nodes[a].node.get_our_node_id());
1344 let bs_update = get_event_msg!(nodes[b], MessageSendEvent::SendChannelUpdate, nodes[a].node.get_our_node_id());
1346 nodes[a].node.handle_channel_update(&nodes[b].node.get_our_node_id(), &bs_update);
1347 nodes[b].node.handle_channel_update(&nodes[a].node.get_our_node_id(), &as_update);
1349 let mut found_a = false;
1350 for chan in nodes[a].node.list_usable_channels() {
1351 if chan.channel_id == as_channel_ready.channel_id {
1354 assert!(!chan.is_public);
1359 let mut found_b = false;
1360 for chan in nodes[b].node.list_usable_channels() {
1361 if chan.channel_id == as_channel_ready.channel_id {
1364 assert!(!chan.is_public);
1369 (as_channel_ready, tx)
1372 pub fn update_nodes_with_chan_announce<'a, 'b, 'c, 'd>(nodes: &'a Vec<Node<'b, 'c, 'd>>, a: usize, b: usize, ann: &msgs::ChannelAnnouncement, upd_1: &msgs::ChannelUpdate, upd_2: &msgs::ChannelUpdate) {
1374 assert!(node.gossip_sync.handle_channel_announcement(ann).unwrap());
1375 node.gossip_sync.handle_channel_update(upd_1).unwrap();
1376 node.gossip_sync.handle_channel_update(upd_2).unwrap();
1378 // Note that channel_updates are also delivered to ChannelManagers to ensure we have
1379 // forwarding info for local channels even if its not accepted in the network graph.
1380 node.node.handle_channel_update(&nodes[a].node.get_our_node_id(), &upd_1);
1381 node.node.handle_channel_update(&nodes[b].node.get_our_node_id(), &upd_2);
1385 pub fn do_check_spends<F: Fn(&bitcoin::blockdata::transaction::OutPoint) -> Option<TxOut>>(tx: &Transaction, get_output: F) {
1386 for outp in tx.output.iter() {
1387 assert!(outp.value >= outp.script_pubkey.dust_value().to_sat(), "Spending tx output didn't meet dust limit");
1389 let mut total_value_in = 0;
1390 for input in tx.input.iter() {
1391 total_value_in += get_output(&input.previous_output).unwrap().value;
1393 let mut total_value_out = 0;
1394 for output in tx.output.iter() {
1395 total_value_out += output.value;
1397 let min_fee = (tx.weight() as u64 + 3) / 4; // One sat per vbyte (ie per weight/4, rounded up)
1398 // Input amount - output amount = fee, so check that out + min_fee is smaller than input
1399 assert!(total_value_out + min_fee <= total_value_in);
1400 tx.verify(get_output).unwrap();
1404 macro_rules! check_spends {
1405 ($tx: expr, $($spends_txn: expr),*) => {
1408 for outp in $spends_txn.output.iter() {
1409 assert!(outp.value >= outp.script_pubkey.dust_value().to_sat(), "Input tx output didn't meet dust limit");
1412 let get_output = |out_point: &bitcoin::blockdata::transaction::OutPoint| {
1414 if out_point.txid == $spends_txn.txid() {
1415 return $spends_txn.output.get(out_point.vout as usize).cloned()
1420 $crate::ln::functional_test_utils::do_check_spends(&$tx, get_output);
1425 macro_rules! get_closing_signed_broadcast {
1426 ($node: expr, $dest_pubkey: expr) => {
1428 let events = $node.get_and_clear_pending_msg_events();
1429 assert!(events.len() == 1 || events.len() == 2);
1430 (match events[events.len() - 1] {
1431 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
1432 assert_eq!(msg.contents.flags & 2, 2);
1435 _ => panic!("Unexpected event"),
1436 }, if events.len() == 2 {
1438 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
1439 assert_eq!(*node_id, $dest_pubkey);
1442 _ => panic!("Unexpected event"),
1450 macro_rules! check_warn_msg {
1451 ($node: expr, $recipient_node_id: expr, $chan_id: expr) => {{
1452 let msg_events = $node.node.get_and_clear_pending_msg_events();
1453 assert_eq!(msg_events.len(), 1);
1454 match msg_events[0] {
1455 MessageSendEvent::HandleError { action: ErrorAction::SendWarningMessage { ref msg, log_level: _ }, node_id } => {
1456 assert_eq!(node_id, $recipient_node_id);
1457 assert_eq!(msg.channel_id, $chan_id);
1460 _ => panic!("Unexpected event"),
1465 /// Check that a channel's closing channel update has been broadcasted, and optionally
1466 /// check whether an error message event has occurred.
1467 pub fn check_closed_broadcast(node: &Node, num_channels: usize, with_error_msg: bool) -> Vec<msgs::ErrorMessage> {
1468 let msg_events = node.node.get_and_clear_pending_msg_events();
1469 assert_eq!(msg_events.len(), if with_error_msg { num_channels * 2 } else { num_channels });
1470 msg_events.into_iter().filter_map(|msg_event| {
1472 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
1473 assert_eq!(msg.contents.flags & 2, 2);
1476 MessageSendEvent::HandleError { action: msgs::ErrorAction::SendErrorMessage { msg }, node_id: _ } => {
1477 assert!(with_error_msg);
1478 // TODO: Check node_id
1481 MessageSendEvent::HandleError { action: msgs::ErrorAction::DisconnectPeer { msg }, node_id: _ } => {
1482 assert!(with_error_msg);
1483 // TODO: Check node_id
1486 _ => panic!("Unexpected event"),
1491 /// Check that a channel's closing channel update has been broadcasted, and optionally
1492 /// check whether an error message event has occurred.
1494 /// Don't use this, use the identically-named function instead.
1496 macro_rules! check_closed_broadcast {
1497 ($node: expr, $with_error_msg: expr) => {
1498 $crate::ln::functional_test_utils::check_closed_broadcast(&$node, 1, $with_error_msg).pop()
1502 /// Check that a channel's closing channel events has been issued
1503 pub fn check_closed_event(node: &Node, events_count: usize, expected_reason: ClosureReason, is_check_discard_funding: bool,
1504 expected_counterparty_node_ids: &[PublicKey], expected_channel_capacity: u64) {
1505 let events = node.node.get_and_clear_pending_events();
1506 assert_eq!(events.len(), events_count, "{:?}", events);
1507 let mut issues_discard_funding = false;
1508 for event in events {
1510 Event::ChannelClosed { ref reason, counterparty_node_id,
1511 channel_capacity_sats, .. } => {
1512 assert_eq!(*reason, expected_reason);
1513 assert!(expected_counterparty_node_ids.iter().any(|id| id == &counterparty_node_id.unwrap()));
1514 assert_eq!(channel_capacity_sats.unwrap(), expected_channel_capacity);
1516 Event::DiscardFunding { .. } => {
1517 issues_discard_funding = true;
1519 _ => panic!("Unexpected event"),
1522 assert_eq!(is_check_discard_funding, issues_discard_funding);
1525 /// Check that a channel's closing channel events has been issued
1527 /// Don't use this, use the identically-named function instead.
1529 macro_rules! check_closed_event {
1530 ($node: expr, $events: expr, $reason: expr, $counterparty_node_ids: expr, $channel_capacity: expr) => {
1531 check_closed_event!($node, $events, $reason, false, $counterparty_node_ids, $channel_capacity);
1533 ($node: expr, $events: expr, $reason: expr, $is_check_discard_funding: expr, $counterparty_node_ids: expr, $channel_capacity: expr) => {
1534 $crate::ln::functional_test_utils::check_closed_event(&$node, $events, $reason,
1535 $is_check_discard_funding, &$counterparty_node_ids, $channel_capacity);
1539 pub fn handle_bump_htlc_event(node: &Node, count: usize) {
1540 let events = node.chain_monitor.chain_monitor.get_and_clear_pending_events();
1541 assert_eq!(events.len(), count);
1542 for event in events {
1544 Event::BumpTransaction(bump_event) => {
1545 if let BumpTransactionEvent::HTLCResolution { .. } = &bump_event {}
1547 node.bump_tx_handler.handle_event(&bump_event);
1554 pub fn close_channel<'a, 'b, 'c>(outbound_node: &Node<'a, 'b, 'c>, inbound_node: &Node<'a, 'b, 'c>, channel_id: &ChannelId, funding_tx: Transaction, close_inbound_first: bool) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, Transaction) {
1555 let (node_a, broadcaster_a, struct_a) = if close_inbound_first { (&inbound_node.node, &inbound_node.tx_broadcaster, inbound_node) } else { (&outbound_node.node, &outbound_node.tx_broadcaster, outbound_node) };
1556 let (node_b, broadcaster_b, struct_b) = if close_inbound_first { (&outbound_node.node, &outbound_node.tx_broadcaster, outbound_node) } else { (&inbound_node.node, &inbound_node.tx_broadcaster, inbound_node) };
1559 node_a.close_channel(channel_id, &node_b.get_our_node_id()).unwrap();
1560 node_b.handle_shutdown(&node_a.get_our_node_id(), &get_event_msg!(struct_a, MessageSendEvent::SendShutdown, node_b.get_our_node_id()));
1562 let events_1 = node_b.get_and_clear_pending_msg_events();
1563 assert!(events_1.len() >= 1);
1564 let shutdown_b = match events_1[0] {
1565 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
1566 assert_eq!(node_id, &node_a.get_our_node_id());
1569 _ => panic!("Unexpected event"),
1572 let closing_signed_b = if !close_inbound_first {
1573 assert_eq!(events_1.len(), 1);
1576 Some(match events_1[1] {
1577 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
1578 assert_eq!(node_id, &node_a.get_our_node_id());
1581 _ => panic!("Unexpected event"),
1585 node_a.handle_shutdown(&node_b.get_our_node_id(), &shutdown_b);
1586 let (as_update, bs_update) = if close_inbound_first {
1587 assert!(node_a.get_and_clear_pending_msg_events().is_empty());
1588 node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap());
1590 node_b.handle_closing_signed(&node_a.get_our_node_id(), &get_event_msg!(struct_a, MessageSendEvent::SendClosingSigned, node_b.get_our_node_id()));
1591 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
1592 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
1593 let (bs_update, closing_signed_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
1595 node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap());
1596 let (as_update, none_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
1597 assert!(none_a.is_none());
1598 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
1599 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
1600 (as_update, bs_update)
1602 let closing_signed_a = get_event_msg!(struct_a, MessageSendEvent::SendClosingSigned, node_b.get_our_node_id());
1604 node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a);
1605 node_a.handle_closing_signed(&node_b.get_our_node_id(), &get_event_msg!(struct_b, MessageSendEvent::SendClosingSigned, node_a.get_our_node_id()));
1607 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
1608 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
1609 let (as_update, closing_signed_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
1611 node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap());
1612 let (bs_update, none_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
1613 assert!(none_b.is_none());
1614 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
1615 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
1616 (as_update, bs_update)
1618 assert_eq!(tx_a, tx_b);
1619 check_spends!(tx_a, funding_tx);
1621 (as_update, bs_update, tx_a)
1624 pub struct SendEvent {
1625 pub node_id: PublicKey,
1626 pub msgs: Vec<msgs::UpdateAddHTLC>,
1627 pub commitment_msg: msgs::CommitmentSigned,
1630 pub fn from_commitment_update(node_id: PublicKey, updates: msgs::CommitmentUpdate) -> SendEvent {
1631 assert!(updates.update_fulfill_htlcs.is_empty());
1632 assert!(updates.update_fail_htlcs.is_empty());
1633 assert!(updates.update_fail_malformed_htlcs.is_empty());
1634 assert!(updates.update_fee.is_none());
1635 SendEvent { node_id, msgs: updates.update_add_htlcs, commitment_msg: updates.commitment_signed }
1638 pub fn from_event(event: MessageSendEvent) -> SendEvent {
1640 MessageSendEvent::UpdateHTLCs { node_id, updates } => SendEvent::from_commitment_update(node_id, updates),
1641 _ => panic!("Unexpected event type!"),
1645 pub fn from_node<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>) -> SendEvent {
1646 let mut events = node.node.get_and_clear_pending_msg_events();
1647 assert_eq!(events.len(), 1);
1648 SendEvent::from_event(events.pop().unwrap())
1653 /// Don't use this, use the identically-named function instead.
1654 macro_rules! expect_pending_htlcs_forwardable_conditions {
1655 ($node: expr, $expected_failures: expr) => {
1656 $crate::ln::functional_test_utils::expect_pending_htlcs_forwardable_conditions($node.node.get_and_clear_pending_events(), &$expected_failures);
1661 macro_rules! expect_htlc_handling_failed_destinations {
1662 ($events: expr, $expected_failures: expr) => {{
1663 for event in $events {
1665 $crate::events::Event::PendingHTLCsForwardable { .. } => { },
1666 $crate::events::Event::HTLCHandlingFailed { ref failed_next_destination, .. } => {
1667 assert!($expected_failures.contains(&failed_next_destination))
1669 _ => panic!("Unexpected destination"),
1675 /// Checks that an [`Event::PendingHTLCsForwardable`] is available in the given events and, if
1676 /// there are any [`Event::HTLCHandlingFailed`] events their [`HTLCDestination`] is included in the
1677 /// `expected_failures` set.
1678 pub fn expect_pending_htlcs_forwardable_conditions(events: Vec<Event>, expected_failures: &[HTLCDestination]) {
1680 Event::PendingHTLCsForwardable { .. } => { },
1681 _ => panic!("Unexpected event {:?}", events),
1684 let count = expected_failures.len() + 1;
1685 assert_eq!(events.len(), count);
1687 if expected_failures.len() > 0 {
1688 expect_htlc_handling_failed_destinations!(events, expected_failures)
1693 /// Clears (and ignores) a PendingHTLCsForwardable event
1695 /// Don't use this, call [`expect_pending_htlcs_forwardable_conditions()`] with an empty failure
1697 macro_rules! expect_pending_htlcs_forwardable_ignore {
1699 $crate::ln::functional_test_utils::expect_pending_htlcs_forwardable_conditions($node.node.get_and_clear_pending_events(), &[]);
1704 /// Clears (and ignores) PendingHTLCsForwardable and HTLCHandlingFailed events
1706 /// Don't use this, call [`expect_pending_htlcs_forwardable_conditions()`] instead.
1707 macro_rules! expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore {
1708 ($node: expr, $expected_failures: expr) => {
1709 $crate::ln::functional_test_utils::expect_pending_htlcs_forwardable_conditions($node.node.get_and_clear_pending_events(), &$expected_failures);
1714 /// Handles a PendingHTLCsForwardable event
1715 macro_rules! expect_pending_htlcs_forwardable {
1717 $crate::ln::functional_test_utils::expect_pending_htlcs_forwardable_conditions($node.node.get_and_clear_pending_events(), &[]);
1718 $node.node.process_pending_htlc_forwards();
1720 // Ensure process_pending_htlc_forwards is idempotent.
1721 $node.node.process_pending_htlc_forwards();
1726 /// Handles a PendingHTLCsForwardable and HTLCHandlingFailed event
1727 macro_rules! expect_pending_htlcs_forwardable_and_htlc_handling_failed {
1728 ($node: expr, $expected_failures: expr) => {{
1729 $crate::ln::functional_test_utils::expect_pending_htlcs_forwardable_conditions($node.node.get_and_clear_pending_events(), &$expected_failures);
1730 $node.node.process_pending_htlc_forwards();
1732 // Ensure process_pending_htlc_forwards is idempotent.
1733 $node.node.process_pending_htlc_forwards();
1738 macro_rules! expect_pending_htlcs_forwardable_from_events {
1739 ($node: expr, $events: expr, $ignore: expr) => {{
1740 assert_eq!($events.len(), 1);
1742 Event::PendingHTLCsForwardable { .. } => { },
1743 _ => panic!("Unexpected event"),
1746 $node.node.process_pending_htlc_forwards();
1748 // Ensure process_pending_htlc_forwards is idempotent.
1749 $node.node.process_pending_htlc_forwards();
1755 /// Performs the "commitment signed dance" - the series of message exchanges which occur after a
1756 /// commitment update.
1757 macro_rules! commitment_signed_dance {
1758 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */) => {
1759 $crate::ln::functional_test_utils::do_commitment_signed_dance(&$node_a, &$node_b, &$commitment_signed, $fail_backwards, true);
1761 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */, true /* return last RAA */) => {
1762 $crate::ln::functional_test_utils::do_main_commitment_signed_dance(&$node_a, &$node_b, $fail_backwards)
1764 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */, false /* return extra message */, true /* return last RAA */) => {
1766 $crate::ln::functional_test_utils::check_added_monitors(&$node_a, 0);
1767 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
1768 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed);
1769 check_added_monitors(&$node_a, 1);
1770 let (extra_msg_option, bs_revoke_and_ack) = $crate::ln::functional_test_utils::do_main_commitment_signed_dance(&$node_a, &$node_b, $fail_backwards);
1771 assert!(extra_msg_option.is_none());
1775 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, false /* no extra message */, $incl_claim: expr) => {
1776 assert!($crate::ln::functional_test_utils::commitment_signed_dance_through_cp_raa(&$node_a, &$node_b, $fail_backwards, $incl_claim).is_none());
1778 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr) => {
1779 $crate::ln::functional_test_utils::do_commitment_signed_dance(&$node_a, &$node_b, &$commitment_signed, $fail_backwards, false);
1783 /// Runs the commitment_signed dance after the initial commitment_signed is delivered through to
1784 /// the initiator's `revoke_and_ack` response. i.e. [`do_main_commitment_signed_dance`] plus the
1785 /// `revoke_and_ack` response to it.
1787 /// An HTLC claim on one channel blocks the RAA channel monitor update for the outbound edge
1788 /// channel until the inbound edge channel preimage monitor update completes. Thus, when checking
1789 /// for channel monitor updates, we need to know if an `update_fulfill_htlc` was included in the
1790 /// the commitment we're exchanging. `includes_claim` provides that information.
1792 /// Returns any additional message `node_b` generated in addition to the `revoke_and_ack` response.
1793 pub fn commitment_signed_dance_through_cp_raa(node_a: &Node<'_, '_, '_>, node_b: &Node<'_, '_, '_>, fail_backwards: bool, includes_claim: bool) -> Option<MessageSendEvent> {
1794 let (extra_msg_option, bs_revoke_and_ack) = do_main_commitment_signed_dance(node_a, node_b, fail_backwards);
1795 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &bs_revoke_and_ack);
1796 check_added_monitors(node_a, if includes_claim { 0 } else { 1 });
1800 /// Does the main logic in the commitment_signed dance. After the first `commitment_signed` has
1801 /// been delivered, this method picks up and delivers the response `revoke_and_ack` and
1802 /// `commitment_signed`, returning the recipient's `revoke_and_ack` and any extra message it may
1804 pub fn do_main_commitment_signed_dance(node_a: &Node<'_, '_, '_>, node_b: &Node<'_, '_, '_>, fail_backwards: bool) -> (Option<MessageSendEvent>, msgs::RevokeAndACK) {
1805 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(node_a, node_b.node.get_our_node_id());
1806 check_added_monitors!(node_b, 0);
1807 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
1808 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &as_revoke_and_ack);
1809 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
1810 check_added_monitors!(node_b, 1);
1811 node_b.node.handle_commitment_signed(&node_a.node.get_our_node_id(), &as_commitment_signed);
1812 let (bs_revoke_and_ack, extra_msg_option) = {
1813 let mut events = node_b.node.get_and_clear_pending_msg_events();
1814 assert!(events.len() <= 2);
1815 let node_a_event = remove_first_msg_event_to_node(&node_a.node.get_our_node_id(), &mut events);
1816 (match node_a_event {
1817 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
1818 assert_eq!(*node_id, node_a.node.get_our_node_id());
1821 _ => panic!("Unexpected event"),
1822 }, events.get(0).map(|e| e.clone()))
1824 check_added_monitors!(node_b, 1);
1826 assert!(node_a.node.get_and_clear_pending_events().is_empty());
1827 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
1829 (extra_msg_option, bs_revoke_and_ack)
1832 /// Runs a full commitment_signed dance, delivering a commitment_signed, the responding
1833 /// `revoke_and_ack` and `commitment_signed`, and then the final `revoke_and_ack` response.
1835 /// If `skip_last_step` is unset, also checks for the payment failure update for the previous hop
1836 /// on failure or that no new messages are left over on success.
1837 pub fn do_commitment_signed_dance(node_a: &Node<'_, '_, '_>, node_b: &Node<'_, '_, '_>, commitment_signed: &msgs::CommitmentSigned, fail_backwards: bool, skip_last_step: bool) {
1838 check_added_monitors!(node_a, 0);
1839 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
1840 node_a.node.handle_commitment_signed(&node_b.node.get_our_node_id(), commitment_signed);
1841 check_added_monitors!(node_a, 1);
1843 // If this commitment signed dance was due to a claim, don't check for an RAA monitor update.
1844 let got_claim = node_a.node.test_raa_monitor_updates_held(node_b.node.get_our_node_id(), commitment_signed.channel_id);
1845 if fail_backwards { assert!(!got_claim); }
1846 commitment_signed_dance!(node_a, node_b, (), fail_backwards, true, false, got_claim);
1848 if skip_last_step { return; }
1851 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(node_a,
1852 vec![crate::events::HTLCDestination::NextHopChannel{ node_id: Some(node_b.node.get_our_node_id()), channel_id: commitment_signed.channel_id }]);
1853 check_added_monitors!(node_a, 1);
1855 let node_a_per_peer_state = node_a.node.per_peer_state.read().unwrap();
1856 let mut number_of_msg_events = 0;
1857 for (cp_id, peer_state_mutex) in node_a_per_peer_state.iter() {
1858 let peer_state = peer_state_mutex.lock().unwrap();
1859 let cp_pending_msg_events = &peer_state.pending_msg_events;
1860 number_of_msg_events += cp_pending_msg_events.len();
1861 if cp_pending_msg_events.len() == 1 {
1862 if let MessageSendEvent::UpdateHTLCs { .. } = cp_pending_msg_events[0] {
1863 assert_ne!(*cp_id, node_b.node.get_our_node_id());
1864 } else { panic!("Unexpected event"); }
1867 // Expecting the failure backwards event to the previous hop (not `node_b`)
1868 assert_eq!(number_of_msg_events, 1);
1870 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
1874 /// Get a payment preimage and hash.
1875 pub fn get_payment_preimage_hash(recipient: &Node, min_value_msat: Option<u64>, min_final_cltv_expiry_delta: Option<u16>) -> (PaymentPreimage, PaymentHash, PaymentSecret) {
1876 let mut payment_count = recipient.network_payment_count.borrow_mut();
1877 let payment_preimage = PaymentPreimage([*payment_count; 32]);
1878 *payment_count += 1;
1879 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner());
1880 let payment_secret = recipient.node.create_inbound_payment_for_hash(payment_hash, min_value_msat, 7200, min_final_cltv_expiry_delta).unwrap();
1881 (payment_preimage, payment_hash, payment_secret)
1884 /// Get a payment preimage and hash.
1886 /// Don't use this, use the identically-named function instead.
1888 macro_rules! get_payment_preimage_hash {
1889 ($dest_node: expr) => {
1890 get_payment_preimage_hash!($dest_node, None)
1892 ($dest_node: expr, $min_value_msat: expr) => {
1893 crate::get_payment_preimage_hash!($dest_node, $min_value_msat, None)
1895 ($dest_node: expr, $min_value_msat: expr, $min_final_cltv_expiry_delta: expr) => {
1896 $crate::ln::functional_test_utils::get_payment_preimage_hash(&$dest_node, $min_value_msat, $min_final_cltv_expiry_delta)
1900 /// Gets a route from the given sender to the node described in `payment_params`.
1901 pub fn get_route(send_node: &Node, route_params: &RouteParameters) -> Result<Route, msgs::LightningError> {
1902 let scorer = TestScorer::new();
1903 let keys_manager = TestKeysInterface::new(&[0u8; 32], bitcoin::network::constants::Network::Testnet);
1904 let random_seed_bytes = keys_manager.get_secure_random_bytes();
1906 &send_node.node.get_our_node_id(), route_params, &send_node.network_graph.read_only(),
1907 Some(&send_node.node.list_usable_channels().iter().collect::<Vec<_>>()),
1908 send_node.logger, &scorer, &Default::default(), &random_seed_bytes
1912 /// Gets a route from the given sender to the node described in `payment_params`.
1914 /// Don't use this, use the identically-named function instead.
1916 macro_rules! get_route {
1917 ($send_node: expr, $payment_params: expr, $recv_value: expr) => {{
1918 let route_params = $crate::routing::router::RouteParameters::from_payment_params_and_value($payment_params, $recv_value);
1919 $crate::ln::functional_test_utils::get_route(&$send_node, &route_params)
1925 macro_rules! get_route_and_payment_hash {
1926 ($send_node: expr, $recv_node: expr, $recv_value: expr) => {{
1927 let payment_params = $crate::routing::router::PaymentParameters::from_node_id($recv_node.node.get_our_node_id(), TEST_FINAL_CLTV)
1928 .with_bolt11_features($recv_node.node.bolt11_invoice_features()).unwrap();
1929 $crate::get_route_and_payment_hash!($send_node, $recv_node, payment_params, $recv_value)
1931 ($send_node: expr, $recv_node: expr, $payment_params: expr, $recv_value: expr) => {{
1932 $crate::get_route_and_payment_hash!($send_node, $recv_node, $payment_params, $recv_value, None)
1934 ($send_node: expr, $recv_node: expr, $payment_params: expr, $recv_value: expr, $max_total_routing_fee_msat: expr) => {{
1935 let mut route_params = $crate::routing::router::RouteParameters::from_payment_params_and_value($payment_params, $recv_value);
1936 route_params.max_total_routing_fee_msat = $max_total_routing_fee_msat;
1937 let (payment_preimage, payment_hash, payment_secret) =
1938 $crate::ln::functional_test_utils::get_payment_preimage_hash(&$recv_node, Some($recv_value), None);
1939 let route = $crate::ln::functional_test_utils::get_route(&$send_node, &route_params);
1940 (route.unwrap(), payment_hash, payment_preimage, payment_secret)
1944 pub fn check_payment_claimable(
1945 event: &Event, expected_payment_hash: PaymentHash, expected_payment_secret: PaymentSecret,
1946 expected_recv_value: u64, expected_payment_preimage: Option<PaymentPreimage>,
1947 expected_receiver_node_id: PublicKey,
1950 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, .. } => {
1951 assert_eq!(expected_payment_hash, *payment_hash);
1952 assert_eq!(expected_recv_value, *amount_msat);
1953 assert_eq!(expected_receiver_node_id, receiver_node_id.unwrap());
1955 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1956 assert_eq!(&expected_payment_preimage, payment_preimage);
1957 assert_eq!(expected_payment_secret, *payment_secret);
1962 _ => panic!("Unexpected event"),
1967 #[cfg(any(test, ldk_bench, feature = "_test_utils"))]
1968 macro_rules! expect_payment_claimable {
1969 ($node: expr, $expected_payment_hash: expr, $expected_payment_secret: expr, $expected_recv_value: expr) => {
1970 expect_payment_claimable!($node, $expected_payment_hash, $expected_payment_secret, $expected_recv_value, None, $node.node.get_our_node_id())
1972 ($node: expr, $expected_payment_hash: expr, $expected_payment_secret: expr, $expected_recv_value: expr, $expected_payment_preimage: expr, $expected_receiver_node_id: expr) => {
1973 let events = $node.node.get_and_clear_pending_events();
1974 assert_eq!(events.len(), 1);
1975 $crate::ln::functional_test_utils::check_payment_claimable(&events[0], $expected_payment_hash, $expected_payment_secret, $expected_recv_value, $expected_payment_preimage, $expected_receiver_node_id)
1980 #[cfg(any(test, ldk_bench, feature = "_test_utils"))]
1981 macro_rules! expect_payment_claimed {
1982 ($node: expr, $expected_payment_hash: expr, $expected_recv_value: expr) => {
1983 let events = $node.node.get_and_clear_pending_events();
1984 assert_eq!(events.len(), 1);
1986 $crate::events::Event::PaymentClaimed { ref payment_hash, amount_msat, .. } => {
1987 assert_eq!($expected_payment_hash, *payment_hash);
1988 assert_eq!($expected_recv_value, amount_msat);
1990 _ => panic!("Unexpected event"),
1995 pub fn expect_payment_sent<CM: AChannelManager, H: NodeHolder<CM=CM>>(node: &H,
1996 expected_payment_preimage: PaymentPreimage, expected_fee_msat_opt: Option<Option<u64>>,
1997 expect_per_path_claims: bool, expect_post_ev_mon_update: bool,
1999 let events = node.node().get_and_clear_pending_events();
2000 let expected_payment_hash = PaymentHash(
2001 bitcoin::hashes::sha256::Hash::hash(&expected_payment_preimage.0).into_inner());
2002 if expect_per_path_claims {
2003 assert!(events.len() > 1);
2005 assert_eq!(events.len(), 1);
2007 if expect_post_ev_mon_update {
2008 check_added_monitors(node, 1);
2010 let expected_payment_id = match events[0] {
2011 Event::PaymentSent { ref payment_id, ref payment_preimage, ref payment_hash, ref fee_paid_msat } => {
2012 assert_eq!(expected_payment_preimage, *payment_preimage);
2013 assert_eq!(expected_payment_hash, *payment_hash);
2014 if let Some(expected_fee_msat) = expected_fee_msat_opt {
2015 assert_eq!(*fee_paid_msat, expected_fee_msat);
2017 assert!(fee_paid_msat.is_some());
2021 _ => panic!("Unexpected event"),
2023 if expect_per_path_claims {
2024 for i in 1..events.len() {
2026 Event::PaymentPathSuccessful { payment_id, payment_hash, .. } => {
2027 assert_eq!(payment_id, expected_payment_id);
2028 assert_eq!(payment_hash, Some(expected_payment_hash));
2030 _ => panic!("Unexpected event"),
2037 macro_rules! expect_payment_sent {
2038 ($node: expr, $expected_payment_preimage: expr) => {
2039 $crate::expect_payment_sent!($node, $expected_payment_preimage, None::<u64>, true);
2041 ($node: expr, $expected_payment_preimage: expr, $expected_fee_msat_opt: expr) => {
2042 $crate::expect_payment_sent!($node, $expected_payment_preimage, $expected_fee_msat_opt, true);
2044 ($node: expr, $expected_payment_preimage: expr, $expected_fee_msat_opt: expr, $expect_paths: expr) => {
2045 $crate::ln::functional_test_utils::expect_payment_sent(&$node, $expected_payment_preimage,
2046 $expected_fee_msat_opt.map(|o| Some(o)), $expect_paths, true);
2052 macro_rules! expect_payment_path_successful {
2054 let events = $node.node.get_and_clear_pending_events();
2055 assert_eq!(events.len(), 1);
2057 $crate::events::Event::PaymentPathSuccessful { .. } => {},
2058 _ => panic!("Unexpected event"),
2063 pub fn expect_payment_forwarded<CM: AChannelManager, H: NodeHolder<CM=CM>>(
2064 event: Event, node: &H, prev_node: &H, next_node: &H, expected_fee: Option<u64>,
2065 upstream_force_closed: bool, downstream_force_closed: bool
2068 Event::PaymentForwarded {
2069 fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id,
2070 outbound_amount_forwarded_msat: _
2072 assert_eq!(fee_earned_msat, expected_fee);
2073 if !upstream_force_closed {
2074 // Is the event prev_channel_id in one of the channels between the two nodes?
2075 assert!(node.node().list_channels().iter().any(|x| x.counterparty.node_id == prev_node.node().get_our_node_id() && x.channel_id == prev_channel_id.unwrap()));
2077 // We check for force closures since a force closed channel is removed from the
2078 // node's channel list
2079 if !downstream_force_closed {
2080 assert!(node.node().list_channels().iter().any(|x| x.counterparty.node_id == next_node.node().get_our_node_id() && x.channel_id == next_channel_id.unwrap()));
2082 assert_eq!(claim_from_onchain_tx, downstream_force_closed);
2084 _ => panic!("Unexpected event"),
2088 macro_rules! expect_payment_forwarded {
2089 ($node: expr, $prev_node: expr, $next_node: expr, $expected_fee: expr, $upstream_force_closed: expr, $downstream_force_closed: expr) => {
2090 let mut events = $node.node.get_and_clear_pending_events();
2091 assert_eq!(events.len(), 1);
2092 $crate::ln::functional_test_utils::expect_payment_forwarded(
2093 events.pop().unwrap(), &$node, &$prev_node, &$next_node, $expected_fee,
2094 $upstream_force_closed, $downstream_force_closed);
2100 macro_rules! expect_channel_shutdown_state {
2101 ($node: expr, $chan_id: expr, $state: path) => {
2102 let chan_details = $node.node.list_channels().into_iter().filter(|cd| cd.channel_id == $chan_id).collect::<Vec<ChannelDetails>>();
2103 assert_eq!(chan_details.len(), 1);
2104 assert_eq!(chan_details[0].channel_shutdown_state, Some($state));
2108 #[cfg(any(test, ldk_bench, feature = "_test_utils"))]
2109 pub fn expect_channel_pending_event<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, expected_counterparty_node_id: &PublicKey) {
2110 let events = node.node.get_and_clear_pending_events();
2111 assert_eq!(events.len(), 1);
2113 crate::events::Event::ChannelPending { ref counterparty_node_id, .. } => {
2114 assert_eq!(*expected_counterparty_node_id, *counterparty_node_id);
2116 _ => panic!("Unexpected event"),
2120 #[cfg(any(test, ldk_bench, feature = "_test_utils"))]
2121 pub fn expect_channel_ready_event<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, expected_counterparty_node_id: &PublicKey) {
2122 let events = node.node.get_and_clear_pending_events();
2123 assert_eq!(events.len(), 1);
2125 crate::events::Event::ChannelReady{ ref counterparty_node_id, .. } => {
2126 assert_eq!(*expected_counterparty_node_id, *counterparty_node_id);
2128 _ => panic!("Unexpected event"),
2132 pub struct PaymentFailedConditions<'a> {
2133 pub(crate) expected_htlc_error_data: Option<(u16, &'a [u8])>,
2134 pub(crate) expected_blamed_scid: Option<u64>,
2135 pub(crate) expected_blamed_chan_closed: Option<bool>,
2136 pub(crate) expected_mpp_parts_remain: bool,
2139 impl<'a> PaymentFailedConditions<'a> {
2140 pub fn new() -> Self {
2142 expected_htlc_error_data: None,
2143 expected_blamed_scid: None,
2144 expected_blamed_chan_closed: None,
2145 expected_mpp_parts_remain: false,
2148 pub fn mpp_parts_remain(mut self) -> Self {
2149 self.expected_mpp_parts_remain = true;
2152 pub fn blamed_scid(mut self, scid: u64) -> Self {
2153 self.expected_blamed_scid = Some(scid);
2156 pub fn blamed_chan_closed(mut self, closed: bool) -> Self {
2157 self.expected_blamed_chan_closed = Some(closed);
2160 pub fn expected_htlc_error_data(mut self, code: u16, data: &'a [u8]) -> Self {
2161 self.expected_htlc_error_data = Some((code, data));
2167 macro_rules! expect_payment_failed_with_update {
2168 ($node: expr, $expected_payment_hash: expr, $payment_failed_permanently: expr, $scid: expr, $chan_closed: expr) => {
2169 $crate::ln::functional_test_utils::expect_payment_failed_conditions(
2170 &$node, $expected_payment_hash, $payment_failed_permanently,
2171 $crate::ln::functional_test_utils::PaymentFailedConditions::new()
2172 .blamed_scid($scid).blamed_chan_closed($chan_closed));
2177 macro_rules! expect_payment_failed {
2178 ($node: expr, $expected_payment_hash: expr, $payment_failed_permanently: expr $(, $expected_error_code: expr, $expected_error_data: expr)*) => {
2179 #[allow(unused_mut)]
2180 let mut conditions = $crate::ln::functional_test_utils::PaymentFailedConditions::new();
2182 conditions = conditions.expected_htlc_error_data($expected_error_code, &$expected_error_data);
2184 $crate::ln::functional_test_utils::expect_payment_failed_conditions(&$node, $expected_payment_hash, $payment_failed_permanently, conditions);
2188 pub fn expect_payment_failed_conditions_event<'a, 'b, 'c, 'd, 'e>(
2189 payment_failed_events: Vec<Event>, expected_payment_hash: PaymentHash,
2190 expected_payment_failed_permanently: bool, conditions: PaymentFailedConditions<'e>
2192 if conditions.expected_mpp_parts_remain { assert_eq!(payment_failed_events.len(), 1); } else { assert_eq!(payment_failed_events.len(), 2); }
2193 let expected_payment_id = match &payment_failed_events[0] {
2194 Event::PaymentPathFailed { payment_hash, payment_failed_permanently, payment_id, failure,
2198 error_data, .. } => {
2199 assert_eq!(*payment_hash, expected_payment_hash, "unexpected payment_hash");
2200 assert_eq!(*payment_failed_permanently, expected_payment_failed_permanently, "unexpected payment_failed_permanently value");
2203 assert!(error_code.is_some(), "expected error_code.is_some() = true");
2204 assert!(error_data.is_some(), "expected error_data.is_some() = true");
2205 if let Some((code, data)) = conditions.expected_htlc_error_data {
2206 assert_eq!(error_code.unwrap(), code, "unexpected error code");
2207 assert_eq!(&error_data.as_ref().unwrap()[..], data, "unexpected error data");
2211 if let Some(chan_closed) = conditions.expected_blamed_chan_closed {
2212 if let PathFailure::OnPath { network_update: Some(upd) } = failure {
2214 NetworkUpdate::ChannelUpdateMessage { ref msg } if !chan_closed => {
2215 if let Some(scid) = conditions.expected_blamed_scid {
2216 assert_eq!(msg.contents.short_channel_id, scid);
2218 const CHAN_DISABLED_FLAG: u8 = 2;
2219 assert_eq!(msg.contents.flags & CHAN_DISABLED_FLAG, 0);
2221 NetworkUpdate::ChannelFailure { short_channel_id, is_permanent } if chan_closed => {
2222 if let Some(scid) = conditions.expected_blamed_scid {
2223 assert_eq!(*short_channel_id, scid);
2225 assert!(is_permanent);
2227 _ => panic!("Unexpected update type"),
2229 } else { panic!("Expected network update"); }
2234 _ => panic!("Unexpected event"),
2236 if !conditions.expected_mpp_parts_remain {
2237 match &payment_failed_events[1] {
2238 Event::PaymentFailed { ref payment_hash, ref payment_id, ref reason } => {
2239 assert_eq!(*payment_hash, expected_payment_hash, "unexpected second payment_hash");
2240 assert_eq!(*payment_id, expected_payment_id);
2241 assert_eq!(reason.unwrap(), if expected_payment_failed_permanently {
2242 PaymentFailureReason::RecipientRejected
2244 PaymentFailureReason::RetriesExhausted
2247 _ => panic!("Unexpected second event"),
2252 pub fn expect_payment_failed_conditions<'a, 'b, 'c, 'd, 'e>(
2253 node: &'a Node<'b, 'c, 'd>, expected_payment_hash: PaymentHash, expected_payment_failed_permanently: bool,
2254 conditions: PaymentFailedConditions<'e>
2256 let events = node.node.get_and_clear_pending_events();
2257 expect_payment_failed_conditions_event(events, expected_payment_hash, expected_payment_failed_permanently, conditions);
2260 pub fn send_along_route_with_secret<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, route: Route, expected_paths: &[&[&Node<'a, 'b, 'c>]], recv_value: u64, our_payment_hash: PaymentHash, our_payment_secret: PaymentSecret) -> PaymentId {
2261 let payment_id = PaymentId(origin_node.keys_manager.backing.get_secure_random_bytes());
2262 origin_node.node.send_payment_with_route(&route, our_payment_hash,
2263 RecipientOnionFields::secret_only(our_payment_secret), payment_id).unwrap();
2264 check_added_monitors!(origin_node, expected_paths.len());
2265 pass_along_route(origin_node, expected_paths, recv_value, our_payment_hash, our_payment_secret);
2269 pub fn do_pass_along_path<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_path: &[&Node<'a, 'b, 'c>], recv_value: u64, our_payment_hash: PaymentHash, our_payment_secret: Option<PaymentSecret>, ev: MessageSendEvent, payment_claimable_expected: bool, clear_recipient_events: bool, expected_preimage: Option<PaymentPreimage>) -> Option<Event> {
2270 let mut payment_event = SendEvent::from_event(ev);
2271 let mut prev_node = origin_node;
2272 let mut event = None;
2274 for (idx, &node) in expected_path.iter().enumerate() {
2275 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
2277 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
2278 check_added_monitors!(node, 0);
2279 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
2281 expect_pending_htlcs_forwardable!(node);
2283 if idx == expected_path.len() - 1 && clear_recipient_events {
2284 let events_2 = node.node.get_and_clear_pending_events();
2285 if payment_claimable_expected {
2286 assert_eq!(events_2.len(), 1);
2287 match &events_2[0] {
2288 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat,
2289 receiver_node_id, ref via_channel_id, ref via_user_channel_id,
2290 claim_deadline, onion_fields, ..
2292 assert_eq!(our_payment_hash, *payment_hash);
2293 assert_eq!(node.node.get_our_node_id(), receiver_node_id.unwrap());
2294 assert!(onion_fields.is_some());
2296 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2297 assert_eq!(expected_preimage, *payment_preimage);
2298 assert_eq!(our_payment_secret.unwrap(), *payment_secret);
2299 assert_eq!(Some(*payment_secret), onion_fields.as_ref().unwrap().payment_secret);
2301 PaymentPurpose::SpontaneousPayment(payment_preimage) => {
2302 assert_eq!(expected_preimage.unwrap(), *payment_preimage);
2303 assert_eq!(our_payment_secret, onion_fields.as_ref().unwrap().payment_secret);
2306 assert_eq!(*amount_msat, recv_value);
2307 assert!(node.node.list_channels().iter().any(|details| details.channel_id == via_channel_id.unwrap()));
2308 assert!(node.node.list_channels().iter().any(|details| details.user_channel_id == via_user_channel_id.unwrap()));
2309 assert!(claim_deadline.unwrap() > node.best_block_info().1);
2311 _ => panic!("Unexpected event"),
2313 event = Some(events_2[0].clone());
2315 assert!(events_2.is_empty());
2317 } else if idx != expected_path.len() - 1 {
2318 let mut events_2 = node.node.get_and_clear_pending_msg_events();
2319 assert_eq!(events_2.len(), 1);
2320 check_added_monitors!(node, 1);
2321 payment_event = SendEvent::from_event(events_2.remove(0));
2322 assert_eq!(payment_event.msgs.len(), 1);
2330 pub fn pass_along_path<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_path: &[&Node<'a, 'b, 'c>], recv_value: u64, our_payment_hash: PaymentHash, our_payment_secret: Option<PaymentSecret>, ev: MessageSendEvent, payment_claimable_expected: bool, expected_preimage: Option<PaymentPreimage>) -> Option<Event> {
2331 do_pass_along_path(origin_node, expected_path, recv_value, our_payment_hash, our_payment_secret, ev, payment_claimable_expected, true, expected_preimage)
2334 pub fn pass_along_route<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_route: &[&[&Node<'a, 'b, 'c>]], recv_value: u64, our_payment_hash: PaymentHash, our_payment_secret: PaymentSecret) {
2335 let mut events = origin_node.node.get_and_clear_pending_msg_events();
2336 assert_eq!(events.len(), expected_route.len());
2337 for (path_idx, expected_path) in expected_route.iter().enumerate() {
2338 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
2339 // Once we've gotten through all the HTLCs, the last one should result in a
2340 // PaymentClaimable (but each previous one should not!), .
2341 let expect_payment = path_idx == expected_route.len() - 1;
2342 pass_along_path(origin_node, expected_path, recv_value, our_payment_hash.clone(), Some(our_payment_secret), ev, expect_payment, None);
2346 pub fn send_along_route<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, route: Route, expected_route: &[&Node<'a, 'b, 'c>], recv_value: u64) -> (PaymentPreimage, PaymentHash, PaymentSecret, PaymentId) {
2347 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(expected_route.last().unwrap());
2348 let payment_id = send_along_route_with_secret(origin_node, route, &[expected_route], recv_value, our_payment_hash, our_payment_secret);
2349 (our_payment_preimage, our_payment_hash, our_payment_secret, payment_id)
2352 pub fn do_claim_payment_along_route<'a, 'b, 'c>(
2353 origin_node: &Node<'a, 'b, 'c>, expected_paths: &[&[&Node<'a, 'b, 'c>]], skip_last: bool,
2354 our_payment_preimage: PaymentPreimage
2356 let extra_fees = vec![0; expected_paths.len()];
2357 do_claim_payment_along_route_with_extra_penultimate_hop_fees(origin_node, expected_paths,
2358 &extra_fees[..], skip_last, our_payment_preimage)
2361 pub fn do_claim_payment_along_route_with_extra_penultimate_hop_fees<'a, 'b, 'c>(
2362 origin_node: &Node<'a, 'b, 'c>, expected_paths: &[&[&Node<'a, 'b, 'c>]], expected_extra_fees:
2363 &[u32], skip_last: bool, our_payment_preimage: PaymentPreimage
2365 assert_eq!(expected_paths.len(), expected_extra_fees.len());
2366 for path in expected_paths.iter() {
2367 assert_eq!(path.last().unwrap().node.get_our_node_id(), expected_paths[0].last().unwrap().node.get_our_node_id());
2369 expected_paths[0].last().unwrap().node.claim_funds(our_payment_preimage);
2370 pass_claimed_payment_along_route(origin_node, expected_paths, expected_extra_fees, skip_last, our_payment_preimage)
2373 pub fn pass_claimed_payment_along_route<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_paths: &[&[&Node<'a, 'b, 'c>]], expected_extra_fees: &[u32], skip_last: bool, our_payment_preimage: PaymentPreimage) -> u64 {
2374 let claim_event = expected_paths[0].last().unwrap().node.get_and_clear_pending_events();
2375 assert_eq!(claim_event.len(), 1);
2376 match claim_event[0] {
2377 Event::PaymentClaimed {
2378 purpose: PaymentPurpose::SpontaneousPayment(preimage),
2382 | Event::PaymentClaimed {
2383 purpose: PaymentPurpose::InvoicePayment { payment_preimage: Some(preimage), ..},
2388 assert_eq!(preimage, our_payment_preimage);
2389 assert_eq!(htlcs.len(), expected_paths.len()); // One per path.
2390 assert_eq!(htlcs.iter().map(|h| h.value_msat).sum::<u64>(), amount_msat);
2391 expected_paths.iter().zip(htlcs).for_each(|(path, htlc)| check_claimed_htlc_channel(origin_node, path, htlc));
2393 Event::PaymentClaimed {
2394 purpose: PaymentPurpose::InvoicePayment { .. },
2400 assert_eq!(&payment_hash.0, &Sha256::hash(&our_payment_preimage.0)[..]);
2401 assert_eq!(htlcs.len(), expected_paths.len()); // One per path.
2402 assert_eq!(htlcs.iter().map(|h| h.value_msat).sum::<u64>(), amount_msat);
2403 expected_paths.iter().zip(htlcs).for_each(|(path, htlc)| check_claimed_htlc_channel(origin_node, path, htlc));
2408 check_added_monitors!(expected_paths[0].last().unwrap(), expected_paths.len());
2410 let mut expected_total_fee_msat = 0;
2412 macro_rules! msgs_from_ev {
2415 &MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
2416 assert!(update_add_htlcs.is_empty());
2417 assert_eq!(update_fulfill_htlcs.len(), 1);
2418 assert!(update_fail_htlcs.is_empty());
2419 assert!(update_fail_malformed_htlcs.is_empty());
2420 assert!(update_fee.is_none());
2421 ((update_fulfill_htlcs[0].clone(), commitment_signed.clone()), node_id.clone())
2423 _ => panic!("Unexpected event"),
2427 let mut per_path_msgs: Vec<((msgs::UpdateFulfillHTLC, msgs::CommitmentSigned), PublicKey)> = Vec::with_capacity(expected_paths.len());
2428 let mut events = expected_paths[0].last().unwrap().node.get_and_clear_pending_msg_events();
2429 assert_eq!(events.len(), expected_paths.len());
2431 if events.len() == 1 {
2432 per_path_msgs.push(msgs_from_ev!(&events[0]));
2434 for expected_path in expected_paths.iter() {
2435 // For MPP payments, we always want the message to the first node in the path.
2436 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
2437 per_path_msgs.push(msgs_from_ev!(&ev));
2441 for (i, (expected_route, (path_msgs, next_hop))) in expected_paths.iter().zip(per_path_msgs.drain(..)).enumerate() {
2442 let mut next_msgs = Some(path_msgs);
2443 let mut expected_next_node = next_hop;
2445 macro_rules! last_update_fulfill_dance {
2446 ($node: expr, $prev_node: expr) => {
2448 $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0);
2449 check_added_monitors!($node, 0);
2450 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
2451 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
2455 macro_rules! mid_update_fulfill_dance {
2456 ($idx: expr, $node: expr, $prev_node: expr, $next_node: expr, $new_msgs: expr) => {
2458 $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0);
2460 let per_peer_state = $node.node.per_peer_state.read().unwrap();
2461 let peer_state = per_peer_state.get(&$prev_node.node.get_our_node_id())
2462 .unwrap().lock().unwrap();
2463 let channel = peer_state.channel_by_id.get(&next_msgs.as_ref().unwrap().0.channel_id).unwrap();
2464 if let Some(prev_config) = channel.context().prev_config() {
2465 prev_config.forwarding_fee_base_msat
2467 channel.context().config().forwarding_fee_base_msat
2470 if $idx == 1 { fee += expected_extra_fees[i]; }
2471 expect_payment_forwarded!(*$node, $next_node, $prev_node, Some(fee as u64), false, false);
2472 expected_total_fee_msat += fee as u64;
2473 check_added_monitors!($node, 1);
2474 let new_next_msgs = if $new_msgs {
2475 let events = $node.node.get_and_clear_pending_msg_events();
2476 assert_eq!(events.len(), 1);
2477 let (res, nexthop) = msgs_from_ev!(&events[0]);
2478 expected_next_node = nexthop;
2481 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
2484 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
2485 next_msgs = new_next_msgs;
2490 let mut prev_node = expected_route.last().unwrap();
2491 for (idx, node) in expected_route.iter().rev().enumerate().skip(1) {
2492 assert_eq!(expected_next_node, node.node.get_our_node_id());
2493 let update_next_msgs = !skip_last || idx != expected_route.len() - 1;
2494 if next_msgs.is_some() {
2495 // Since we are traversing in reverse, next_node is actually the previous node
2496 let next_node: &Node;
2497 if idx == expected_route.len() - 1 {
2498 next_node = origin_node;
2500 next_node = expected_route[expected_route.len() - 1 - idx - 1];
2502 mid_update_fulfill_dance!(idx, node, prev_node, next_node, update_next_msgs);
2504 assert!(!update_next_msgs);
2505 assert!(node.node.get_and_clear_pending_msg_events().is_empty());
2507 if !skip_last && idx == expected_route.len() - 1 {
2508 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
2515 last_update_fulfill_dance!(origin_node, expected_route.first().unwrap());
2519 // Ensure that claim_funds is idempotent.
2520 expected_paths[0].last().unwrap().node.claim_funds(our_payment_preimage);
2521 assert!(expected_paths[0].last().unwrap().node.get_and_clear_pending_msg_events().is_empty());
2522 check_added_monitors!(expected_paths[0].last().unwrap(), 0);
2524 expected_total_fee_msat
2526 pub fn claim_payment_along_route<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_paths: &[&[&Node<'a, 'b, 'c>]], skip_last: bool, our_payment_preimage: PaymentPreimage) {
2527 let expected_total_fee_msat = do_claim_payment_along_route(origin_node, expected_paths, skip_last, our_payment_preimage);
2529 expect_payment_sent!(origin_node, our_payment_preimage, Some(expected_total_fee_msat));
2533 pub fn claim_payment<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_route: &[&Node<'a, 'b, 'c>], our_payment_preimage: PaymentPreimage) {
2534 claim_payment_along_route(origin_node, &[expected_route], false, our_payment_preimage);
2537 pub const TEST_FINAL_CLTV: u32 = 70;
2539 pub fn route_payment<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_route: &[&Node<'a, 'b, 'c>], recv_value: u64) -> (PaymentPreimage, PaymentHash, PaymentSecret, PaymentId) {
2540 let payment_params = PaymentParameters::from_node_id(expected_route.last().unwrap().node.get_our_node_id(), TEST_FINAL_CLTV)
2541 .with_bolt11_features(expected_route.last().unwrap().node.bolt11_invoice_features()).unwrap();
2542 let route_params = RouteParameters::from_payment_params_and_value(payment_params, recv_value);
2543 let route = get_route(origin_node, &route_params).unwrap();
2544 assert_eq!(route.paths.len(), 1);
2545 assert_eq!(route.paths[0].hops.len(), expected_route.len());
2546 for (node, hop) in expected_route.iter().zip(route.paths[0].hops.iter()) {
2547 assert_eq!(hop.pubkey, node.node.get_our_node_id());
2550 let res = send_along_route(origin_node, route, expected_route, recv_value);
2551 (res.0, res.1, res.2, res.3)
2554 pub fn route_over_limit<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_route: &[&Node<'a, 'b, 'c>], recv_value: u64) {
2555 let payment_params = PaymentParameters::from_node_id(expected_route.last().unwrap().node.get_our_node_id(), TEST_FINAL_CLTV)
2556 .with_bolt11_features(expected_route.last().unwrap().node.bolt11_invoice_features()).unwrap();
2557 let route_params = RouteParameters::from_payment_params_and_value(payment_params, recv_value);
2558 let network_graph = origin_node.network_graph.read_only();
2559 let scorer = test_utils::TestScorer::new();
2560 let seed = [0u8; 32];
2561 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
2562 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2563 let route = router::get_route(&origin_node.node.get_our_node_id(), &route_params, &network_graph,
2564 None, origin_node.logger, &scorer, &Default::default(), &random_seed_bytes).unwrap();
2565 assert_eq!(route.paths.len(), 1);
2566 assert_eq!(route.paths[0].hops.len(), expected_route.len());
2567 for (node, hop) in expected_route.iter().zip(route.paths[0].hops.iter()) {
2568 assert_eq!(hop.pubkey, node.node.get_our_node_id());
2571 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(expected_route.last().unwrap());
2572 unwrap_send_err!(origin_node.node.send_payment_with_route(&route, our_payment_hash,
2573 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)),
2574 true, APIError::ChannelUnavailable { ref err },
2575 assert!(err.contains("Cannot send value that would put us over the max HTLC value in flight our peer will accept")));
2578 pub fn send_payment<'a, 'b, 'c>(origin: &Node<'a, 'b, 'c>, expected_route: &[&Node<'a, 'b, 'c>], recv_value: u64) -> (PaymentPreimage, PaymentHash, PaymentSecret, PaymentId) {
2579 let res = route_payment(&origin, expected_route, recv_value);
2580 claim_payment(&origin, expected_route, res.0);
2584 pub fn fail_payment_along_route<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_paths: &[&[&Node<'a, 'b, 'c>]], skip_last: bool, our_payment_hash: PaymentHash) {
2585 for path in expected_paths.iter() {
2586 assert_eq!(path.last().unwrap().node.get_our_node_id(), expected_paths[0].last().unwrap().node.get_our_node_id());
2588 expected_paths[0].last().unwrap().node.fail_htlc_backwards(&our_payment_hash);
2589 let expected_destinations: Vec<HTLCDestination> = repeat(HTLCDestination::FailedPayment { payment_hash: our_payment_hash }).take(expected_paths.len()).collect();
2590 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(expected_paths[0].last().unwrap(), expected_destinations);
2592 pass_failed_payment_back(origin_node, expected_paths, skip_last, our_payment_hash, PaymentFailureReason::RecipientRejected);
2595 pub fn pass_failed_payment_back<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_paths_slice: &[&[&Node<'a, 'b, 'c>]], skip_last: bool, our_payment_hash: PaymentHash, expected_fail_reason: PaymentFailureReason) {
2596 let mut expected_paths: Vec<_> = expected_paths_slice.iter().collect();
2597 check_added_monitors!(expected_paths[0].last().unwrap(), expected_paths.len());
2599 let mut per_path_msgs: Vec<((msgs::UpdateFailHTLC, msgs::CommitmentSigned), PublicKey)> = Vec::with_capacity(expected_paths.len());
2600 let events = expected_paths[0].last().unwrap().node.get_and_clear_pending_msg_events();
2601 assert_eq!(events.len(), expected_paths.len());
2602 for ev in events.iter() {
2603 let (update_fail, commitment_signed, node_id) = match ev {
2604 &MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
2605 assert!(update_add_htlcs.is_empty());
2606 assert!(update_fulfill_htlcs.is_empty());
2607 assert_eq!(update_fail_htlcs.len(), 1);
2608 assert!(update_fail_malformed_htlcs.is_empty());
2609 assert!(update_fee.is_none());
2610 (update_fail_htlcs[0].clone(), commitment_signed.clone(), node_id.clone())
2612 _ => panic!("Unexpected event"),
2614 per_path_msgs.push(((update_fail, commitment_signed), node_id));
2616 per_path_msgs.sort_unstable_by(|(_, node_id_a), (_, node_id_b)| node_id_a.cmp(node_id_b));
2617 expected_paths.sort_unstable_by(|path_a, path_b| path_a[path_a.len() - 2].node.get_our_node_id().cmp(&path_b[path_b.len() - 2].node.get_our_node_id()));
2619 for (i, (expected_route, (path_msgs, next_hop))) in expected_paths.iter().zip(per_path_msgs.drain(..)).enumerate() {
2620 let mut next_msgs = Some(path_msgs);
2621 let mut expected_next_node = next_hop;
2622 let mut prev_node = expected_route.last().unwrap();
2624 for (idx, node) in expected_route.iter().rev().enumerate().skip(1) {
2625 assert_eq!(expected_next_node, node.node.get_our_node_id());
2626 let update_next_node = !skip_last || idx != expected_route.len() - 1;
2627 if next_msgs.is_some() {
2628 node.node.handle_update_fail_htlc(&prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0);
2629 commitment_signed_dance!(node, prev_node, next_msgs.as_ref().unwrap().1, update_next_node);
2630 if !update_next_node {
2631 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(node, vec![HTLCDestination::NextHopChannel { node_id: Some(prev_node.node.get_our_node_id()), channel_id: next_msgs.as_ref().unwrap().0.channel_id }]);
2634 let events = node.node.get_and_clear_pending_msg_events();
2635 if update_next_node {
2636 assert_eq!(events.len(), 1);
2638 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
2639 assert!(update_add_htlcs.is_empty());
2640 assert!(update_fulfill_htlcs.is_empty());
2641 assert_eq!(update_fail_htlcs.len(), 1);
2642 assert!(update_fail_malformed_htlcs.is_empty());
2643 assert!(update_fee.is_none());
2644 expected_next_node = node_id.clone();
2645 next_msgs = Some((update_fail_htlcs[0].clone(), commitment_signed.clone()));
2647 _ => panic!("Unexpected event"),
2650 assert!(events.is_empty());
2652 if !skip_last && idx == expected_route.len() - 1 {
2653 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
2660 let prev_node = expected_route.first().unwrap();
2661 origin_node.node.handle_update_fail_htlc(&prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0);
2662 check_added_monitors!(origin_node, 0);
2663 assert!(origin_node.node.get_and_clear_pending_msg_events().is_empty());
2664 commitment_signed_dance!(origin_node, prev_node, next_msgs.as_ref().unwrap().1, false);
2665 let events = origin_node.node.get_and_clear_pending_events();
2666 if i == expected_paths.len() - 1 { assert_eq!(events.len(), 2); } else { assert_eq!(events.len(), 1); }
2668 let expected_payment_id = match events[0] {
2669 Event::PaymentPathFailed { payment_hash, payment_failed_permanently, ref path, ref payment_id, .. } => {
2670 assert_eq!(payment_hash, our_payment_hash);
2671 assert!(payment_failed_permanently);
2672 for (idx, hop) in expected_route.iter().enumerate() {
2673 assert_eq!(hop.node.get_our_node_id(), path.hops[idx].pubkey);
2677 _ => panic!("Unexpected event"),
2679 if i == expected_paths.len() - 1 {
2681 Event::PaymentFailed { ref payment_hash, ref payment_id, ref reason } => {
2682 assert_eq!(*payment_hash, our_payment_hash, "unexpected second payment_hash");
2683 assert_eq!(*payment_id, expected_payment_id);
2684 assert_eq!(reason.unwrap(), expected_fail_reason);
2686 _ => panic!("Unexpected second event"),
2692 // Ensure that fail_htlc_backwards is idempotent.
2693 expected_paths[0].last().unwrap().node.fail_htlc_backwards(&our_payment_hash);
2694 assert!(expected_paths[0].last().unwrap().node.get_and_clear_pending_events().is_empty());
2695 assert!(expected_paths[0].last().unwrap().node.get_and_clear_pending_msg_events().is_empty());
2696 check_added_monitors!(expected_paths[0].last().unwrap(), 0);
2699 pub fn fail_payment<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_path: &[&Node<'a, 'b, 'c>], our_payment_hash: PaymentHash) {
2700 fail_payment_along_route(origin_node, &[&expected_path[..]], false, our_payment_hash);
2703 pub fn create_chanmon_cfgs(node_count: usize) -> Vec<TestChanMonCfg> {
2704 let mut chan_mon_cfgs = Vec::new();
2705 for i in 0..node_count {
2706 let tx_broadcaster = test_utils::TestBroadcaster::new(Network::Testnet);
2707 let fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
2708 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
2709 let logger = test_utils::TestLogger::with_id(format!("node {}", i));
2710 let persister = test_utils::TestPersister::new();
2711 let seed = [i as u8; 32];
2712 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
2713 let scorer = RwLock::new(test_utils::TestScorer::new());
2715 chan_mon_cfgs.push(TestChanMonCfg { tx_broadcaster, fee_estimator, chain_source, logger, persister, keys_manager, scorer });
2721 pub fn create_node_cfgs<'a>(node_count: usize, chanmon_cfgs: &'a Vec<TestChanMonCfg>) -> Vec<NodeCfg<'a>> {
2722 create_node_cfgs_with_persisters(node_count, chanmon_cfgs, chanmon_cfgs.iter().map(|c| &c.persister).collect())
2725 pub fn create_node_cfgs_with_persisters<'a>(node_count: usize, chanmon_cfgs: &'a Vec<TestChanMonCfg>, persisters: Vec<&'a impl Persist<TestChannelSigner>>) -> Vec<NodeCfg<'a>> {
2726 let mut nodes = Vec::new();
2728 for i in 0..node_count {
2729 let chain_monitor = test_utils::TestChainMonitor::new(Some(&chanmon_cfgs[i].chain_source), &chanmon_cfgs[i].tx_broadcaster, &chanmon_cfgs[i].logger, &chanmon_cfgs[i].fee_estimator, persisters[i], &chanmon_cfgs[i].keys_manager);
2730 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[i].logger));
2731 let seed = [i as u8; 32];
2732 nodes.push(NodeCfg {
2733 chain_source: &chanmon_cfgs[i].chain_source,
2734 logger: &chanmon_cfgs[i].logger,
2735 tx_broadcaster: &chanmon_cfgs[i].tx_broadcaster,
2736 fee_estimator: &chanmon_cfgs[i].fee_estimator,
2737 router: test_utils::TestRouter::new(network_graph.clone(), &chanmon_cfgs[i].scorer),
2739 keys_manager: &chanmon_cfgs[i].keys_manager,
2742 override_init_features: Rc::new(RefCell::new(None)),
2749 pub fn test_default_channel_config() -> UserConfig {
2750 let mut default_config = UserConfig::default();
2751 // Set cltv_expiry_delta slightly lower to keep the final CLTV values inside one byte in our
2752 // tests so that our script-length checks don't fail (see ACCEPTED_HTLC_SCRIPT_WEIGHT).
2753 default_config.channel_config.cltv_expiry_delta = MIN_CLTV_EXPIRY_DELTA;
2754 default_config.channel_handshake_config.announced_channel = true;
2755 default_config.channel_handshake_limits.force_announced_channel_preference = false;
2756 // When most of our tests were written, the default HTLC minimum was fixed at 1000.
2757 // It now defaults to 1, so we simply set it to the expected value here.
2758 default_config.channel_handshake_config.our_htlc_minimum_msat = 1000;
2759 // When most of our tests were written, we didn't have the notion of a `max_dust_htlc_exposure_msat`,
2760 // to avoid interfering with tests we bump it to 50_000_000 msat (assuming the default test
2762 default_config.channel_config.max_dust_htlc_exposure =
2763 MaxDustHTLCExposure::FeeRateMultiplier(50_000_000 / 253);
2767 pub fn create_node_chanmgrs<'a, 'b>(node_count: usize, cfgs: &'a Vec<NodeCfg<'b>>, node_config: &[Option<UserConfig>]) -> Vec<ChannelManager<&'a TestChainMonitor<'b>, &'b test_utils::TestBroadcaster, &'a test_utils::TestKeysInterface, &'a test_utils::TestKeysInterface, &'a test_utils::TestKeysInterface, &'b test_utils::TestFeeEstimator, &'a test_utils::TestRouter<'b>, &'b test_utils::TestLogger>> {
2768 let mut chanmgrs = Vec::new();
2769 for i in 0..node_count {
2770 let network = Network::Testnet;
2771 let genesis_block = bitcoin::blockdata::constants::genesis_block(network);
2772 let params = ChainParameters {
2774 best_block: BestBlock::from_network(network),
2776 let node = ChannelManager::new(cfgs[i].fee_estimator, &cfgs[i].chain_monitor, cfgs[i].tx_broadcaster, &cfgs[i].router, cfgs[i].logger, cfgs[i].keys_manager,
2777 cfgs[i].keys_manager, cfgs[i].keys_manager, if node_config[i].is_some() { node_config[i].clone().unwrap() } else { test_default_channel_config() }, params, genesis_block.header.time);
2778 chanmgrs.push(node);
2784 pub fn create_network<'a, 'b: 'a, 'c: 'b>(node_count: usize, cfgs: &'b Vec<NodeCfg<'c>>, chan_mgrs: &'a Vec<ChannelManager<&'b TestChainMonitor<'c>, &'c test_utils::TestBroadcaster, &'b test_utils::TestKeysInterface, &'b test_utils::TestKeysInterface, &'b test_utils::TestKeysInterface, &'c test_utils::TestFeeEstimator, &'c test_utils::TestRouter, &'c test_utils::TestLogger>>) -> Vec<Node<'a, 'b, 'c>> {
2785 let mut nodes = Vec::new();
2786 let chan_count = Rc::new(RefCell::new(0));
2787 let payment_count = Rc::new(RefCell::new(0));
2788 let connect_style = Rc::new(RefCell::new(ConnectStyle::random_style()));
2790 for i in 0..node_count {
2791 let gossip_sync = P2PGossipSync::new(cfgs[i].network_graph.as_ref(), None, cfgs[i].logger);
2792 let wallet_source = Arc::new(test_utils::TestWalletSource::new(SecretKey::from_slice(&[i as u8 + 1; 32]).unwrap()));
2794 chain_source: cfgs[i].chain_source, tx_broadcaster: cfgs[i].tx_broadcaster,
2795 fee_estimator: cfgs[i].fee_estimator, router: &cfgs[i].router,
2796 chain_monitor: &cfgs[i].chain_monitor, keys_manager: &cfgs[i].keys_manager,
2797 node: &chan_mgrs[i], network_graph: cfgs[i].network_graph.as_ref(), gossip_sync,
2798 node_seed: cfgs[i].node_seed, network_chan_count: chan_count.clone(),
2799 network_payment_count: payment_count.clone(), logger: cfgs[i].logger,
2800 blocks: Arc::clone(&cfgs[i].tx_broadcaster.blocks),
2801 connect_style: Rc::clone(&connect_style),
2802 override_init_features: Rc::clone(&cfgs[i].override_init_features),
2803 wallet_source: Arc::clone(&wallet_source),
2804 bump_tx_handler: BumpTransactionEventHandler::new(
2805 cfgs[i].tx_broadcaster, Arc::new(Wallet::new(Arc::clone(&wallet_source), cfgs[i].logger)),
2806 &cfgs[i].keys_manager, cfgs[i].logger,
2811 for i in 0..node_count {
2812 for j in (i+1)..node_count {
2813 nodes[i].node.peer_connected(&nodes[j].node.get_our_node_id(), &msgs::Init {
2814 features: nodes[j].override_init_features.borrow().clone().unwrap_or_else(|| nodes[j].node.init_features()),
2816 remote_network_address: None,
2818 nodes[j].node.peer_connected(&nodes[i].node.get_our_node_id(), &msgs::Init {
2819 features: nodes[i].override_init_features.borrow().clone().unwrap_or_else(|| nodes[i].node.init_features()),
2821 remote_network_address: None,
2829 // Note that the following only works for CLTV values up to 128
2830 pub const ACCEPTED_HTLC_SCRIPT_WEIGHT: usize = 137; // Here we have a diff due to HTLC CLTV expiry being < 2^15 in test
2831 pub const ACCEPTED_HTLC_SCRIPT_WEIGHT_ANCHORS: usize = 140; // Here we have a diff due to HTLC CLTV expiry being < 2^15 in test
2833 #[derive(PartialEq)]
2834 pub enum HTLCType { NONE, TIMEOUT, SUCCESS }
2835 /// Tests that the given node has broadcast transactions for the given Channel
2837 /// First checks that the latest holder commitment tx has been broadcast, unless an explicit
2838 /// commitment_tx is provided, which may be used to test that a remote commitment tx was
2839 /// broadcast and the revoked outputs were claimed.
2841 /// Next tests that there is (or is not) a transaction that spends the commitment transaction
2842 /// that appears to be the type of HTLC transaction specified in has_htlc_tx.
2844 /// All broadcast transactions must be accounted for in one of the above three types of we'll
2846 pub fn test_txn_broadcast<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, chan: &(msgs::ChannelUpdate, msgs::ChannelUpdate, ChannelId, Transaction), commitment_tx: Option<Transaction>, has_htlc_tx: HTLCType) -> Vec<Transaction> {
2847 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2848 let mut txn_seen = HashSet::new();
2849 node_txn.retain(|tx| txn_seen.insert(tx.txid()));
2850 assert!(node_txn.len() >= if commitment_tx.is_some() { 0 } else { 1 } + if has_htlc_tx == HTLCType::NONE { 0 } else { 1 });
2852 let mut res = Vec::with_capacity(2);
2853 node_txn.retain(|tx| {
2854 if tx.input.len() == 1 && tx.input[0].previous_output.txid == chan.3.txid() {
2855 check_spends!(tx, chan.3);
2856 if commitment_tx.is_none() {
2857 res.push(tx.clone());
2862 if let Some(explicit_tx) = commitment_tx {
2863 res.push(explicit_tx.clone());
2866 assert_eq!(res.len(), 1);
2868 if has_htlc_tx != HTLCType::NONE {
2869 node_txn.retain(|tx| {
2870 if tx.input.len() == 1 && tx.input[0].previous_output.txid == res[0].txid() {
2871 check_spends!(tx, res[0]);
2872 if has_htlc_tx == HTLCType::TIMEOUT {
2873 assert!(tx.lock_time.0 != 0);
2875 assert!(tx.lock_time.0 == 0);
2877 res.push(tx.clone());
2881 assert!(res.len() == 2 || res.len() == 3);
2883 assert_eq!(res[1], res[2]);
2887 assert!(node_txn.is_empty());
2891 /// Tests that the given node has broadcast a claim transaction against the provided revoked
2892 /// HTLC transaction.
2893 pub fn test_revoked_htlc_claim_txn_broadcast<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, revoked_tx: Transaction, commitment_revoked_tx: Transaction) {
2894 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2895 // We may issue multiple claiming transaction on revoked outputs due to block rescan
2896 // for revoked htlc outputs
2897 if node_txn.len() != 1 && node_txn.len() != 2 && node_txn.len() != 3 { assert!(false); }
2898 node_txn.retain(|tx| {
2899 if tx.input.len() == 1 && tx.input[0].previous_output.txid == revoked_tx.txid() {
2900 check_spends!(tx, revoked_tx);
2904 node_txn.retain(|tx| {
2905 check_spends!(tx, commitment_revoked_tx);
2908 assert!(node_txn.is_empty());
2911 pub fn check_preimage_claim<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, prev_txn: &Vec<Transaction>) -> Vec<Transaction> {
2912 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2913 let mut txn_seen = HashSet::new();
2914 node_txn.retain(|tx| txn_seen.insert(tx.txid()));
2916 let mut found_prev = false;
2917 for prev_tx in prev_txn {
2918 for tx in &*node_txn {
2919 if tx.input[0].previous_output.txid == prev_tx.txid() {
2920 check_spends!(tx, prev_tx);
2921 let mut iter = tx.input[0].witness.iter();
2922 iter.next().expect("expected 3 witness items");
2923 iter.next().expect("expected 3 witness items");
2924 assert!(iter.next().expect("expected 3 witness items").len() > 106); // must spend an htlc output
2925 assert_eq!(tx.input.len(), 1); // must spend a commitment tx
2932 assert!(found_prev);
2934 let mut res = Vec::new();
2935 mem::swap(&mut *node_txn, &mut res);
2939 pub fn handle_announce_close_broadcast_events<'a, 'b, 'c>(nodes: &Vec<Node<'a, 'b, 'c>>, a: usize, b: usize, needs_err_handle: bool, expected_error: &str) {
2940 let events_1 = nodes[a].node.get_and_clear_pending_msg_events();
2941 assert_eq!(events_1.len(), 2);
2942 let as_update = match events_1[0] {
2943 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2946 _ => panic!("Unexpected event"),
2949 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
2950 assert_eq!(node_id, nodes[b].node.get_our_node_id());
2951 assert_eq!(msg.data, expected_error);
2952 if needs_err_handle {
2953 nodes[b].node.handle_error(&nodes[a].node.get_our_node_id(), msg);
2956 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::DisconnectPeer { ref msg } } => {
2957 assert_eq!(node_id, nodes[b].node.get_our_node_id());
2958 assert_eq!(msg.as_ref().unwrap().data, expected_error);
2959 if needs_err_handle {
2960 nodes[b].node.handle_error(&nodes[a].node.get_our_node_id(), msg.as_ref().unwrap());
2963 _ => panic!("Unexpected event"),
2966 let events_2 = nodes[b].node.get_and_clear_pending_msg_events();
2967 assert_eq!(events_2.len(), if needs_err_handle { 1 } else { 2 });
2968 let bs_update = match events_2[0] {
2969 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2972 _ => panic!("Unexpected event"),
2974 if !needs_err_handle {
2976 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
2977 assert_eq!(node_id, nodes[a].node.get_our_node_id());
2978 assert_eq!(msg.data, expected_error);
2980 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::DisconnectPeer { ref msg } } => {
2981 assert_eq!(node_id, nodes[a].node.get_our_node_id());
2982 assert_eq!(msg.as_ref().unwrap().data, expected_error);
2984 _ => panic!("Unexpected event"),
2989 node.gossip_sync.handle_channel_update(&as_update).unwrap();
2990 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
2994 pub fn get_announce_close_broadcast_events<'a, 'b, 'c>(nodes: &Vec<Node<'a, 'b, 'c>>, a: usize, b: usize) {
2995 handle_announce_close_broadcast_events(nodes, a, b, false, "Channel closed because commitment or closing transaction was confirmed on chain.");
2999 macro_rules! get_channel_value_stat {
3000 ($node: expr, $counterparty_node: expr, $channel_id: expr) => {{
3001 let peer_state_lock = $node.node.per_peer_state.read().unwrap();
3002 let chan_lock = peer_state_lock.get(&$counterparty_node.node.get_our_node_id()).unwrap().lock().unwrap();
3003 let chan = chan_lock.channel_by_id.get(&$channel_id).map(
3004 |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
3005 ).flatten().unwrap();
3006 chan.get_value_stat()
3010 macro_rules! get_chan_reestablish_msgs {
3011 ($src_node: expr, $dst_node: expr) => {
3013 let mut announcements = $crate::prelude::HashSet::new();
3014 let mut res = Vec::with_capacity(1);
3015 for msg in $src_node.node.get_and_clear_pending_msg_events() {
3016 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
3017 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
3018 res.push(msg.clone());
3019 } else if let MessageSendEvent::SendChannelAnnouncement { ref node_id, ref msg, .. } = msg {
3020 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
3021 announcements.insert(msg.contents.short_channel_id);
3023 panic!("Unexpected event")
3026 assert!(announcements.is_empty());
3032 macro_rules! handle_chan_reestablish_msgs {
3033 ($src_node: expr, $dst_node: expr) => {
3035 let msg_events = $src_node.node.get_and_clear_pending_msg_events();
3037 let channel_ready = if let Some(&MessageSendEvent::SendChannelReady { ref node_id, ref msg }) = msg_events.get(0) {
3039 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
3045 if let Some(&MessageSendEvent::SendAnnouncementSignatures { ref node_id, msg: _ }) = msg_events.get(idx) {
3047 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
3050 let mut had_channel_update = false; // ChannelUpdate may be now or later, but not both
3051 if let Some(&MessageSendEvent::SendChannelUpdate { ref node_id, .. }) = msg_events.get(idx) {
3052 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
3054 had_channel_update = true;
3057 let mut revoke_and_ack = None;
3058 let mut commitment_update = None;
3059 let order = if let Some(ev) = msg_events.get(idx) {
3061 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
3062 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
3063 revoke_and_ack = Some(msg.clone());
3065 RAACommitmentOrder::RevokeAndACKFirst
3067 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3068 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
3069 commitment_update = Some(updates.clone());
3071 RAACommitmentOrder::CommitmentFirst
3073 _ => RAACommitmentOrder::CommitmentFirst,
3076 RAACommitmentOrder::CommitmentFirst
3079 if let Some(ev) = msg_events.get(idx) {
3081 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
3082 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
3083 assert!(revoke_and_ack.is_none());
3084 revoke_and_ack = Some(msg.clone());
3087 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3088 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
3089 assert!(commitment_update.is_none());
3090 commitment_update = Some(updates.clone());
3097 if let Some(&MessageSendEvent::SendChannelUpdate { ref node_id, .. }) = msg_events.get(idx) {
3098 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
3100 assert!(!had_channel_update);
3103 assert_eq!(msg_events.len(), idx);
3105 (channel_ready, revoke_and_ack, commitment_update, order)
3110 pub struct ReconnectArgs<'a, 'b, 'c, 'd> {
3111 pub node_a: &'a Node<'b, 'c, 'd>,
3112 pub node_b: &'a Node<'b, 'c, 'd>,
3113 pub send_channel_ready: (bool, bool),
3114 pub pending_responding_commitment_signed: (bool, bool),
3115 /// Indicates that the pending responding commitment signed will be a dup for the recipient,
3116 /// and no monitor update is expected
3117 pub pending_responding_commitment_signed_dup_monitor: (bool, bool),
3118 pub pending_htlc_adds: (usize, usize),
3119 pub pending_htlc_claims: (usize, usize),
3120 pub pending_htlc_fails: (usize, usize),
3121 pub pending_cell_htlc_claims: (usize, usize),
3122 pub pending_cell_htlc_fails: (usize, usize),
3123 pub pending_raa: (bool, bool),
3126 impl<'a, 'b, 'c, 'd> ReconnectArgs<'a, 'b, 'c, 'd> {
3127 pub fn new(node_a: &'a Node<'b, 'c, 'd>, node_b: &'a Node<'b, 'c, 'd>) -> Self {
3131 send_channel_ready: (false, false),
3132 pending_responding_commitment_signed: (false, false),
3133 pending_responding_commitment_signed_dup_monitor: (false, false),
3134 pending_htlc_adds: (0, 0),
3135 pending_htlc_claims: (0, 0),
3136 pending_htlc_fails: (0, 0),
3137 pending_cell_htlc_claims: (0, 0),
3138 pending_cell_htlc_fails: (0, 0),
3139 pending_raa: (false, false),
3144 /// pending_htlc_adds includes both the holding cell and in-flight update_add_htlcs, whereas
3145 /// for claims/fails they are separated out.
3146 pub fn reconnect_nodes<'a, 'b, 'c, 'd>(args: ReconnectArgs<'a, 'b, 'c, 'd>) {
3148 node_a, node_b, send_channel_ready, pending_htlc_adds, pending_htlc_claims, pending_htlc_fails,
3149 pending_cell_htlc_claims, pending_cell_htlc_fails, pending_raa,
3150 pending_responding_commitment_signed, pending_responding_commitment_signed_dup_monitor,
3152 node_a.node.peer_connected(&node_b.node.get_our_node_id(), &msgs::Init {
3153 features: node_b.node.init_features(), networks: None, remote_network_address: None
3155 let reestablish_1 = get_chan_reestablish_msgs!(node_a, node_b);
3156 node_b.node.peer_connected(&node_a.node.get_our_node_id(), &msgs::Init {
3157 features: node_a.node.init_features(), networks: None, remote_network_address: None
3159 let reestablish_2 = get_chan_reestablish_msgs!(node_b, node_a);
3161 if send_channel_ready.0 {
3162 // If a expects a channel_ready, it better not think it has received a revoke_and_ack
3164 for reestablish in reestablish_1.iter() {
3165 assert_eq!(reestablish.next_remote_commitment_number, 0);
3168 if send_channel_ready.1 {
3169 // If b expects a channel_ready, it better not think it has received a revoke_and_ack
3171 for reestablish in reestablish_2.iter() {
3172 assert_eq!(reestablish.next_remote_commitment_number, 0);
3175 if send_channel_ready.0 || send_channel_ready.1 {
3176 // If we expect any channel_ready's, both sides better have set
3177 // next_holder_commitment_number to 1
3178 for reestablish in reestablish_1.iter() {
3179 assert_eq!(reestablish.next_local_commitment_number, 1);
3181 for reestablish in reestablish_2.iter() {
3182 assert_eq!(reestablish.next_local_commitment_number, 1);
3186 let mut resp_1 = Vec::new();
3187 for msg in reestablish_1 {
3188 node_b.node.handle_channel_reestablish(&node_a.node.get_our_node_id(), &msg);
3189 resp_1.push(handle_chan_reestablish_msgs!(node_b, node_a));
3191 if pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
3192 check_added_monitors!(node_b, 1);
3194 check_added_monitors!(node_b, 0);
3197 let mut resp_2 = Vec::new();
3198 for msg in reestablish_2 {
3199 node_a.node.handle_channel_reestablish(&node_b.node.get_our_node_id(), &msg);
3200 resp_2.push(handle_chan_reestablish_msgs!(node_a, node_b));
3202 if pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
3203 check_added_monitors!(node_a, 1);
3205 check_added_monitors!(node_a, 0);
3208 // We don't yet support both needing updates, as that would require a different commitment dance:
3209 assert!((pending_htlc_adds.0 == 0 && pending_htlc_claims.0 == 0 && pending_htlc_fails.0 == 0 &&
3210 pending_cell_htlc_claims.0 == 0 && pending_cell_htlc_fails.0 == 0) ||
3211 (pending_htlc_adds.1 == 0 && pending_htlc_claims.1 == 0 && pending_htlc_fails.1 == 0 &&
3212 pending_cell_htlc_claims.1 == 0 && pending_cell_htlc_fails.1 == 0));
3214 for chan_msgs in resp_1.drain(..) {
3215 if send_channel_ready.0 {
3216 node_a.node.handle_channel_ready(&node_b.node.get_our_node_id(), &chan_msgs.0.unwrap());
3217 let announcement_event = node_a.node.get_and_clear_pending_msg_events();
3218 if !announcement_event.is_empty() {
3219 assert_eq!(announcement_event.len(), 1);
3220 if let MessageSendEvent::SendChannelUpdate { .. } = announcement_event[0] {
3221 //TODO: Test announcement_sigs re-sending
3222 } else { panic!("Unexpected event! {:?}", announcement_event[0]); }
3225 assert!(chan_msgs.0.is_none());
3228 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
3229 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap());
3230 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
3231 check_added_monitors!(node_a, 1);
3233 assert!(chan_msgs.1.is_none());
3235 if pending_htlc_adds.0 != 0 || pending_htlc_claims.0 != 0 || pending_htlc_fails.0 != 0 ||
3236 pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 ||
3237 pending_responding_commitment_signed.0
3239 let commitment_update = chan_msgs.2.unwrap();
3240 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.0);
3241 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
3242 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_htlc_fails.0 + pending_cell_htlc_fails.0);
3243 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
3244 for update_add in commitment_update.update_add_htlcs {
3245 node_a.node.handle_update_add_htlc(&node_b.node.get_our_node_id(), &update_add);
3247 for update_fulfill in commitment_update.update_fulfill_htlcs {
3248 node_a.node.handle_update_fulfill_htlc(&node_b.node.get_our_node_id(), &update_fulfill);
3250 for update_fail in commitment_update.update_fail_htlcs {
3251 node_a.node.handle_update_fail_htlc(&node_b.node.get_our_node_id(), &update_fail);
3254 if !pending_responding_commitment_signed.0 {
3255 commitment_signed_dance!(node_a, node_b, commitment_update.commitment_signed, false);
3257 node_a.node.handle_commitment_signed(&node_b.node.get_our_node_id(), &commitment_update.commitment_signed);
3258 check_added_monitors!(node_a, 1);
3259 let as_revoke_and_ack = get_event_msg!(node_a, MessageSendEvent::SendRevokeAndACK, node_b.node.get_our_node_id());
3260 // No commitment_signed so get_event_msg's assert(len == 1) passes
3261 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &as_revoke_and_ack);
3262 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
3263 check_added_monitors!(node_b, if pending_responding_commitment_signed_dup_monitor.0 { 0 } else { 1 });
3266 assert!(chan_msgs.2.is_none());
3270 for chan_msgs in resp_2.drain(..) {
3271 if send_channel_ready.1 {
3272 node_b.node.handle_channel_ready(&node_a.node.get_our_node_id(), &chan_msgs.0.unwrap());
3273 let announcement_event = node_b.node.get_and_clear_pending_msg_events();
3274 if !announcement_event.is_empty() {
3275 assert_eq!(announcement_event.len(), 1);
3276 match announcement_event[0] {
3277 MessageSendEvent::SendChannelUpdate { .. } => {},
3278 MessageSendEvent::SendAnnouncementSignatures { .. } => {},
3279 _ => panic!("Unexpected event {:?}!", announcement_event[0]),
3283 assert!(chan_msgs.0.is_none());
3286 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
3287 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap());
3288 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
3289 check_added_monitors!(node_b, 1);
3291 assert!(chan_msgs.1.is_none());
3293 if pending_htlc_adds.1 != 0 || pending_htlc_claims.1 != 0 || pending_htlc_fails.1 != 0 ||
3294 pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 ||
3295 pending_responding_commitment_signed.1
3297 let commitment_update = chan_msgs.2.unwrap();
3298 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.1);
3299 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.1 + pending_cell_htlc_claims.1);
3300 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_htlc_fails.1 + pending_cell_htlc_fails.1);
3301 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
3302 for update_add in commitment_update.update_add_htlcs {
3303 node_b.node.handle_update_add_htlc(&node_a.node.get_our_node_id(), &update_add);
3305 for update_fulfill in commitment_update.update_fulfill_htlcs {
3306 node_b.node.handle_update_fulfill_htlc(&node_a.node.get_our_node_id(), &update_fulfill);
3308 for update_fail in commitment_update.update_fail_htlcs {
3309 node_b.node.handle_update_fail_htlc(&node_a.node.get_our_node_id(), &update_fail);
3312 if !pending_responding_commitment_signed.1 {
3313 commitment_signed_dance!(node_b, node_a, commitment_update.commitment_signed, false);
3315 node_b.node.handle_commitment_signed(&node_a.node.get_our_node_id(), &commitment_update.commitment_signed);
3316 check_added_monitors!(node_b, 1);
3317 let bs_revoke_and_ack = get_event_msg!(node_b, MessageSendEvent::SendRevokeAndACK, node_a.node.get_our_node_id());
3318 // No commitment_signed so get_event_msg's assert(len == 1) passes
3319 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &bs_revoke_and_ack);
3320 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
3321 check_added_monitors!(node_a, if pending_responding_commitment_signed_dup_monitor.1 { 0 } else { 1 });
3324 assert!(chan_msgs.2.is_none());
3329 /// Initiates channel opening and creates a single batch funding transaction.
3330 /// This will go through the open_channel / accept_channel flow, and return the batch funding
3331 /// transaction with corresponding funding_created messages.
3332 pub fn create_batch_channel_funding<'a, 'b, 'c>(
3333 funding_node: &Node<'a, 'b, 'c>,
3334 params: &[(&Node<'a, 'b, 'c>, u64, u64, u128, Option<UserConfig>)],
3335 ) -> (Transaction, Vec<msgs::FundingCreated>) {
3336 let mut tx_outs = Vec::new();
3337 let mut temp_chan_ids = Vec::new();
3338 let mut funding_created_msgs = Vec::new();
3340 for (other_node, channel_value_satoshis, push_msat, user_channel_id, override_config) in params {
3341 // Initialize channel opening.
3342 let temp_chan_id = funding_node.node.create_channel(
3343 other_node.node.get_our_node_id(), *channel_value_satoshis, *push_msat, *user_channel_id,
3346 let open_channel_msg = get_event_msg!(funding_node, MessageSendEvent::SendOpenChannel, other_node.node.get_our_node_id());
3347 other_node.node.handle_open_channel(&funding_node.node.get_our_node_id(), &open_channel_msg);
3348 let accept_channel_msg = get_event_msg!(other_node, MessageSendEvent::SendAcceptChannel, funding_node.node.get_our_node_id());
3349 funding_node.node.handle_accept_channel(&other_node.node.get_our_node_id(), &accept_channel_msg);
3351 // Create the corresponding funding output.
3352 let events = funding_node.node.get_and_clear_pending_events();
3353 assert_eq!(events.len(), 1);
3355 Event::FundingGenerationReady {
3356 ref temporary_channel_id,
3357 ref counterparty_node_id,
3358 channel_value_satoshis: ref event_channel_value_satoshis,
3360 user_channel_id: ref event_user_channel_id
3362 assert_eq!(temporary_channel_id, &temp_chan_id);
3363 assert_eq!(counterparty_node_id, &other_node.node.get_our_node_id());
3364 assert_eq!(channel_value_satoshis, event_channel_value_satoshis);
3365 assert_eq!(user_channel_id, event_user_channel_id);
3366 tx_outs.push(TxOut {
3367 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
3370 _ => panic!("Unexpected event"),
3372 temp_chan_ids.push((temp_chan_id, other_node.node.get_our_node_id()));
3375 // Compose the batch funding transaction and give it to the ChannelManager.
3376 let tx = Transaction {
3378 lock_time: PackedLockTime::ZERO,
3382 assert!(funding_node.node.batch_funding_transaction_generated(
3383 temp_chan_ids.iter().map(|(a, b)| (a, b)).collect::<Vec<_>>().as_slice(),
3386 check_added_monitors!(funding_node, 0);
3387 let events = funding_node.node.get_and_clear_pending_msg_events();
3388 assert_eq!(events.len(), params.len());
3389 for (other_node, ..) in params {
3390 let funding_created = events
3392 .find_map(|event| match event {
3393 MessageSendEvent::SendFundingCreated { node_id, msg } if node_id == &other_node.node.get_our_node_id() => Some(msg.clone()),
3397 funding_created_msgs.push(funding_created);
3399 return (tx, funding_created_msgs);