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, keysinterface::EntropySource};
14 use crate::chain::channelmonitor::ChannelMonitor;
15 use crate::chain::transaction::OutPoint;
16 use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
17 use crate::ln::channelmanager::{ChainParameters, ChannelManager, ChannelManagerReadArgs, RAACommitmentOrder, PaymentSendFailure, PaymentId, MIN_CLTV_EXPIRY_DELTA};
18 use crate::routing::gossip::{P2PGossipSync, NetworkGraph, NetworkUpdate};
19 use crate::routing::router::{self, PaymentParameters, Route};
20 use crate::ln::features::InitFeatures;
22 use crate::ln::msgs::{ChannelMessageHandler,RoutingMessageHandler};
23 use crate::util::events::ClosureReason;
24 use crate::util::enforcing_trait_impls::EnforcingSigner;
25 use crate::util::scid_utils;
26 use crate::util::test_utils;
27 use crate::util::test_utils::{panicking, TestChainMonitor, TestScorer, TestKeysInterface};
28 use crate::util::events::{Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentPurpose};
29 use crate::util::errors::APIError;
30 use crate::util::config::UserConfig;
31 use crate::util::ser::{ReadableArgs, Writeable};
33 use bitcoin::blockdata::block::{Block, BlockHeader};
34 use bitcoin::blockdata::constants::genesis_block;
35 use bitcoin::blockdata::transaction::{Transaction, TxOut};
36 use bitcoin::network::constants::Network;
38 use bitcoin::hash_types::BlockHash;
39 use bitcoin::hashes::sha256::Hash as Sha256;
40 use bitcoin::hashes::Hash as _;
42 use bitcoin::secp256k1::PublicKey;
45 use crate::prelude::*;
46 use core::cell::RefCell;
48 use crate::sync::{Arc, Mutex, LockTestExt};
50 use core::iter::repeat;
51 use bitcoin::{PackedLockTime, 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 the given transaction at the given height, mining blocks as required to build to that
81 /// Returns the SCID a channel confirmed in the given transaction will have, assuming the funding
82 /// output is the 1st output in the transaction.
83 pub fn confirm_transactions_at<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, txn: &[&Transaction], conf_height: u32) -> u64 {
84 let first_connect_height = node.best_block_info().1 + 1;
85 assert!(first_connect_height <= conf_height);
86 if conf_height > first_connect_height {
87 connect_blocks(node, conf_height - first_connect_height);
89 let mut block = Block {
90 header: BlockHeader { version: 0x20000000, prev_blockhash: node.best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: conf_height, bits: 42, nonce: 42 },
93 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
94 block.txdata.push(Transaction { version: 0, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: Vec::new() });
97 block.txdata.push((*tx).clone());
99 connect_block(node, &block);
100 scid_utils::scid_from_parts(conf_height as u64, block.txdata.len() as u64 - 1, 0).unwrap()
102 pub fn confirm_transaction_at<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, tx: &Transaction, conf_height: u32) -> u64 {
103 confirm_transactions_at(node, &[tx], conf_height)
106 /// The possible ways we may notify a ChannelManager of a new block
107 #[derive(Clone, Copy, Debug, PartialEq)]
108 pub enum ConnectStyle {
109 /// Calls `best_block_updated` first, detecting transactions in the block only after receiving
110 /// the header and height information.
112 /// The same as `BestBlockFirst`, however when we have multiple blocks to connect, we only
113 /// make a single `best_block_updated` call.
114 BestBlockFirstSkippingBlocks,
115 /// The same as `BestBlockFirst` when connecting blocks. During disconnection only
116 /// `transaction_unconfirmed` is called.
117 BestBlockFirstReorgsOnlyTip,
118 /// Calls `transactions_confirmed` first, detecting transactions in the block before updating
119 /// the header and height information.
121 /// The same as `TransactionsFirst`, however when we have multiple blocks to connect, we only
122 /// make a single `best_block_updated` call.
123 TransactionsFirstSkippingBlocks,
124 /// The same as `TransactionsFirst`, however when we have multiple blocks to connect, we only
125 /// make a single `best_block_updated` call. Further, we call `transactions_confirmed` multiple
126 /// times to ensure it's idempotent.
127 TransactionsDuplicativelyFirstSkippingBlocks,
128 /// The same as `TransactionsFirst`, however when we have multiple blocks to connect, we only
129 /// make a single `best_block_updated` call. Further, we call `transactions_confirmed` multiple
130 /// times to ensure it's idempotent.
131 HighlyRedundantTransactionsFirstSkippingBlocks,
132 /// The same as `TransactionsFirst` when connecting blocks. During disconnection only
133 /// `transaction_unconfirmed` is called.
134 TransactionsFirstReorgsOnlyTip,
135 /// Provides the full block via the `chain::Listen` interface. In the current code this is
136 /// equivalent to `TransactionsFirst` with some additional assertions.
141 fn random_style() -> ConnectStyle {
142 #[cfg(feature = "std")] {
143 use core::hash::{BuildHasher, Hasher};
144 // Get a random value using the only std API to do so - the DefaultHasher
145 let rand_val = std::collections::hash_map::RandomState::new().build_hasher().finish();
146 let res = match rand_val % 9 {
147 0 => ConnectStyle::BestBlockFirst,
148 1 => ConnectStyle::BestBlockFirstSkippingBlocks,
149 2 => ConnectStyle::BestBlockFirstReorgsOnlyTip,
150 3 => ConnectStyle::TransactionsFirst,
151 4 => ConnectStyle::TransactionsFirstSkippingBlocks,
152 5 => ConnectStyle::TransactionsDuplicativelyFirstSkippingBlocks,
153 6 => ConnectStyle::HighlyRedundantTransactionsFirstSkippingBlocks,
154 7 => ConnectStyle::TransactionsFirstReorgsOnlyTip,
155 8 => ConnectStyle::FullBlockViaListen,
158 eprintln!("Using Block Connection Style: {:?}", res);
161 #[cfg(not(feature = "std"))] {
162 ConnectStyle::FullBlockViaListen
167 pub fn connect_blocks<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, depth: u32) -> BlockHash {
168 let skip_intermediaries = match *node.connect_style.borrow() {
169 ConnectStyle::BestBlockFirstSkippingBlocks|ConnectStyle::TransactionsFirstSkippingBlocks|
170 ConnectStyle::TransactionsDuplicativelyFirstSkippingBlocks|ConnectStyle::HighlyRedundantTransactionsFirstSkippingBlocks|
171 ConnectStyle::BestBlockFirstReorgsOnlyTip|ConnectStyle::TransactionsFirstReorgsOnlyTip => true,
175 let height = node.best_block_info().1 + 1;
176 let mut block = Block {
177 header: BlockHeader { version: 0x2000000, prev_blockhash: node.best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: height, bits: 42, nonce: 42 },
182 let prev_blockhash = block.header.block_hash();
183 do_connect_block(node, block, skip_intermediaries);
185 header: BlockHeader { version: 0x20000000, prev_blockhash, merkle_root: TxMerkleNode::all_zeros(), time: height + i, bits: 42, nonce: 42 },
189 let hash = block.header.block_hash();
190 do_connect_block(node, block, false);
194 pub fn connect_block<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, block: &Block) {
195 do_connect_block(node, block.clone(), false);
198 fn call_claimable_balances<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>) {
199 // Ensure `get_claimable_balances`' self-tests never panic
200 for funding_outpoint in node.chain_monitor.chain_monitor.list_monitors() {
201 node.chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances();
205 fn do_connect_block<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, block: Block, skip_intermediaries: bool) {
206 call_claimable_balances(node);
207 let height = node.best_block_info().1 + 1;
208 #[cfg(feature = "std")] {
209 eprintln!("Connecting block using Block Connection Style: {:?}", *node.connect_style.borrow());
211 if !skip_intermediaries {
212 let txdata: Vec<_> = block.txdata.iter().enumerate().collect();
213 match *node.connect_style.borrow() {
214 ConnectStyle::BestBlockFirst|ConnectStyle::BestBlockFirstSkippingBlocks|ConnectStyle::BestBlockFirstReorgsOnlyTip => {
215 node.chain_monitor.chain_monitor.best_block_updated(&block.header, height);
216 call_claimable_balances(node);
217 node.chain_monitor.chain_monitor.transactions_confirmed(&block.header, &txdata, height);
218 node.node.best_block_updated(&block.header, height);
219 node.node.transactions_confirmed(&block.header, &txdata, height);
221 ConnectStyle::TransactionsFirst|ConnectStyle::TransactionsFirstSkippingBlocks|
222 ConnectStyle::TransactionsDuplicativelyFirstSkippingBlocks|ConnectStyle::HighlyRedundantTransactionsFirstSkippingBlocks|
223 ConnectStyle::TransactionsFirstReorgsOnlyTip => {
224 if *node.connect_style.borrow() == ConnectStyle::HighlyRedundantTransactionsFirstSkippingBlocks {
225 let mut connections = Vec::new();
226 for (block, height) in node.blocks.lock().unwrap().iter() {
227 if !block.txdata.is_empty() {
228 // Reconnect all transactions we've ever seen to ensure transaction connection
229 // is *really* idempotent. This is a somewhat likely deployment for some
230 // esplora implementations of chain sync which try to reduce state and
231 // complexity as much as possible.
233 // Sadly we have to clone the block here to maintain lockorder. In the
234 // future we should consider Arc'ing the blocks to avoid this.
235 connections.push((block.clone(), *height));
238 for (old_block, height) in connections {
239 node.chain_monitor.chain_monitor.transactions_confirmed(&old_block.header,
240 &old_block.txdata.iter().enumerate().collect::<Vec<_>>(), height);
243 node.chain_monitor.chain_monitor.transactions_confirmed(&block.header, &txdata, height);
244 if *node.connect_style.borrow() == ConnectStyle::TransactionsDuplicativelyFirstSkippingBlocks {
245 node.chain_monitor.chain_monitor.transactions_confirmed(&block.header, &txdata, height);
247 call_claimable_balances(node);
248 node.chain_monitor.chain_monitor.best_block_updated(&block.header, height);
249 node.node.transactions_confirmed(&block.header, &txdata, height);
250 node.node.best_block_updated(&block.header, height);
252 ConnectStyle::FullBlockViaListen => {
253 node.chain_monitor.chain_monitor.block_connected(&block, height);
254 node.node.block_connected(&block, height);
258 call_claimable_balances(node);
259 node.node.test_process_background_events();
260 node.blocks.lock().unwrap().push((block, height));
263 pub fn disconnect_blocks<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, count: u32) {
264 call_claimable_balances(node);
265 #[cfg(feature = "std")] {
266 eprintln!("Disconnecting {} blocks using Block Connection Style: {:?}", count, *node.connect_style.borrow());
269 let orig = node.blocks.lock().unwrap().pop().unwrap();
270 assert!(orig.1 > 0); // Cannot disconnect genesis
271 let prev = node.blocks.lock().unwrap().last().unwrap().clone();
273 match *node.connect_style.borrow() {
274 ConnectStyle::FullBlockViaListen => {
275 node.chain_monitor.chain_monitor.block_disconnected(&orig.0.header, orig.1);
276 Listen::block_disconnected(node.node, &orig.0.header, orig.1);
278 ConnectStyle::BestBlockFirstSkippingBlocks|ConnectStyle::TransactionsFirstSkippingBlocks|
279 ConnectStyle::HighlyRedundantTransactionsFirstSkippingBlocks|ConnectStyle::TransactionsDuplicativelyFirstSkippingBlocks => {
281 node.chain_monitor.chain_monitor.best_block_updated(&prev.0.header, prev.1);
282 node.node.best_block_updated(&prev.0.header, prev.1);
285 ConnectStyle::BestBlockFirstReorgsOnlyTip|ConnectStyle::TransactionsFirstReorgsOnlyTip => {
286 for tx in orig.0.txdata {
287 node.chain_monitor.chain_monitor.transaction_unconfirmed(&tx.txid());
288 node.node.transaction_unconfirmed(&tx.txid());
292 node.chain_monitor.chain_monitor.best_block_updated(&prev.0.header, prev.1);
293 node.node.best_block_updated(&prev.0.header, prev.1);
296 call_claimable_balances(node);
300 pub fn disconnect_all_blocks<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>) {
301 let count = node.blocks.lock().unwrap().len() as u32 - 1;
302 disconnect_blocks(node, count);
305 pub struct TestChanMonCfg {
306 pub tx_broadcaster: test_utils::TestBroadcaster,
307 pub fee_estimator: test_utils::TestFeeEstimator,
308 pub chain_source: test_utils::TestChainSource,
309 pub persister: test_utils::TestPersister,
310 pub logger: test_utils::TestLogger,
311 pub keys_manager: test_utils::TestKeysInterface,
312 pub scorer: Mutex<test_utils::TestScorer>,
315 pub struct NodeCfg<'a> {
316 pub chain_source: &'a test_utils::TestChainSource,
317 pub tx_broadcaster: &'a test_utils::TestBroadcaster,
318 pub fee_estimator: &'a test_utils::TestFeeEstimator,
319 pub router: test_utils::TestRouter<'a>,
320 pub chain_monitor: test_utils::TestChainMonitor<'a>,
321 pub keys_manager: &'a test_utils::TestKeysInterface,
322 pub logger: &'a test_utils::TestLogger,
323 pub network_graph: Arc<NetworkGraph<&'a test_utils::TestLogger>>,
324 pub node_seed: [u8; 32],
325 pub override_init_features: Rc<RefCell<Option<InitFeatures>>>,
328 pub struct Node<'a, 'b: 'a, 'c: 'b> {
329 pub chain_source: &'c test_utils::TestChainSource,
330 pub tx_broadcaster: &'c test_utils::TestBroadcaster,
331 pub fee_estimator: &'c test_utils::TestFeeEstimator,
332 pub router: &'b test_utils::TestRouter<'c>,
333 pub chain_monitor: &'b test_utils::TestChainMonitor<'c>,
334 pub keys_manager: &'b test_utils::TestKeysInterface,
335 pub node: &'a ChannelManager<&'b TestChainMonitor<'c>, &'c test_utils::TestBroadcaster, &'b test_utils::TestKeysInterface, &'b test_utils::TestKeysInterface, &'b test_utils::TestKeysInterface, &'c test_utils::TestFeeEstimator, &'b test_utils::TestRouter<'c>, &'c test_utils::TestLogger>,
336 pub network_graph: &'a NetworkGraph<&'c test_utils::TestLogger>,
337 pub gossip_sync: P2PGossipSync<&'b NetworkGraph<&'c test_utils::TestLogger>, &'c test_utils::TestChainSource, &'c test_utils::TestLogger>,
338 pub node_seed: [u8; 32],
339 pub network_payment_count: Rc<RefCell<u8>>,
340 pub network_chan_count: Rc<RefCell<u32>>,
341 pub logger: &'c test_utils::TestLogger,
342 pub blocks: Arc<Mutex<Vec<(Block, u32)>>>,
343 pub connect_style: Rc<RefCell<ConnectStyle>>,
344 pub override_init_features: Rc<RefCell<Option<InitFeatures>>>,
346 impl<'a, 'b, 'c> Node<'a, 'b, 'c> {
347 pub fn best_block_hash(&self) -> BlockHash {
348 self.blocks.lock().unwrap().last().unwrap().0.block_hash()
350 pub fn best_block_info(&self) -> (BlockHash, u32) {
351 self.blocks.lock().unwrap().last().map(|(a, b)| (a.block_hash(), *b)).unwrap()
353 pub fn get_block_header(&self, height: u32) -> BlockHeader {
354 self.blocks.lock().unwrap()[height as usize].0.header
358 /// If we need an unsafe pointer to a `Node` (ie to reference it in a thread
359 /// pre-std::thread::scope), this provides that with `Sync`. Note that accessing some of the fields
360 /// in the `Node` are not safe to use (i.e. the ones behind an `Rc`), but that's left to the caller
362 pub struct NodePtr(pub *const Node<'static, 'static, 'static>);
364 pub fn from_node<'a, 'b: 'a, 'c: 'b>(node: &Node<'a, 'b, 'c>) -> Self {
365 Self((node as *const Node<'a, 'b, 'c>).cast())
368 unsafe impl Send for NodePtr {}
369 unsafe impl Sync for NodePtr {}
371 impl<'a, 'b, 'c> Drop for Node<'a, 'b, 'c> {
374 // Check that we processed all pending events
375 let msg_events = self.node.get_and_clear_pending_msg_events();
376 if !msg_events.is_empty() {
377 panic!("Had excess message events on node {}: {:?}", self.logger.id, msg_events);
379 let events = self.node.get_and_clear_pending_events();
380 if !events.is_empty() {
381 panic!("Had excess events on node {}: {:?}", self.logger.id, events);
383 let added_monitors = self.chain_monitor.added_monitors.lock().unwrap().split_off(0);
384 if !added_monitors.is_empty() {
385 panic!("Had {} excess added monitors on node {}", added_monitors.len(), self.logger.id);
388 // Check that if we serialize the network graph, we can deserialize it again.
389 let network_graph = {
390 let mut w = test_utils::TestVecWriter(Vec::new());
391 self.network_graph.write(&mut w).unwrap();
392 let network_graph_deser = <NetworkGraph<_>>::read(&mut io::Cursor::new(&w.0), self.logger).unwrap();
393 assert!(network_graph_deser == *self.network_graph);
394 let gossip_sync = P2PGossipSync::new(
395 &network_graph_deser, Some(self.chain_source), self.logger
397 let mut chan_progress = 0;
399 let orig_announcements = self.gossip_sync.get_next_channel_announcement(chan_progress);
400 let deserialized_announcements = gossip_sync.get_next_channel_announcement(chan_progress);
401 assert!(orig_announcements == deserialized_announcements);
402 chan_progress = match orig_announcements {
403 Some(announcement) => announcement.0.contents.short_channel_id + 1,
407 let mut node_progress = None;
409 let orig_announcements = self.gossip_sync.get_next_node_announcement(node_progress.as_ref());
410 let deserialized_announcements = gossip_sync.get_next_node_announcement(node_progress.as_ref());
411 assert!(orig_announcements == deserialized_announcements);
412 node_progress = match orig_announcements {
413 Some(announcement) => Some(announcement.contents.node_id),
420 // Check that if we serialize and then deserialize all our channel monitors we get the
421 // same set of outputs to watch for on chain as we have now. Note that if we write
422 // tests that fully close channels and remove the monitors at some point this may break.
423 let feeest = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
424 let mut deserialized_monitors = Vec::new();
426 for outpoint in self.chain_monitor.chain_monitor.list_monitors() {
427 let mut w = test_utils::TestVecWriter(Vec::new());
428 self.chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut w).unwrap();
429 let (_, deserialized_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
430 &mut io::Cursor::new(&w.0), (self.keys_manager, self.keys_manager)).unwrap();
431 deserialized_monitors.push(deserialized_monitor);
435 let broadcaster = test_utils::TestBroadcaster {
436 txn_broadcasted: Mutex::new(self.tx_broadcaster.txn_broadcasted.lock().unwrap().clone()),
437 blocks: Arc::new(Mutex::new(self.tx_broadcaster.blocks.lock().unwrap().clone())),
440 // Before using all the new monitors to check the watch outpoints, use the full set of
441 // them to ensure we can write and reload our ChannelManager.
443 let mut channel_monitors = HashMap::new();
444 for monitor in deserialized_monitors.iter_mut() {
445 channel_monitors.insert(monitor.get_funding_txo().0, monitor);
448 let scorer = Mutex::new(test_utils::TestScorer::new());
449 let mut w = test_utils::TestVecWriter(Vec::new());
450 self.node.write(&mut w).unwrap();
451 <(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 {
452 default_config: *self.node.get_current_default_configuration(),
453 entropy_source: self.keys_manager,
454 node_signer: self.keys_manager,
455 signer_provider: self.keys_manager,
456 fee_estimator: &test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
457 router: &test_utils::TestRouter::new(Arc::new(network_graph), &scorer),
458 chain_monitor: self.chain_monitor,
459 tx_broadcaster: &broadcaster,
460 logger: &self.logger,
465 let persister = test_utils::TestPersister::new();
466 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
467 let chain_monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &broadcaster, &self.logger, &feeest, &persister, &self.keys_manager);
468 for deserialized_monitor in deserialized_monitors.drain(..) {
469 if chain_monitor.watch_channel(deserialized_monitor.get_funding_txo().0, deserialized_monitor) != ChannelMonitorUpdateStatus::Completed {
473 assert_eq!(*chain_source.watched_txn.unsafe_well_ordered_double_lock_self(), *self.chain_source.watched_txn.unsafe_well_ordered_double_lock_self());
474 assert_eq!(*chain_source.watched_outputs.unsafe_well_ordered_double_lock_self(), *self.chain_source.watched_outputs.unsafe_well_ordered_double_lock_self());
479 pub fn create_chan_between_nodes<'a, 'b, 'c, 'd>(node_a: &'a Node<'b, 'c, 'd>, node_b: &'a Node<'b, 'c, 'd>) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
480 create_chan_between_nodes_with_value(node_a, node_b, 100000, 10001)
483 pub fn create_chan_between_nodes_with_value<'a, 'b, 'c, 'd>(node_a: &'a Node<'b, 'c, 'd>, node_b: &'a Node<'b, 'c, 'd>, channel_value: u64, push_msat: u64) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
484 let (channel_ready, channel_id, tx) = create_chan_between_nodes_with_value_a(node_a, node_b, channel_value, push_msat);
485 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(node_a, node_b, &channel_ready);
486 (announcement, as_update, bs_update, channel_id, tx)
489 /// Gets an RAA and CS which were sent in response to a commitment update
491 /// Should only be used directly when the `$node` is not actually a [`Node`].
492 macro_rules! do_get_revoke_commit_msgs {
493 ($node: expr, $recipient: expr) => { {
494 let events = $node.node.get_and_clear_pending_msg_events();
495 assert_eq!(events.len(), 2);
497 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
498 assert_eq!(node_id, $recipient);
501 _ => panic!("Unexpected event"),
503 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
504 assert_eq!(node_id, $recipient);
505 assert!(updates.update_add_htlcs.is_empty());
506 assert!(updates.update_fulfill_htlcs.is_empty());
507 assert!(updates.update_fail_htlcs.is_empty());
508 assert!(updates.update_fail_malformed_htlcs.is_empty());
509 assert!(updates.update_fee.is_none());
510 updates.commitment_signed.clone()
512 _ => panic!("Unexpected event"),
517 /// Gets an RAA and CS which were sent in response to a commitment update
518 pub fn get_revoke_commit_msgs(node: &Node, recipient: &PublicKey) -> (msgs::RevokeAndACK, msgs::CommitmentSigned) {
519 do_get_revoke_commit_msgs!(node, recipient)
523 /// Gets an RAA and CS which were sent in response to a commitment update
525 /// Don't use this, use the identically-named function instead.
526 macro_rules! get_revoke_commit_msgs {
527 ($node: expr, $node_id: expr) => {
528 $crate::ln::functional_test_utils::get_revoke_commit_msgs(&$node, &$node_id)
532 /// Get an specific event message from the pending events queue.
534 macro_rules! get_event_msg {
535 ($node: expr, $event_type: path, $node_id: expr) => {
537 let events = $node.node.get_and_clear_pending_msg_events();
538 assert_eq!(events.len(), 1);
540 $event_type { ref node_id, ref msg } => {
541 assert_eq!(*node_id, $node_id);
544 _ => panic!("Unexpected event"),
550 /// Get an error message from the pending events queue.
551 pub fn get_err_msg(node: &Node, recipient: &PublicKey) -> msgs::ErrorMessage {
552 let events = node.node.get_and_clear_pending_msg_events();
553 assert_eq!(events.len(), 1);
555 MessageSendEvent::HandleError {
556 action: msgs::ErrorAction::SendErrorMessage { ref msg }, ref node_id
558 assert_eq!(node_id, recipient);
561 _ => panic!("Unexpected event"),
565 /// Get a specific event from the pending events queue.
567 macro_rules! get_event {
568 ($node: expr, $event_type: path) => {
570 let mut events = $node.node.get_and_clear_pending_events();
571 assert_eq!(events.len(), 1);
572 let ev = events.pop().unwrap();
574 $event_type { .. } => {
577 _ => panic!("Unexpected event"),
583 /// Gets an UpdateHTLCs MessageSendEvent
584 pub fn get_htlc_update_msgs(node: &Node, recipient: &PublicKey) -> msgs::CommitmentUpdate {
585 let events = node.node.get_and_clear_pending_msg_events();
586 assert_eq!(events.len(), 1);
588 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
589 assert_eq!(node_id, recipient);
592 _ => panic!("Unexpected event"),
597 /// Gets an UpdateHTLCs MessageSendEvent
599 /// Don't use this, use the identically-named function instead.
600 macro_rules! get_htlc_update_msgs {
601 ($node: expr, $node_id: expr) => {
602 $crate::ln::functional_test_utils::get_htlc_update_msgs(&$node, &$node_id)
606 /// Fetches the first `msg_event` to the passed `node_id` in the passed `msg_events` vec.
607 /// Returns the `msg_event`.
609 /// Note that even though `BroadcastChannelAnnouncement` and `BroadcastChannelUpdate`
610 /// `msg_events` are stored under specific peers, this function does not fetch such `msg_events` as
611 /// such messages are intended to all peers.
612 pub fn remove_first_msg_event_to_node(msg_node_id: &PublicKey, msg_events: &mut Vec<MessageSendEvent>) -> MessageSendEvent {
613 let ev_index = msg_events.iter().position(|e| { match e {
614 MessageSendEvent::SendAcceptChannel { node_id, .. } => {
615 node_id == msg_node_id
617 MessageSendEvent::SendOpenChannel { node_id, .. } => {
618 node_id == msg_node_id
620 MessageSendEvent::SendFundingCreated { node_id, .. } => {
621 node_id == msg_node_id
623 MessageSendEvent::SendFundingSigned { node_id, .. } => {
624 node_id == msg_node_id
626 MessageSendEvent::SendChannelReady { node_id, .. } => {
627 node_id == msg_node_id
629 MessageSendEvent::SendAnnouncementSignatures { node_id, .. } => {
630 node_id == msg_node_id
632 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
633 node_id == msg_node_id
635 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
636 node_id == msg_node_id
638 MessageSendEvent::SendClosingSigned { node_id, .. } => {
639 node_id == msg_node_id
641 MessageSendEvent::SendShutdown { node_id, .. } => {
642 node_id == msg_node_id
644 MessageSendEvent::SendChannelReestablish { node_id, .. } => {
645 node_id == msg_node_id
647 MessageSendEvent::SendChannelAnnouncement { node_id, .. } => {
648 node_id == msg_node_id
650 MessageSendEvent::BroadcastChannelAnnouncement { .. } => {
653 MessageSendEvent::BroadcastChannelUpdate { .. } => {
656 MessageSendEvent::BroadcastNodeAnnouncement { .. } => {
659 MessageSendEvent::SendChannelUpdate { node_id, .. } => {
660 node_id == msg_node_id
662 MessageSendEvent::HandleError { node_id, .. } => {
663 node_id == msg_node_id
665 MessageSendEvent::SendChannelRangeQuery { node_id, .. } => {
666 node_id == msg_node_id
668 MessageSendEvent::SendShortIdsQuery { node_id, .. } => {
669 node_id == msg_node_id
671 MessageSendEvent::SendReplyChannelRange { node_id, .. } => {
672 node_id == msg_node_id
674 MessageSendEvent::SendGossipTimestampFilter { node_id, .. } => {
675 node_id == msg_node_id
678 if ev_index.is_some() {
679 msg_events.remove(ev_index.unwrap())
681 panic!("Couldn't find any MessageSendEvent to the node!")
686 macro_rules! get_channel_ref {
687 ($node: expr, $counterparty_node: expr, $per_peer_state_lock: ident, $peer_state_lock: ident, $channel_id: expr) => {
689 $per_peer_state_lock = $node.node.per_peer_state.read().unwrap();
690 $peer_state_lock = $per_peer_state_lock.get(&$counterparty_node.node.get_our_node_id()).unwrap().lock().unwrap();
691 $peer_state_lock.channel_by_id.get_mut(&$channel_id).unwrap()
697 macro_rules! get_feerate {
698 ($node: expr, $counterparty_node: expr, $channel_id: expr) => {
700 let mut per_peer_state_lock;
701 let mut peer_state_lock;
702 let chan = get_channel_ref!($node, $counterparty_node, per_peer_state_lock, peer_state_lock, $channel_id);
703 chan.get_feerate_sat_per_1000_weight()
709 macro_rules! get_opt_anchors {
710 ($node: expr, $counterparty_node: expr, $channel_id: expr) => {
712 let mut per_peer_state_lock;
713 let mut peer_state_lock;
714 let chan = get_channel_ref!($node, $counterparty_node, per_peer_state_lock, peer_state_lock, $channel_id);
720 /// Returns a channel monitor given a channel id, making some naive assumptions
722 macro_rules! get_monitor {
723 ($node: expr, $channel_id: expr) => {
725 use bitcoin::hashes::Hash;
726 let mut monitor = None;
727 // Assume funding vout is either 0 or 1 blindly
729 if let Ok(mon) = $node.chain_monitor.chain_monitor.get_monitor(
730 $crate::chain::transaction::OutPoint {
731 txid: bitcoin::Txid::from_slice(&$channel_id[..]).unwrap(), index
743 /// Returns any local commitment transactions for the channel.
745 macro_rules! get_local_commitment_txn {
746 ($node: expr, $channel_id: expr) => {
748 $crate::get_monitor!($node, $channel_id).unsafe_get_latest_holder_commitment_txn(&$node.logger)
753 /// Check the error from attempting a payment.
755 macro_rules! unwrap_send_err {
756 ($res: expr, $all_failed: expr, $type: pat, $check: expr) => {
758 &Err(PaymentSendFailure::AllFailedResendSafe(ref fails)) if $all_failed => {
759 assert_eq!(fails.len(), 1);
765 &Err(PaymentSendFailure::PartialFailure { ref results, .. }) if !$all_failed => {
766 assert_eq!(results.len(), 1);
768 Err($type) => { $check },
777 /// Check whether N channel monitor(s) have been added.
778 pub fn check_added_monitors(node: &Node, count: usize) {
779 let mut added_monitors = node.chain_monitor.added_monitors.lock().unwrap();
780 assert_eq!(added_monitors.len(), count);
781 added_monitors.clear();
784 /// Check whether N channel monitor(s) have been added.
786 /// Don't use this, use the identically-named function instead.
788 macro_rules! check_added_monitors {
789 ($node: expr, $count: expr) => {
790 $crate::ln::functional_test_utils::check_added_monitors(&$node, $count);
794 pub fn _reload_node<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, default_config: UserConfig, chanman_encoded: &[u8], monitors_encoded: &[&[u8]]) -> ChannelManager<&'b TestChainMonitor<'c>, &'c test_utils::TestBroadcaster, &'b test_utils::TestKeysInterface, &'b test_utils::TestKeysInterface, &'b test_utils::TestKeysInterface, &'c test_utils::TestFeeEstimator, &'b test_utils::TestRouter<'c>, &'c test_utils::TestLogger> {
795 let mut monitors_read = Vec::with_capacity(monitors_encoded.len());
796 for encoded in monitors_encoded {
797 let mut monitor_read = &encoded[..];
798 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>
799 ::read(&mut monitor_read, (node.keys_manager, node.keys_manager)).unwrap();
800 assert!(monitor_read.is_empty());
801 monitors_read.push(monitor);
804 let mut node_read = &chanman_encoded[..];
805 let (_, node_deserialized) = {
806 let mut channel_monitors = HashMap::new();
807 for monitor in monitors_read.iter_mut() {
808 assert!(channel_monitors.insert(monitor.get_funding_txo().0, monitor).is_none());
810 <(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 node_read, ChannelManagerReadArgs {
812 entropy_source: node.keys_manager,
813 node_signer: node.keys_manager,
814 signer_provider: node.keys_manager,
815 fee_estimator: node.fee_estimator,
817 chain_monitor: node.chain_monitor,
818 tx_broadcaster: node.tx_broadcaster,
823 assert!(node_read.is_empty());
825 for monitor in monitors_read.drain(..) {
826 assert_eq!(node.chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor),
827 ChannelMonitorUpdateStatus::Completed);
828 check_added_monitors!(node, 1);
835 macro_rules! reload_node {
836 ($node: expr, $new_config: expr, $chanman_encoded: expr, $monitors_encoded: expr, $persister: ident, $new_chain_monitor: ident, $new_channelmanager: ident) => {
837 let chanman_encoded = $chanman_encoded;
839 $persister = test_utils::TestPersister::new();
840 $new_chain_monitor = test_utils::TestChainMonitor::new(Some($node.chain_source), $node.tx_broadcaster.clone(), $node.logger, $node.fee_estimator, &$persister, &$node.keys_manager);
841 $node.chain_monitor = &$new_chain_monitor;
843 $new_channelmanager = _reload_node(&$node, $new_config, &chanman_encoded, $monitors_encoded);
844 $node.node = &$new_channelmanager;
846 ($node: expr, $chanman_encoded: expr, $monitors_encoded: expr, $persister: ident, $new_chain_monitor: ident, $new_channelmanager: ident) => {
847 reload_node!($node, $crate::util::config::UserConfig::default(), $chanman_encoded, $monitors_encoded, $persister, $new_chain_monitor, $new_channelmanager);
851 pub fn create_funding_transaction<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, expected_counterparty_node_id: &PublicKey, expected_chan_value: u64, expected_user_chan_id: u128) -> ([u8; 32], Transaction, OutPoint) {
852 let chan_id = *node.network_chan_count.borrow();
854 let events = node.node.get_and_clear_pending_events();
855 assert_eq!(events.len(), 1);
857 Event::FundingGenerationReady { ref temporary_channel_id, ref counterparty_node_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
858 assert_eq!(counterparty_node_id, expected_counterparty_node_id);
859 assert_eq!(*channel_value_satoshis, expected_chan_value);
860 assert_eq!(user_channel_id, expected_user_chan_id);
862 let tx = Transaction { version: chan_id as i32, lock_time: PackedLockTime::ZERO, input: Vec::new(), output: vec![TxOut {
863 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
865 let funding_outpoint = OutPoint { txid: tx.txid(), index: 0 };
866 (*temporary_channel_id, tx, funding_outpoint)
868 _ => panic!("Unexpected event"),
871 pub fn sign_funding_transaction<'a, 'b, 'c>(node_a: &Node<'a, 'b, 'c>, node_b: &Node<'a, 'b, 'c>, channel_value: u64, expected_temporary_channel_id: [u8; 32]) -> Transaction {
872 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(node_a, &node_b.node.get_our_node_id(), channel_value, 42);
873 assert_eq!(temporary_channel_id, expected_temporary_channel_id);
875 assert!(node_a.node.funding_transaction_generated(&temporary_channel_id, &node_b.node.get_our_node_id(), tx.clone()).is_ok());
876 check_added_monitors!(node_a, 0);
878 let funding_created_msg = get_event_msg!(node_a, MessageSendEvent::SendFundingCreated, node_b.node.get_our_node_id());
879 assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
880 node_b.node.handle_funding_created(&node_a.node.get_our_node_id(), &funding_created_msg);
882 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
883 assert_eq!(added_monitors.len(), 1);
884 assert_eq!(added_monitors[0].0, funding_output);
885 added_monitors.clear();
888 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()));
890 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
891 assert_eq!(added_monitors.len(), 1);
892 assert_eq!(added_monitors[0].0, funding_output);
893 added_monitors.clear();
896 let events_4 = node_a.node.get_and_clear_pending_events();
897 assert_eq!(events_4.len(), 0);
899 assert_eq!(node_a.tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
900 assert_eq!(node_a.tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
901 node_a.tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
903 // Ensure that funding_transaction_generated is idempotent.
904 assert!(node_a.node.funding_transaction_generated(&temporary_channel_id, &node_b.node.get_our_node_id(), tx.clone()).is_err());
905 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
906 check_added_monitors!(node_a, 0);
911 // Receiver must have been initialized with manually_accept_inbound_channels set to true.
912 pub fn open_zero_conf_channel<'a, 'b, 'c, 'd>(initiator: &'a Node<'b, 'c, 'd>, receiver: &'a Node<'b, 'c, 'd>, initiator_config: Option<UserConfig>) -> (bitcoin::Transaction, [u8; 32]) {
913 let initiator_channels = initiator.node.list_usable_channels().len();
914 let receiver_channels = receiver.node.list_usable_channels().len();
916 initiator.node.create_channel(receiver.node.get_our_node_id(), 100_000, 10_001, 42, initiator_config).unwrap();
917 let open_channel = get_event_msg!(initiator, MessageSendEvent::SendOpenChannel, receiver.node.get_our_node_id());
919 receiver.node.handle_open_channel(&initiator.node.get_our_node_id(), &open_channel);
920 let events = receiver.node.get_and_clear_pending_events();
921 assert_eq!(events.len(), 1);
923 Event::OpenChannelRequest { temporary_channel_id, .. } => {
924 receiver.node.accept_inbound_channel_from_trusted_peer_0conf(&temporary_channel_id, &initiator.node.get_our_node_id(), 0).unwrap();
926 _ => panic!("Unexpected event"),
929 let accept_channel = get_event_msg!(receiver, MessageSendEvent::SendAcceptChannel, initiator.node.get_our_node_id());
930 assert_eq!(accept_channel.minimum_depth, 0);
931 initiator.node.handle_accept_channel(&receiver.node.get_our_node_id(), &accept_channel);
933 let (temporary_channel_id, tx, _) = create_funding_transaction(&initiator, &receiver.node.get_our_node_id(), 100_000, 42);
934 initiator.node.funding_transaction_generated(&temporary_channel_id, &receiver.node.get_our_node_id(), tx.clone()).unwrap();
935 let funding_created = get_event_msg!(initiator, MessageSendEvent::SendFundingCreated, receiver.node.get_our_node_id());
937 receiver.node.handle_funding_created(&initiator.node.get_our_node_id(), &funding_created);
938 check_added_monitors!(receiver, 1);
939 let bs_signed_locked = receiver.node.get_and_clear_pending_msg_events();
940 assert_eq!(bs_signed_locked.len(), 2);
941 let as_channel_ready;
942 match &bs_signed_locked[0] {
943 MessageSendEvent::SendFundingSigned { node_id, msg } => {
944 assert_eq!(*node_id, initiator.node.get_our_node_id());
945 initiator.node.handle_funding_signed(&receiver.node.get_our_node_id(), &msg);
946 check_added_monitors!(initiator, 1);
948 assert_eq!(initiator.tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
949 assert_eq!(initiator.tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0)[0], tx);
951 as_channel_ready = get_event_msg!(initiator, MessageSendEvent::SendChannelReady, receiver.node.get_our_node_id());
953 _ => panic!("Unexpected event"),
955 match &bs_signed_locked[1] {
956 MessageSendEvent::SendChannelReady { node_id, msg } => {
957 assert_eq!(*node_id, initiator.node.get_our_node_id());
958 initiator.node.handle_channel_ready(&receiver.node.get_our_node_id(), &msg);
960 _ => panic!("Unexpected event"),
963 receiver.node.handle_channel_ready(&initiator.node.get_our_node_id(), &as_channel_ready);
965 let as_channel_update = get_event_msg!(initiator, MessageSendEvent::SendChannelUpdate, receiver.node.get_our_node_id());
966 let bs_channel_update = get_event_msg!(receiver, MessageSendEvent::SendChannelUpdate, initiator.node.get_our_node_id());
968 initiator.node.handle_channel_update(&receiver.node.get_our_node_id(), &bs_channel_update);
969 receiver.node.handle_channel_update(&initiator.node.get_our_node_id(), &as_channel_update);
971 assert_eq!(initiator.node.list_usable_channels().len(), initiator_channels + 1);
972 assert_eq!(receiver.node.list_usable_channels().len(), receiver_channels + 1);
974 expect_channel_ready_event(&initiator, &receiver.node.get_our_node_id());
975 expect_channel_ready_event(&receiver, &initiator.node.get_our_node_id());
977 (tx, as_channel_ready.channel_id)
980 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 {
981 let create_chan_id = node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
982 let open_channel_msg = get_event_msg!(node_a, MessageSendEvent::SendOpenChannel, node_b.node.get_our_node_id());
983 assert_eq!(open_channel_msg.temporary_channel_id, create_chan_id);
984 assert_eq!(node_a.node.list_channels().iter().find(|channel| channel.channel_id == create_chan_id).unwrap().user_channel_id, 42);
985 node_b.node.handle_open_channel(&node_a.node.get_our_node_id(), &open_channel_msg);
986 let accept_channel_msg = get_event_msg!(node_b, MessageSendEvent::SendAcceptChannel, node_a.node.get_our_node_id());
987 assert_eq!(accept_channel_msg.temporary_channel_id, create_chan_id);
988 node_a.node.handle_accept_channel(&node_b.node.get_our_node_id(), &accept_channel_msg);
989 assert_ne!(node_b.node.list_channels().iter().find(|channel| channel.channel_id == create_chan_id).unwrap().user_channel_id, 0);
991 sign_funding_transaction(node_a, node_b, channel_value, create_chan_id)
994 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) {
995 confirm_transaction_at(node_conf, tx, conf_height);
996 connect_blocks(node_conf, CHAN_CONFIRM_DEPTH - 1);
997 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()));
1000 pub fn create_chan_between_nodes_with_value_confirm_second<'a, 'b, 'c>(node_recv: &Node<'a, 'b, 'c>, node_conf: &Node<'a, 'b, 'c>) -> ((msgs::ChannelReady, msgs::AnnouncementSignatures), [u8; 32]) {
1002 let events_6 = node_conf.node.get_and_clear_pending_msg_events();
1003 assert_eq!(events_6.len(), 3);
1004 let announcement_sigs_idx = if let MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } = events_6[1] {
1005 assert_eq!(*node_id, node_recv.node.get_our_node_id());
1007 } else if let MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } = events_6[2] {
1008 assert_eq!(*node_id, node_recv.node.get_our_node_id());
1010 } else { panic!("Unexpected event: {:?}", events_6[1]); };
1011 ((match events_6[0] {
1012 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
1013 channel_id = msg.channel_id.clone();
1014 assert_eq!(*node_id, node_recv.node.get_our_node_id());
1017 _ => panic!("Unexpected event"),
1018 }, match events_6[announcement_sigs_idx] {
1019 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
1020 assert_eq!(*node_id, node_recv.node.get_our_node_id());
1023 _ => panic!("Unexpected event"),
1027 pub fn create_chan_between_nodes_with_value_confirm<'a, 'b, 'c, 'd>(node_a: &'a Node<'b, 'c, 'd>, node_b: &'a Node<'b, 'c, 'd>, tx: &Transaction) -> ((msgs::ChannelReady, msgs::AnnouncementSignatures), [u8; 32]) {
1028 let conf_height = core::cmp::max(node_a.best_block_info().1 + 1, node_b.best_block_info().1 + 1);
1029 create_chan_between_nodes_with_value_confirm_first(node_a, node_b, tx, conf_height);
1030 confirm_transaction_at(node_a, tx, conf_height);
1031 connect_blocks(node_a, CHAN_CONFIRM_DEPTH - 1);
1032 expect_channel_ready_event(&node_a, &node_b.node.get_our_node_id());
1033 create_chan_between_nodes_with_value_confirm_second(node_b, node_a)
1036 pub fn create_chan_between_nodes_with_value_a<'a, 'b, 'c, 'd>(node_a: &'a Node<'b, 'c, 'd>, node_b: &'a Node<'b, 'c, 'd>, channel_value: u64, push_msat: u64) -> ((msgs::ChannelReady, msgs::AnnouncementSignatures), [u8; 32], Transaction) {
1037 let tx = create_chan_between_nodes_with_value_init(node_a, node_b, channel_value, push_msat);
1038 let (msgs, chan_id) = create_chan_between_nodes_with_value_confirm(node_a, node_b, &tx);
1042 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) {
1043 node_b.node.handle_channel_ready(&node_a.node.get_our_node_id(), &as_funding_msgs.0);
1044 let bs_announcement_sigs = get_event_msg!(node_b, MessageSendEvent::SendAnnouncementSignatures, node_a.node.get_our_node_id());
1045 node_b.node.handle_announcement_signatures(&node_a.node.get_our_node_id(), &as_funding_msgs.1);
1047 let events_7 = node_b.node.get_and_clear_pending_msg_events();
1048 assert_eq!(events_7.len(), 1);
1049 let (announcement, bs_update) = match events_7[0] {
1050 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
1051 (msg, update_msg.clone().unwrap())
1053 _ => panic!("Unexpected event"),
1056 node_a.node.handle_announcement_signatures(&node_b.node.get_our_node_id(), &bs_announcement_sigs);
1057 let events_8 = node_a.node.get_and_clear_pending_msg_events();
1058 assert_eq!(events_8.len(), 1);
1059 let as_update = match events_8[0] {
1060 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
1061 assert!(*announcement == *msg);
1062 let update_msg = update_msg.clone().unwrap();
1063 assert_eq!(update_msg.contents.short_channel_id, announcement.contents.short_channel_id);
1064 assert_eq!(update_msg.contents.short_channel_id, bs_update.contents.short_channel_id);
1067 _ => panic!("Unexpected event"),
1070 *node_a.network_chan_count.borrow_mut() += 1;
1072 expect_channel_ready_event(&node_b, &node_a.node.get_our_node_id());
1073 ((*announcement).clone(), as_update, bs_update)
1076 pub fn create_announced_chan_between_nodes<'a, 'b, 'c, 'd>(nodes: &'a Vec<Node<'b, 'c, 'd>>, a: usize, b: usize) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
1077 create_announced_chan_between_nodes_with_value(nodes, a, b, 100000, 10001)
1080 pub fn create_announced_chan_between_nodes_with_value<'a, 'b, 'c, 'd>(nodes: &'a Vec<Node<'b, 'c, 'd>>, a: usize, b: usize, channel_value: u64, push_msat: u64) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
1081 let chan_announcement = create_chan_between_nodes_with_value(&nodes[a], &nodes[b], channel_value, push_msat);
1082 update_nodes_with_chan_announce(nodes, a, b, &chan_announcement.0, &chan_announcement.1, &chan_announcement.2);
1083 (chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
1086 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) {
1087 let mut no_announce_cfg = test_default_channel_config();
1088 no_announce_cfg.channel_handshake_config.announced_channel = false;
1089 nodes[a].node.create_channel(nodes[b].node.get_our_node_id(), channel_value, push_msat, 42, Some(no_announce_cfg)).unwrap();
1090 let open_channel = get_event_msg!(nodes[a], MessageSendEvent::SendOpenChannel, nodes[b].node.get_our_node_id());
1091 nodes[b].node.handle_open_channel(&nodes[a].node.get_our_node_id(), &open_channel);
1092 let accept_channel = get_event_msg!(nodes[b], MessageSendEvent::SendAcceptChannel, nodes[a].node.get_our_node_id());
1093 nodes[a].node.handle_accept_channel(&nodes[b].node.get_our_node_id(), &accept_channel);
1095 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[a], &nodes[b].node.get_our_node_id(), channel_value, 42);
1096 nodes[a].node.funding_transaction_generated(&temporary_channel_id, &nodes[b].node.get_our_node_id(), tx.clone()).unwrap();
1097 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()));
1098 check_added_monitors!(nodes[b], 1);
1100 let cs_funding_signed = get_event_msg!(nodes[b], MessageSendEvent::SendFundingSigned, nodes[a].node.get_our_node_id());
1101 nodes[a].node.handle_funding_signed(&nodes[b].node.get_our_node_id(), &cs_funding_signed);
1102 check_added_monitors!(nodes[a], 1);
1104 assert_eq!(nodes[a].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1105 assert_eq!(nodes[a].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
1106 nodes[a].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1108 let conf_height = core::cmp::max(nodes[a].best_block_info().1 + 1, nodes[b].best_block_info().1 + 1);
1109 confirm_transaction_at(&nodes[a], &tx, conf_height);
1110 connect_blocks(&nodes[a], CHAN_CONFIRM_DEPTH - 1);
1111 confirm_transaction_at(&nodes[b], &tx, conf_height);
1112 connect_blocks(&nodes[b], CHAN_CONFIRM_DEPTH - 1);
1113 let as_channel_ready = get_event_msg!(nodes[a], MessageSendEvent::SendChannelReady, nodes[b].node.get_our_node_id());
1114 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()));
1115 expect_channel_ready_event(&nodes[a], &nodes[b].node.get_our_node_id());
1116 let as_update = get_event_msg!(nodes[a], MessageSendEvent::SendChannelUpdate, nodes[b].node.get_our_node_id());
1117 nodes[b].node.handle_channel_ready(&nodes[a].node.get_our_node_id(), &as_channel_ready);
1118 expect_channel_ready_event(&nodes[b], &nodes[a].node.get_our_node_id());
1119 let bs_update = get_event_msg!(nodes[b], MessageSendEvent::SendChannelUpdate, nodes[a].node.get_our_node_id());
1121 nodes[a].node.handle_channel_update(&nodes[b].node.get_our_node_id(), &bs_update);
1122 nodes[b].node.handle_channel_update(&nodes[a].node.get_our_node_id(), &as_update);
1124 let mut found_a = false;
1125 for chan in nodes[a].node.list_usable_channels() {
1126 if chan.channel_id == as_channel_ready.channel_id {
1129 assert!(!chan.is_public);
1134 let mut found_b = false;
1135 for chan in nodes[b].node.list_usable_channels() {
1136 if chan.channel_id == as_channel_ready.channel_id {
1139 assert!(!chan.is_public);
1144 (as_channel_ready, tx)
1147 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) {
1149 assert!(node.gossip_sync.handle_channel_announcement(ann).unwrap());
1150 node.gossip_sync.handle_channel_update(upd_1).unwrap();
1151 node.gossip_sync.handle_channel_update(upd_2).unwrap();
1153 // Note that channel_updates are also delivered to ChannelManagers to ensure we have
1154 // forwarding info for local channels even if its not accepted in the network graph.
1155 node.node.handle_channel_update(&nodes[a].node.get_our_node_id(), &upd_1);
1156 node.node.handle_channel_update(&nodes[b].node.get_our_node_id(), &upd_2);
1160 pub fn do_check_spends<F: Fn(&bitcoin::blockdata::transaction::OutPoint) -> Option<TxOut>>(tx: &Transaction, get_output: F) {
1161 for outp in tx.output.iter() {
1162 assert!(outp.value >= outp.script_pubkey.dust_value().to_sat(), "Spending tx output didn't meet dust limit");
1164 let mut total_value_in = 0;
1165 for input in tx.input.iter() {
1166 total_value_in += get_output(&input.previous_output).unwrap().value;
1168 let mut total_value_out = 0;
1169 for output in tx.output.iter() {
1170 total_value_out += output.value;
1172 let min_fee = (tx.weight() as u64 + 3) / 4; // One sat per vbyte (ie per weight/4, rounded up)
1173 // Input amount - output amount = fee, so check that out + min_fee is smaller than input
1174 assert!(total_value_out + min_fee <= total_value_in);
1175 tx.verify(get_output).unwrap();
1179 macro_rules! check_spends {
1180 ($tx: expr, $($spends_txn: expr),*) => {
1183 for outp in $spends_txn.output.iter() {
1184 assert!(outp.value >= outp.script_pubkey.dust_value().to_sat(), "Input tx output didn't meet dust limit");
1187 let get_output = |out_point: &bitcoin::blockdata::transaction::OutPoint| {
1189 if out_point.txid == $spends_txn.txid() {
1190 return $spends_txn.output.get(out_point.vout as usize).cloned()
1195 $crate::ln::functional_test_utils::do_check_spends(&$tx, get_output);
1200 macro_rules! get_closing_signed_broadcast {
1201 ($node: expr, $dest_pubkey: expr) => {
1203 let events = $node.get_and_clear_pending_msg_events();
1204 assert!(events.len() == 1 || events.len() == 2);
1205 (match events[events.len() - 1] {
1206 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
1207 assert_eq!(msg.contents.flags & 2, 2);
1210 _ => panic!("Unexpected event"),
1211 }, if events.len() == 2 {
1213 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
1214 assert_eq!(*node_id, $dest_pubkey);
1217 _ => panic!("Unexpected event"),
1225 macro_rules! check_warn_msg {
1226 ($node: expr, $recipient_node_id: expr, $chan_id: expr) => {{
1227 let msg_events = $node.node.get_and_clear_pending_msg_events();
1228 assert_eq!(msg_events.len(), 1);
1229 match msg_events[0] {
1230 MessageSendEvent::HandleError { action: ErrorAction::SendWarningMessage { ref msg, log_level: _ }, node_id } => {
1231 assert_eq!(node_id, $recipient_node_id);
1232 assert_eq!(msg.channel_id, $chan_id);
1235 _ => panic!("Unexpected event"),
1240 /// Check that a channel's closing channel update has been broadcasted, and optionally
1241 /// check whether an error message event has occurred.
1242 pub fn check_closed_broadcast(node: &Node, num_channels: usize, with_error_msg: bool) -> Vec<msgs::ErrorMessage> {
1243 let msg_events = node.node.get_and_clear_pending_msg_events();
1244 assert_eq!(msg_events.len(), if with_error_msg { num_channels * 2 } else { num_channels });
1245 msg_events.into_iter().filter_map(|msg_event| {
1247 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
1248 assert_eq!(msg.contents.flags & 2, 2);
1251 MessageSendEvent::HandleError { action: msgs::ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1252 assert!(with_error_msg);
1253 // TODO: Check node_id
1256 _ => panic!("Unexpected event"),
1261 /// Check that a channel's closing channel update has been broadcasted, and optionally
1262 /// check whether an error message event has occurred.
1264 /// Don't use this, use the identically-named function instead.
1266 macro_rules! check_closed_broadcast {
1267 ($node: expr, $with_error_msg: expr) => {
1268 $crate::ln::functional_test_utils::check_closed_broadcast(&$node, 1, $with_error_msg).pop()
1272 /// Check that a channel's closing channel events has been issued
1273 pub fn check_closed_event(node: &Node, events_count: usize, expected_reason: ClosureReason, is_check_discard_funding: bool) {
1274 let events = node.node.get_and_clear_pending_events();
1275 assert_eq!(events.len(), events_count, "{:?}", events);
1276 let mut issues_discard_funding = false;
1277 for event in events {
1279 Event::ChannelClosed { ref reason, .. } => {
1280 assert_eq!(*reason, expected_reason);
1282 Event::DiscardFunding { .. } => {
1283 issues_discard_funding = true;
1285 _ => panic!("Unexpected event"),
1288 assert_eq!(is_check_discard_funding, issues_discard_funding);
1291 /// Check that a channel's closing channel events has been issued
1293 /// Don't use this, use the identically-named function instead.
1295 macro_rules! check_closed_event {
1296 ($node: expr, $events: expr, $reason: expr) => {
1297 check_closed_event!($node, $events, $reason, false);
1299 ($node: expr, $events: expr, $reason: expr, $is_check_discard_funding: expr) => {
1300 $crate::ln::functional_test_utils::check_closed_event(&$node, $events, $reason, $is_check_discard_funding);
1304 pub fn close_channel<'a, 'b, 'c>(outbound_node: &Node<'a, 'b, 'c>, inbound_node: &Node<'a, 'b, 'c>, channel_id: &[u8; 32], funding_tx: Transaction, close_inbound_first: bool) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, Transaction) {
1305 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) };
1306 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) };
1309 node_a.close_channel(channel_id, &node_b.get_our_node_id()).unwrap();
1310 node_b.handle_shutdown(&node_a.get_our_node_id(), &get_event_msg!(struct_a, MessageSendEvent::SendShutdown, node_b.get_our_node_id()));
1312 let events_1 = node_b.get_and_clear_pending_msg_events();
1313 assert!(events_1.len() >= 1);
1314 let shutdown_b = match events_1[0] {
1315 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
1316 assert_eq!(node_id, &node_a.get_our_node_id());
1319 _ => panic!("Unexpected event"),
1322 let closing_signed_b = if !close_inbound_first {
1323 assert_eq!(events_1.len(), 1);
1326 Some(match events_1[1] {
1327 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
1328 assert_eq!(node_id, &node_a.get_our_node_id());
1331 _ => panic!("Unexpected event"),
1335 node_a.handle_shutdown(&node_b.get_our_node_id(), &shutdown_b);
1336 let (as_update, bs_update) = if close_inbound_first {
1337 assert!(node_a.get_and_clear_pending_msg_events().is_empty());
1338 node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap());
1340 node_b.handle_closing_signed(&node_a.get_our_node_id(), &get_event_msg!(struct_a, MessageSendEvent::SendClosingSigned, node_b.get_our_node_id()));
1341 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
1342 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
1343 let (bs_update, closing_signed_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
1345 node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap());
1346 let (as_update, none_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
1347 assert!(none_a.is_none());
1348 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
1349 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
1350 (as_update, bs_update)
1352 let closing_signed_a = get_event_msg!(struct_a, MessageSendEvent::SendClosingSigned, node_b.get_our_node_id());
1354 node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a);
1355 node_a.handle_closing_signed(&node_b.get_our_node_id(), &get_event_msg!(struct_b, MessageSendEvent::SendClosingSigned, node_a.get_our_node_id()));
1357 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
1358 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
1359 let (as_update, closing_signed_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
1361 node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap());
1362 let (bs_update, none_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
1363 assert!(none_b.is_none());
1364 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
1365 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
1366 (as_update, bs_update)
1368 assert_eq!(tx_a, tx_b);
1369 check_spends!(tx_a, funding_tx);
1371 (as_update, bs_update, tx_a)
1374 pub struct SendEvent {
1375 pub node_id: PublicKey,
1376 pub msgs: Vec<msgs::UpdateAddHTLC>,
1377 pub commitment_msg: msgs::CommitmentSigned,
1380 pub fn from_commitment_update(node_id: PublicKey, updates: msgs::CommitmentUpdate) -> SendEvent {
1381 assert!(updates.update_fulfill_htlcs.is_empty());
1382 assert!(updates.update_fail_htlcs.is_empty());
1383 assert!(updates.update_fail_malformed_htlcs.is_empty());
1384 assert!(updates.update_fee.is_none());
1385 SendEvent { node_id, msgs: updates.update_add_htlcs, commitment_msg: updates.commitment_signed }
1388 pub fn from_event(event: MessageSendEvent) -> SendEvent {
1390 MessageSendEvent::UpdateHTLCs { node_id, updates } => SendEvent::from_commitment_update(node_id, updates),
1391 _ => panic!("Unexpected event type!"),
1395 pub fn from_node<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>) -> SendEvent {
1396 let mut events = node.node.get_and_clear_pending_msg_events();
1397 assert_eq!(events.len(), 1);
1398 SendEvent::from_event(events.pop().unwrap())
1403 /// Don't use this, use the identically-named function instead.
1404 macro_rules! expect_pending_htlcs_forwardable_conditions {
1405 ($node: expr, $expected_failures: expr) => {
1406 $crate::ln::functional_test_utils::expect_pending_htlcs_forwardable_conditions($node.node.get_and_clear_pending_events(), &$expected_failures);
1411 macro_rules! expect_htlc_handling_failed_destinations {
1412 ($events: expr, $expected_failures: expr) => {{
1413 for event in $events {
1415 $crate::util::events::Event::PendingHTLCsForwardable { .. } => { },
1416 $crate::util::events::Event::HTLCHandlingFailed { ref failed_next_destination, .. } => {
1417 assert!($expected_failures.contains(&failed_next_destination))
1419 _ => panic!("Unexpected destination"),
1425 /// Checks that an [`Event::PendingHTLCsForwardable`] is available in the given events and, if
1426 /// there are any [`Event::HTLCHandlingFailed`] events their [`HTLCDestination`] is included in the
1427 /// `expected_failures` set.
1428 pub fn expect_pending_htlcs_forwardable_conditions(events: Vec<Event>, expected_failures: &[HTLCDestination]) {
1430 Event::PendingHTLCsForwardable { .. } => { },
1431 _ => panic!("Unexpected event {:?}", events),
1434 let count = expected_failures.len() + 1;
1435 assert_eq!(events.len(), count);
1437 if expected_failures.len() > 0 {
1438 expect_htlc_handling_failed_destinations!(events, expected_failures)
1443 /// Clears (and ignores) a PendingHTLCsForwardable event
1445 /// Don't use this, call [`expect_pending_htlcs_forwardable_conditions()`] with an empty failure
1447 macro_rules! expect_pending_htlcs_forwardable_ignore {
1449 $crate::ln::functional_test_utils::expect_pending_htlcs_forwardable_conditions($node.node.get_and_clear_pending_events(), &[]);
1454 /// Clears (and ignores) PendingHTLCsForwardable and HTLCHandlingFailed events
1456 /// Don't use this, call [`expect_pending_htlcs_forwardable_conditions()`] instead.
1457 macro_rules! expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore {
1458 ($node: expr, $expected_failures: expr) => {
1459 $crate::ln::functional_test_utils::expect_pending_htlcs_forwardable_conditions($node.node.get_and_clear_pending_events(), &$expected_failures);
1464 /// Handles a PendingHTLCsForwardable event
1465 macro_rules! expect_pending_htlcs_forwardable {
1467 $crate::ln::functional_test_utils::expect_pending_htlcs_forwardable_conditions($node.node.get_and_clear_pending_events(), &[]);
1468 $node.node.process_pending_htlc_forwards();
1470 // Ensure process_pending_htlc_forwards is idempotent.
1471 $node.node.process_pending_htlc_forwards();
1476 /// Handles a PendingHTLCsForwardable and HTLCHandlingFailed event
1477 macro_rules! expect_pending_htlcs_forwardable_and_htlc_handling_failed {
1478 ($node: expr, $expected_failures: expr) => {{
1479 $crate::ln::functional_test_utils::expect_pending_htlcs_forwardable_conditions($node.node.get_and_clear_pending_events(), &$expected_failures);
1480 $node.node.process_pending_htlc_forwards();
1482 // Ensure process_pending_htlc_forwards is idempotent.
1483 $node.node.process_pending_htlc_forwards();
1488 macro_rules! expect_pending_htlcs_forwardable_from_events {
1489 ($node: expr, $events: expr, $ignore: expr) => {{
1490 assert_eq!($events.len(), 1);
1492 Event::PendingHTLCsForwardable { .. } => { },
1493 _ => panic!("Unexpected event"),
1496 $node.node.process_pending_htlc_forwards();
1498 // Ensure process_pending_htlc_forwards is idempotent.
1499 $node.node.process_pending_htlc_forwards();
1505 /// Performs the "commitment signed dance" - the series of message exchanges which occur after a
1506 /// commitment update.
1507 macro_rules! commitment_signed_dance {
1508 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */) => {
1509 $crate::ln::functional_test_utils::do_commitment_signed_dance(&$node_a, &$node_b, &$commitment_signed, $fail_backwards, true);
1511 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */, true /* return last RAA */) => {
1512 $crate::ln::functional_test_utils::do_main_commitment_signed_dance(&$node_a, &$node_b, $fail_backwards)
1514 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */, false /* return extra message */, true /* return last RAA */) => {
1516 $crate::ln::functional_test_utils::check_added_monitors(&$node_a, 0);
1517 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
1518 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed);
1519 check_added_monitors(&$node_a, 1);
1520 let (extra_msg_option, bs_revoke_and_ack) = $crate::ln::functional_test_utils::do_main_commitment_signed_dance(&$node_a, &$node_b, $fail_backwards);
1521 assert!(extra_msg_option.is_none());
1525 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */) => {
1527 let (extra_msg_option, bs_revoke_and_ack) = $crate::ln::functional_test_utils::do_main_commitment_signed_dance(&$node_a, &$node_b, $fail_backwards);
1528 $node_a.node.handle_revoke_and_ack(&$node_b.node.get_our_node_id(), &bs_revoke_and_ack);
1529 $crate::ln::functional_test_utils::check_added_monitors(&$node_a, 1);
1533 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, false /* no extra message */) => {
1534 assert!(commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true).is_none());
1536 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr) => {
1537 $crate::ln::functional_test_utils::do_commitment_signed_dance(&$node_a, &$node_b, &$commitment_signed, $fail_backwards, false);
1542 pub fn do_main_commitment_signed_dance(node_a: &Node<'_, '_, '_>, node_b: &Node<'_, '_, '_>, fail_backwards: bool) -> (Option<MessageSendEvent>, msgs::RevokeAndACK) {
1543 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(node_a, node_b.node.get_our_node_id());
1544 check_added_monitors!(node_b, 0);
1545 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
1546 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &as_revoke_and_ack);
1547 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
1548 check_added_monitors!(node_b, 1);
1549 node_b.node.handle_commitment_signed(&node_a.node.get_our_node_id(), &as_commitment_signed);
1550 let (bs_revoke_and_ack, extra_msg_option) = {
1551 let mut events = node_b.node.get_and_clear_pending_msg_events();
1552 assert!(events.len() <= 2);
1553 let node_a_event = remove_first_msg_event_to_node(&node_a.node.get_our_node_id(), &mut events);
1554 (match node_a_event {
1555 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
1556 assert_eq!(*node_id, node_a.node.get_our_node_id());
1559 _ => panic!("Unexpected event"),
1560 }, events.get(0).map(|e| e.clone()))
1562 check_added_monitors!(node_b, 1);
1564 assert!(node_a.node.get_and_clear_pending_events().is_empty());
1565 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
1567 (extra_msg_option, bs_revoke_and_ack)
1570 pub fn do_commitment_signed_dance(node_a: &Node<'_, '_, '_>, node_b: &Node<'_, '_, '_>, commitment_signed: &msgs::CommitmentSigned, fail_backwards: bool, skip_last_step: bool) {
1571 check_added_monitors!(node_a, 0);
1572 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
1573 node_a.node.handle_commitment_signed(&node_b.node.get_our_node_id(), commitment_signed);
1574 check_added_monitors!(node_a, 1);
1576 commitment_signed_dance!(node_a, node_b, (), fail_backwards, true, false);
1578 if skip_last_step { return; }
1581 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(node_a,
1582 vec![crate::util::events::HTLCDestination::NextHopChannel{ node_id: Some(node_b.node.get_our_node_id()), channel_id: commitment_signed.channel_id }]);
1583 check_added_monitors!(node_a, 1);
1585 let node_a_per_peer_state = node_a.node.per_peer_state.read().unwrap();
1586 let mut number_of_msg_events = 0;
1587 for (cp_id, peer_state_mutex) in node_a_per_peer_state.iter() {
1588 let peer_state = peer_state_mutex.lock().unwrap();
1589 let cp_pending_msg_events = &peer_state.pending_msg_events;
1590 number_of_msg_events += cp_pending_msg_events.len();
1591 if cp_pending_msg_events.len() == 1 {
1592 if let MessageSendEvent::UpdateHTLCs { .. } = cp_pending_msg_events[0] {
1593 assert_ne!(*cp_id, node_b.node.get_our_node_id());
1594 } else { panic!("Unexpected event"); }
1597 // Expecting the failure backwards event to the previous hop (not `node_b`)
1598 assert_eq!(number_of_msg_events, 1);
1600 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
1604 /// Get a payment preimage and hash.
1605 pub fn get_payment_preimage_hash(recipient: &Node, min_value_msat: Option<u64>, min_final_cltv_expiry_delta: Option<u16>) -> (PaymentPreimage, PaymentHash, PaymentSecret) {
1606 let mut payment_count = recipient.network_payment_count.borrow_mut();
1607 let payment_preimage = PaymentPreimage([*payment_count; 32]);
1608 *payment_count += 1;
1609 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner());
1610 let payment_secret = recipient.node.create_inbound_payment_for_hash(payment_hash, min_value_msat, 7200, min_final_cltv_expiry_delta).unwrap();
1611 (payment_preimage, payment_hash, payment_secret)
1614 /// Get a payment preimage and hash.
1616 /// Don't use this, use the identically-named function instead.
1618 macro_rules! get_payment_preimage_hash {
1619 ($dest_node: expr) => {
1620 get_payment_preimage_hash!($dest_node, None)
1622 ($dest_node: expr, $min_value_msat: expr) => {
1623 crate::get_payment_preimage_hash!($dest_node, $min_value_msat, None)
1625 ($dest_node: expr, $min_value_msat: expr, $min_final_cltv_expiry_delta: expr) => {
1626 $crate::ln::functional_test_utils::get_payment_preimage_hash(&$dest_node, $min_value_msat, $min_final_cltv_expiry_delta)
1630 /// Gets a route from the given sender to the node described in `payment_params`.
1631 pub fn get_route(send_node: &Node, payment_params: &PaymentParameters, recv_value: u64, final_cltv_expiry_delta: u32) -> Result<Route, msgs::LightningError> {
1632 let scorer = TestScorer::new();
1633 let keys_manager = TestKeysInterface::new(&[0u8; 32], bitcoin::network::constants::Network::Testnet);
1634 let random_seed_bytes = keys_manager.get_secure_random_bytes();
1636 &send_node.node.get_our_node_id(), payment_params, &send_node.network_graph.read_only(),
1637 Some(&send_node.node.list_usable_channels().iter().collect::<Vec<_>>()),
1638 recv_value, final_cltv_expiry_delta, send_node.logger, &scorer, &random_seed_bytes
1642 /// Gets a route from the given sender to the node described in `payment_params`.
1644 /// Don't use this, use the identically-named function instead.
1646 macro_rules! get_route {
1647 ($send_node: expr, $payment_params: expr, $recv_value: expr, $cltv: expr) => {
1648 $crate::ln::functional_test_utils::get_route(&$send_node, &$payment_params, $recv_value, $cltv)
1654 macro_rules! get_route_and_payment_hash {
1655 ($send_node: expr, $recv_node: expr, $recv_value: expr) => {{
1656 let payment_params = $crate::routing::router::PaymentParameters::from_node_id($recv_node.node.get_our_node_id(), TEST_FINAL_CLTV)
1657 .with_features($recv_node.node.invoice_features());
1658 $crate::get_route_and_payment_hash!($send_node, $recv_node, payment_params, $recv_value, TEST_FINAL_CLTV)
1660 ($send_node: expr, $recv_node: expr, $payment_params: expr, $recv_value: expr, $cltv: expr) => {{
1661 let (payment_preimage, payment_hash, payment_secret) =
1662 $crate::ln::functional_test_utils::get_payment_preimage_hash(&$recv_node, Some($recv_value), None);
1663 let route = $crate::ln::functional_test_utils::get_route(&$send_node, &$payment_params, $recv_value, $cltv);
1664 (route.unwrap(), payment_hash, payment_preimage, payment_secret)
1669 #[cfg(any(test, feature = "_bench_unstable", feature = "_test_utils"))]
1670 macro_rules! expect_payment_claimable {
1671 ($node: expr, $expected_payment_hash: expr, $expected_payment_secret: expr, $expected_recv_value: expr) => {
1672 expect_payment_claimable!($node, $expected_payment_hash, $expected_payment_secret, $expected_recv_value, None, $node.node.get_our_node_id())
1674 ($node: expr, $expected_payment_hash: expr, $expected_payment_secret: expr, $expected_recv_value: expr, $expected_payment_preimage: expr, $expected_receiver_node_id: expr) => {
1675 let events = $node.node.get_and_clear_pending_events();
1676 assert_eq!(events.len(), 1);
1678 $crate::util::events::Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id: _, via_user_channel_id: _ } => {
1679 assert_eq!($expected_payment_hash, *payment_hash);
1680 assert_eq!($expected_recv_value, amount_msat);
1681 assert_eq!($expected_receiver_node_id, receiver_node_id.unwrap());
1683 $crate::util::events::PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1684 assert_eq!(&$expected_payment_preimage, payment_preimage);
1685 assert_eq!($expected_payment_secret, *payment_secret);
1690 _ => panic!("Unexpected event"),
1696 #[cfg(any(test, feature = "_bench_unstable", feature = "_test_utils"))]
1697 macro_rules! expect_payment_claimed {
1698 ($node: expr, $expected_payment_hash: expr, $expected_recv_value: expr) => {
1699 let events = $node.node.get_and_clear_pending_events();
1700 assert_eq!(events.len(), 1);
1702 $crate::util::events::Event::PaymentClaimed { ref payment_hash, amount_msat, .. } => {
1703 assert_eq!($expected_payment_hash, *payment_hash);
1704 assert_eq!($expected_recv_value, amount_msat);
1706 _ => panic!("Unexpected event"),
1713 macro_rules! expect_payment_sent_without_paths {
1714 ($node: expr, $expected_payment_preimage: expr) => {
1715 expect_payment_sent!($node, $expected_payment_preimage, None::<u64>, false);
1717 ($node: expr, $expected_payment_preimage: expr, $expected_fee_msat_opt: expr) => {
1718 expect_payment_sent!($node, $expected_payment_preimage, $expected_fee_msat_opt, false);
1723 macro_rules! expect_payment_sent {
1724 ($node: expr, $expected_payment_preimage: expr) => {
1725 $crate::expect_payment_sent!($node, $expected_payment_preimage, None::<u64>, true);
1727 ($node: expr, $expected_payment_preimage: expr, $expected_fee_msat_opt: expr) => {
1728 $crate::expect_payment_sent!($node, $expected_payment_preimage, $expected_fee_msat_opt, true);
1730 ($node: expr, $expected_payment_preimage: expr, $expected_fee_msat_opt: expr, $expect_paths: expr) => { {
1731 use bitcoin::hashes::Hash as _;
1732 let events = $node.node.get_and_clear_pending_events();
1733 let expected_payment_hash = $crate::ln::PaymentHash(
1734 bitcoin::hashes::sha256::Hash::hash(&$expected_payment_preimage.0).into_inner());
1736 assert!(events.len() > 1);
1738 assert_eq!(events.len(), 1);
1740 let expected_payment_id = match events[0] {
1741 $crate::util::events::Event::PaymentSent { ref payment_id, ref payment_preimage, ref payment_hash, ref fee_paid_msat } => {
1742 assert_eq!($expected_payment_preimage, *payment_preimage);
1743 assert_eq!(expected_payment_hash, *payment_hash);
1744 assert!(fee_paid_msat.is_some());
1745 if $expected_fee_msat_opt.is_some() {
1746 assert_eq!(*fee_paid_msat, $expected_fee_msat_opt);
1750 _ => panic!("Unexpected event"),
1753 for i in 1..events.len() {
1755 $crate::util::events::Event::PaymentPathSuccessful { payment_id, payment_hash, .. } => {
1756 assert_eq!(payment_id, expected_payment_id);
1757 assert_eq!(payment_hash, Some(expected_payment_hash));
1759 _ => panic!("Unexpected event"),
1768 macro_rules! expect_payment_path_successful {
1770 let events = $node.node.get_and_clear_pending_events();
1771 assert_eq!(events.len(), 1);
1773 $crate::util::events::Event::PaymentPathSuccessful { .. } => {},
1774 _ => panic!("Unexpected event"),
1779 macro_rules! expect_payment_forwarded {
1780 ($node: expr, $prev_node: expr, $next_node: expr, $expected_fee: expr, $upstream_force_closed: expr, $downstream_force_closed: expr) => {
1781 let events = $node.node.get_and_clear_pending_events();
1782 assert_eq!(events.len(), 1);
1784 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
1785 assert_eq!(fee_earned_msat, $expected_fee);
1786 if fee_earned_msat.is_some() {
1787 // Is the event prev_channel_id in one of the channels between the two nodes?
1788 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()));
1790 // We check for force closures since a force closed channel is removed from the
1791 // node's channel list
1792 if !$downstream_force_closed {
1793 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()));
1795 assert_eq!(claim_from_onchain_tx, $downstream_force_closed);
1797 _ => panic!("Unexpected event"),
1802 #[cfg(any(test, feature = "_bench_unstable", feature = "_test_utils"))]
1803 pub fn expect_channel_ready_event<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, expected_counterparty_node_id: &PublicKey) {
1804 let events = node.node.get_and_clear_pending_events();
1805 assert_eq!(events.len(), 1);
1807 crate::util::events::Event::ChannelReady{ ref counterparty_node_id, .. } => {
1808 assert_eq!(*expected_counterparty_node_id, *counterparty_node_id);
1810 _ => panic!("Unexpected event"),
1815 pub struct PaymentFailedConditions<'a> {
1816 pub(crate) expected_htlc_error_data: Option<(u16, &'a [u8])>,
1817 pub(crate) expected_blamed_scid: Option<u64>,
1818 pub(crate) expected_blamed_chan_closed: Option<bool>,
1819 pub(crate) expected_mpp_parts_remain: bool,
1822 impl<'a> PaymentFailedConditions<'a> {
1823 pub fn new() -> Self {
1825 expected_htlc_error_data: None,
1826 expected_blamed_scid: None,
1827 expected_blamed_chan_closed: None,
1828 expected_mpp_parts_remain: false,
1831 pub fn mpp_parts_remain(mut self) -> Self {
1832 self.expected_mpp_parts_remain = true;
1835 pub fn blamed_scid(mut self, scid: u64) -> Self {
1836 self.expected_blamed_scid = Some(scid);
1839 pub fn blamed_chan_closed(mut self, closed: bool) -> Self {
1840 self.expected_blamed_chan_closed = Some(closed);
1843 pub fn expected_htlc_error_data(mut self, code: u16, data: &'a [u8]) -> Self {
1844 self.expected_htlc_error_data = Some((code, data));
1850 macro_rules! expect_payment_failed_with_update {
1851 ($node: expr, $expected_payment_hash: expr, $payment_failed_permanently: expr, $scid: expr, $chan_closed: expr) => {
1852 $crate::ln::functional_test_utils::expect_payment_failed_conditions(
1853 &$node, $expected_payment_hash, $payment_failed_permanently,
1854 $crate::ln::functional_test_utils::PaymentFailedConditions::new()
1855 .blamed_scid($scid).blamed_chan_closed($chan_closed));
1860 macro_rules! expect_payment_failed {
1861 ($node: expr, $expected_payment_hash: expr, $payment_failed_permanently: expr $(, $expected_error_code: expr, $expected_error_data: expr)*) => {
1862 #[allow(unused_mut)]
1863 let mut conditions = $crate::ln::functional_test_utils::PaymentFailedConditions::new();
1865 conditions = conditions.expected_htlc_error_data($expected_error_code, &$expected_error_data);
1867 $crate::ln::functional_test_utils::expect_payment_failed_conditions(&$node, $expected_payment_hash, $payment_failed_permanently, conditions);
1871 pub fn expect_payment_failed_conditions_event<'a, 'b, 'c, 'd, 'e>(
1872 payment_failed_events: Vec<Event>, expected_payment_hash: PaymentHash,
1873 expected_payment_failed_permanently: bool, conditions: PaymentFailedConditions<'e>
1875 if conditions.expected_mpp_parts_remain { assert_eq!(payment_failed_events.len(), 1); } else { assert_eq!(payment_failed_events.len(), 2); }
1876 let expected_payment_id = match &payment_failed_events[0] {
1877 Event::PaymentPathFailed { payment_hash, payment_failed_permanently, payment_id, failure,
1881 error_data, .. } => {
1882 assert_eq!(*payment_hash, expected_payment_hash, "unexpected payment_hash");
1883 assert_eq!(*payment_failed_permanently, expected_payment_failed_permanently, "unexpected payment_failed_permanently value");
1886 assert!(error_code.is_some(), "expected error_code.is_some() = true");
1887 assert!(error_data.is_some(), "expected error_data.is_some() = true");
1888 if let Some((code, data)) = conditions.expected_htlc_error_data {
1889 assert_eq!(error_code.unwrap(), code, "unexpected error code");
1890 assert_eq!(&error_data.as_ref().unwrap()[..], data, "unexpected error data");
1894 if let Some(chan_closed) = conditions.expected_blamed_chan_closed {
1895 if let PathFailure::OnPath { network_update: Some(upd) } = failure {
1897 NetworkUpdate::ChannelUpdateMessage { ref msg } if !chan_closed => {
1898 if let Some(scid) = conditions.expected_blamed_scid {
1899 assert_eq!(msg.contents.short_channel_id, scid);
1901 const CHAN_DISABLED_FLAG: u8 = 2;
1902 assert_eq!(msg.contents.flags & CHAN_DISABLED_FLAG, 0);
1904 NetworkUpdate::ChannelFailure { short_channel_id, is_permanent } if chan_closed => {
1905 if let Some(scid) = conditions.expected_blamed_scid {
1906 assert_eq!(*short_channel_id, scid);
1908 assert!(is_permanent);
1910 _ => panic!("Unexpected update type"),
1912 } else { panic!("Expected network update"); }
1917 _ => panic!("Unexpected event"),
1919 if !conditions.expected_mpp_parts_remain {
1920 match &payment_failed_events[1] {
1921 Event::PaymentFailed { ref payment_hash, ref payment_id } => {
1922 assert_eq!(*payment_hash, expected_payment_hash, "unexpected second payment_hash");
1923 assert_eq!(*payment_id, expected_payment_id);
1925 _ => panic!("Unexpected second event"),
1930 pub fn expect_payment_failed_conditions<'a, 'b, 'c, 'd, 'e>(
1931 node: &'a Node<'b, 'c, 'd>, expected_payment_hash: PaymentHash, expected_payment_failed_permanently: bool,
1932 conditions: PaymentFailedConditions<'e>
1934 let events = node.node.get_and_clear_pending_events();
1935 expect_payment_failed_conditions_event(events, expected_payment_hash, expected_payment_failed_permanently, conditions);
1938 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 {
1939 let payment_id = PaymentId(origin_node.keys_manager.backing.get_secure_random_bytes());
1940 origin_node.node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), payment_id).unwrap();
1941 check_added_monitors!(origin_node, expected_paths.len());
1942 pass_along_route(origin_node, expected_paths, recv_value, our_payment_hash, our_payment_secret);
1946 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>) {
1947 let mut payment_event = SendEvent::from_event(ev);
1948 let mut prev_node = origin_node;
1950 for (idx, &node) in expected_path.iter().enumerate() {
1951 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
1953 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
1954 check_added_monitors!(node, 0);
1955 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
1957 expect_pending_htlcs_forwardable!(node);
1959 if idx == expected_path.len() - 1 && clear_recipient_events {
1960 let events_2 = node.node.get_and_clear_pending_events();
1961 if payment_claimable_expected {
1962 assert_eq!(events_2.len(), 1);
1964 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, ref via_channel_id, ref via_user_channel_id } => {
1965 assert_eq!(our_payment_hash, *payment_hash);
1966 assert_eq!(node.node.get_our_node_id(), receiver_node_id.unwrap());
1968 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1969 assert_eq!(expected_preimage, *payment_preimage);
1970 assert_eq!(our_payment_secret.unwrap(), *payment_secret);
1972 PaymentPurpose::SpontaneousPayment(payment_preimage) => {
1973 assert_eq!(expected_preimage.unwrap(), *payment_preimage);
1974 assert!(our_payment_secret.is_none());
1977 assert_eq!(amount_msat, recv_value);
1978 assert!(node.node.list_channels().iter().any(|details| details.channel_id == via_channel_id.unwrap()));
1979 assert!(node.node.list_channels().iter().any(|details| details.user_channel_id == via_user_channel_id.unwrap()));
1981 _ => panic!("Unexpected event"),
1984 assert!(events_2.is_empty());
1986 } else if idx != expected_path.len() - 1 {
1987 let mut events_2 = node.node.get_and_clear_pending_msg_events();
1988 assert_eq!(events_2.len(), 1);
1989 check_added_monitors!(node, 1);
1990 payment_event = SendEvent::from_event(events_2.remove(0));
1991 assert_eq!(payment_event.msgs.len(), 1);
1998 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>) {
1999 do_pass_along_path(origin_node, expected_path, recv_value, our_payment_hash, our_payment_secret, ev, payment_claimable_expected, true, expected_preimage);
2002 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) {
2003 let mut events = origin_node.node.get_and_clear_pending_msg_events();
2004 assert_eq!(events.len(), expected_route.len());
2005 for (path_idx, expected_path) in expected_route.iter().enumerate() {
2006 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
2007 // Once we've gotten through all the HTLCs, the last one should result in a
2008 // PaymentClaimable (but each previous one should not!), .
2009 let expect_payment = path_idx == expected_route.len() - 1;
2010 pass_along_path(origin_node, expected_path, recv_value, our_payment_hash.clone(), Some(our_payment_secret), ev, expect_payment, None);
2014 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) {
2015 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(expected_route.last().unwrap());
2016 let payment_id = send_along_route_with_secret(origin_node, route, &[expected_route], recv_value, our_payment_hash, our_payment_secret);
2017 (our_payment_preimage, our_payment_hash, our_payment_secret, payment_id)
2020 pub fn do_claim_payment_along_route<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_paths: &[&[&Node<'a, 'b, 'c>]], skip_last: bool, our_payment_preimage: PaymentPreimage) -> u64 {
2021 for path in expected_paths.iter() {
2022 assert_eq!(path.last().unwrap().node.get_our_node_id(), expected_paths[0].last().unwrap().node.get_our_node_id());
2024 expected_paths[0].last().unwrap().node.claim_funds(our_payment_preimage);
2026 let claim_event = expected_paths[0].last().unwrap().node.get_and_clear_pending_events();
2027 assert_eq!(claim_event.len(), 1);
2028 match claim_event[0] {
2029 Event::PaymentClaimed { purpose: PaymentPurpose::SpontaneousPayment(preimage), .. }|
2030 Event::PaymentClaimed { purpose: PaymentPurpose::InvoicePayment { payment_preimage: Some(preimage), ..}, .. } =>
2031 assert_eq!(preimage, our_payment_preimage),
2032 Event::PaymentClaimed { purpose: PaymentPurpose::InvoicePayment { .. }, payment_hash, .. } =>
2033 assert_eq!(&payment_hash.0, &Sha256::hash(&our_payment_preimage.0)[..]),
2037 check_added_monitors!(expected_paths[0].last().unwrap(), expected_paths.len());
2039 let mut expected_total_fee_msat = 0;
2041 macro_rules! msgs_from_ev {
2044 &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 } } => {
2045 assert!(update_add_htlcs.is_empty());
2046 assert_eq!(update_fulfill_htlcs.len(), 1);
2047 assert!(update_fail_htlcs.is_empty());
2048 assert!(update_fail_malformed_htlcs.is_empty());
2049 assert!(update_fee.is_none());
2050 ((update_fulfill_htlcs[0].clone(), commitment_signed.clone()), node_id.clone())
2052 _ => panic!("Unexpected event"),
2056 let mut per_path_msgs: Vec<((msgs::UpdateFulfillHTLC, msgs::CommitmentSigned), PublicKey)> = Vec::with_capacity(expected_paths.len());
2057 let mut events = expected_paths[0].last().unwrap().node.get_and_clear_pending_msg_events();
2058 assert_eq!(events.len(), expected_paths.len());
2060 if events.len() == 1 {
2061 per_path_msgs.push(msgs_from_ev!(&events[0]));
2063 for expected_path in expected_paths.iter() {
2064 // For MPP payments, we always want the message to the first node in the path.
2065 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
2066 per_path_msgs.push(msgs_from_ev!(&ev));
2070 for (expected_route, (path_msgs, next_hop)) in expected_paths.iter().zip(per_path_msgs.drain(..)) {
2071 let mut next_msgs = Some(path_msgs);
2072 let mut expected_next_node = next_hop;
2074 macro_rules! last_update_fulfill_dance {
2075 ($node: expr, $prev_node: expr) => {
2077 $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0);
2078 check_added_monitors!($node, 0);
2079 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
2080 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
2084 macro_rules! mid_update_fulfill_dance {
2085 ($node: expr, $prev_node: expr, $next_node: expr, $new_msgs: expr) => {
2087 $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0);
2089 let per_peer_state = $node.node.per_peer_state.read().unwrap();
2090 let peer_state = per_peer_state.get(&$prev_node.node.get_our_node_id())
2091 .unwrap().lock().unwrap();
2092 let channel = peer_state.channel_by_id.get(&next_msgs.as_ref().unwrap().0.channel_id).unwrap();
2093 if let Some(prev_config) = channel.prev_config() {
2094 prev_config.forwarding_fee_base_msat
2096 channel.config().forwarding_fee_base_msat
2099 expect_payment_forwarded!($node, $next_node, $prev_node, Some(fee as u64), false, false);
2100 expected_total_fee_msat += fee as u64;
2101 check_added_monitors!($node, 1);
2102 let new_next_msgs = if $new_msgs {
2103 let events = $node.node.get_and_clear_pending_msg_events();
2104 assert_eq!(events.len(), 1);
2105 let (res, nexthop) = msgs_from_ev!(&events[0]);
2106 expected_next_node = nexthop;
2109 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
2112 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
2113 next_msgs = new_next_msgs;
2118 let mut prev_node = expected_route.last().unwrap();
2119 for (idx, node) in expected_route.iter().rev().enumerate().skip(1) {
2120 assert_eq!(expected_next_node, node.node.get_our_node_id());
2121 let update_next_msgs = !skip_last || idx != expected_route.len() - 1;
2122 if next_msgs.is_some() {
2123 // Since we are traversing in reverse, next_node is actually the previous node
2124 let next_node: &Node;
2125 if idx == expected_route.len() - 1 {
2126 next_node = origin_node;
2128 next_node = expected_route[expected_route.len() - 1 - idx - 1];
2130 mid_update_fulfill_dance!(node, prev_node, next_node, update_next_msgs);
2132 assert!(!update_next_msgs);
2133 assert!(node.node.get_and_clear_pending_msg_events().is_empty());
2135 if !skip_last && idx == expected_route.len() - 1 {
2136 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
2143 last_update_fulfill_dance!(origin_node, expected_route.first().unwrap());
2147 // Ensure that claim_funds is idempotent.
2148 expected_paths[0].last().unwrap().node.claim_funds(our_payment_preimage);
2149 assert!(expected_paths[0].last().unwrap().node.get_and_clear_pending_msg_events().is_empty());
2150 check_added_monitors!(expected_paths[0].last().unwrap(), 0);
2152 expected_total_fee_msat
2154 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) {
2155 let expected_total_fee_msat = do_claim_payment_along_route(origin_node, expected_paths, skip_last, our_payment_preimage);
2157 expect_payment_sent!(origin_node, our_payment_preimage, Some(expected_total_fee_msat));
2161 pub fn claim_payment<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_route: &[&Node<'a, 'b, 'c>], our_payment_preimage: PaymentPreimage) {
2162 claim_payment_along_route(origin_node, &[expected_route], false, our_payment_preimage);
2165 pub const TEST_FINAL_CLTV: u32 = 70;
2167 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) {
2168 let payment_params = PaymentParameters::from_node_id(expected_route.last().unwrap().node.get_our_node_id(), TEST_FINAL_CLTV)
2169 .with_features(expected_route.last().unwrap().node.invoice_features());
2170 let route = get_route(origin_node, &payment_params, recv_value, TEST_FINAL_CLTV).unwrap();
2171 assert_eq!(route.paths.len(), 1);
2172 assert_eq!(route.paths[0].len(), expected_route.len());
2173 for (node, hop) in expected_route.iter().zip(route.paths[0].iter()) {
2174 assert_eq!(hop.pubkey, node.node.get_our_node_id());
2177 let res = send_along_route(origin_node, route, expected_route, recv_value);
2178 (res.0, res.1, res.2)
2181 pub fn route_over_limit<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_route: &[&Node<'a, 'b, 'c>], recv_value: u64) {
2182 let payment_params = PaymentParameters::from_node_id(expected_route.last().unwrap().node.get_our_node_id(), TEST_FINAL_CLTV)
2183 .with_features(expected_route.last().unwrap().node.invoice_features());
2184 let network_graph = origin_node.network_graph.read_only();
2185 let scorer = test_utils::TestScorer::new();
2186 let seed = [0u8; 32];
2187 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
2188 let random_seed_bytes = keys_manager.get_secure_random_bytes();
2189 let route = router::get_route(
2190 &origin_node.node.get_our_node_id(), &payment_params, &network_graph,
2191 None, recv_value, TEST_FINAL_CLTV, origin_node.logger, &scorer, &random_seed_bytes).unwrap();
2192 assert_eq!(route.paths.len(), 1);
2193 assert_eq!(route.paths[0].len(), expected_route.len());
2194 for (node, hop) in expected_route.iter().zip(route.paths[0].iter()) {
2195 assert_eq!(hop.pubkey, node.node.get_our_node_id());
2198 let (_, our_payment_hash, our_payment_preimage) = get_payment_preimage_hash!(expected_route.last().unwrap());
2199 unwrap_send_err!(origin_node.node.send_payment(&route, our_payment_hash, &Some(our_payment_preimage), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
2200 assert!(err.contains("Cannot send value that would put us over the max HTLC value in flight our peer will accept")));
2203 pub fn send_payment<'a, 'b, 'c>(origin: &Node<'a, 'b, 'c>, expected_route: &[&Node<'a, 'b, 'c>], recv_value: u64) -> (PaymentPreimage, PaymentHash, PaymentSecret) {
2204 let res = route_payment(&origin, expected_route, recv_value);
2205 claim_payment(&origin, expected_route, res.0);
2209 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) {
2210 for path in expected_paths.iter() {
2211 assert_eq!(path.last().unwrap().node.get_our_node_id(), expected_paths[0].last().unwrap().node.get_our_node_id());
2213 expected_paths[0].last().unwrap().node.fail_htlc_backwards(&our_payment_hash);
2214 let expected_destinations: Vec<HTLCDestination> = repeat(HTLCDestination::FailedPayment { payment_hash: our_payment_hash }).take(expected_paths.len()).collect();
2215 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(expected_paths[0].last().unwrap(), expected_destinations);
2217 pass_failed_payment_back(origin_node, expected_paths, skip_last, our_payment_hash);
2220 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) {
2221 let mut expected_paths: Vec<_> = expected_paths_slice.iter().collect();
2222 check_added_monitors!(expected_paths[0].last().unwrap(), expected_paths.len());
2224 let mut per_path_msgs: Vec<((msgs::UpdateFailHTLC, msgs::CommitmentSigned), PublicKey)> = Vec::with_capacity(expected_paths.len());
2225 let events = expected_paths[0].last().unwrap().node.get_and_clear_pending_msg_events();
2226 assert_eq!(events.len(), expected_paths.len());
2227 for ev in events.iter() {
2228 let (update_fail, commitment_signed, node_id) = match ev {
2229 &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 } } => {
2230 assert!(update_add_htlcs.is_empty());
2231 assert!(update_fulfill_htlcs.is_empty());
2232 assert_eq!(update_fail_htlcs.len(), 1);
2233 assert!(update_fail_malformed_htlcs.is_empty());
2234 assert!(update_fee.is_none());
2235 (update_fail_htlcs[0].clone(), commitment_signed.clone(), node_id.clone())
2237 _ => panic!("Unexpected event"),
2239 per_path_msgs.push(((update_fail, commitment_signed), node_id));
2241 per_path_msgs.sort_unstable_by(|(_, node_id_a), (_, node_id_b)| node_id_a.cmp(node_id_b));
2242 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()));
2244 for (i, (expected_route, (path_msgs, next_hop))) in expected_paths.iter().zip(per_path_msgs.drain(..)).enumerate() {
2245 let mut next_msgs = Some(path_msgs);
2246 let mut expected_next_node = next_hop;
2247 let mut prev_node = expected_route.last().unwrap();
2249 for (idx, node) in expected_route.iter().rev().enumerate().skip(1) {
2250 assert_eq!(expected_next_node, node.node.get_our_node_id());
2251 let update_next_node = !skip_last || idx != expected_route.len() - 1;
2252 if next_msgs.is_some() {
2253 node.node.handle_update_fail_htlc(&prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0);
2254 commitment_signed_dance!(node, prev_node, next_msgs.as_ref().unwrap().1, update_next_node);
2255 if !update_next_node {
2256 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 }]);
2259 let events = node.node.get_and_clear_pending_msg_events();
2260 if update_next_node {
2261 assert_eq!(events.len(), 1);
2263 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 } } => {
2264 assert!(update_add_htlcs.is_empty());
2265 assert!(update_fulfill_htlcs.is_empty());
2266 assert_eq!(update_fail_htlcs.len(), 1);
2267 assert!(update_fail_malformed_htlcs.is_empty());
2268 assert!(update_fee.is_none());
2269 expected_next_node = node_id.clone();
2270 next_msgs = Some((update_fail_htlcs[0].clone(), commitment_signed.clone()));
2272 _ => panic!("Unexpected event"),
2275 assert!(events.is_empty());
2277 if !skip_last && idx == expected_route.len() - 1 {
2278 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
2285 let prev_node = expected_route.first().unwrap();
2286 origin_node.node.handle_update_fail_htlc(&prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0);
2287 check_added_monitors!(origin_node, 0);
2288 assert!(origin_node.node.get_and_clear_pending_msg_events().is_empty());
2289 commitment_signed_dance!(origin_node, prev_node, next_msgs.as_ref().unwrap().1, false);
2290 let events = origin_node.node.get_and_clear_pending_events();
2291 if i == expected_paths.len() - 1 { assert_eq!(events.len(), 2); } else { assert_eq!(events.len(), 1); }
2293 let expected_payment_id = match events[0] {
2294 Event::PaymentPathFailed { payment_hash, payment_failed_permanently, ref path, ref payment_id, .. } => {
2295 assert_eq!(payment_hash, our_payment_hash);
2296 assert!(payment_failed_permanently);
2297 for (idx, hop) in expected_route.iter().enumerate() {
2298 assert_eq!(hop.node.get_our_node_id(), path[idx].pubkey);
2302 _ => panic!("Unexpected event"),
2304 if i == expected_paths.len() - 1 {
2306 Event::PaymentFailed { ref payment_hash, ref payment_id } => {
2307 assert_eq!(*payment_hash, our_payment_hash, "unexpected second payment_hash");
2308 assert_eq!(*payment_id, expected_payment_id);
2310 _ => panic!("Unexpected second event"),
2316 // Ensure that fail_htlc_backwards is idempotent.
2317 expected_paths[0].last().unwrap().node.fail_htlc_backwards(&our_payment_hash);
2318 assert!(expected_paths[0].last().unwrap().node.get_and_clear_pending_events().is_empty());
2319 assert!(expected_paths[0].last().unwrap().node.get_and_clear_pending_msg_events().is_empty());
2320 check_added_monitors!(expected_paths[0].last().unwrap(), 0);
2323 pub fn fail_payment<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_path: &[&Node<'a, 'b, 'c>], our_payment_hash: PaymentHash) {
2324 fail_payment_along_route(origin_node, &[&expected_path[..]], false, our_payment_hash);
2327 pub fn create_chanmon_cfgs(node_count: usize) -> Vec<TestChanMonCfg> {
2328 let mut chan_mon_cfgs = Vec::new();
2329 for i in 0..node_count {
2330 let tx_broadcaster = test_utils::TestBroadcaster {
2331 txn_broadcasted: Mutex::new(Vec::new()),
2332 blocks: Arc::new(Mutex::new(vec![(genesis_block(Network::Testnet), 0)])),
2334 let fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
2335 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
2336 let logger = test_utils::TestLogger::with_id(format!("node {}", i));
2337 let persister = test_utils::TestPersister::new();
2338 let seed = [i as u8; 32];
2339 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
2340 let scorer = Mutex::new(test_utils::TestScorer::new());
2342 chan_mon_cfgs.push(TestChanMonCfg { tx_broadcaster, fee_estimator, chain_source, logger, persister, keys_manager, scorer });
2348 pub fn create_node_cfgs<'a>(node_count: usize, chanmon_cfgs: &'a Vec<TestChanMonCfg>) -> Vec<NodeCfg<'a>> {
2349 let mut nodes = Vec::new();
2351 for i in 0..node_count {
2352 let chain_monitor = test_utils::TestChainMonitor::new(Some(&chanmon_cfgs[i].chain_source), &chanmon_cfgs[i].tx_broadcaster, &chanmon_cfgs[i].logger, &chanmon_cfgs[i].fee_estimator, &chanmon_cfgs[i].persister, &chanmon_cfgs[i].keys_manager);
2353 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[i].logger));
2354 let seed = [i as u8; 32];
2355 nodes.push(NodeCfg {
2356 chain_source: &chanmon_cfgs[i].chain_source,
2357 logger: &chanmon_cfgs[i].logger,
2358 tx_broadcaster: &chanmon_cfgs[i].tx_broadcaster,
2359 fee_estimator: &chanmon_cfgs[i].fee_estimator,
2360 router: test_utils::TestRouter::new(network_graph.clone(), &chanmon_cfgs[i].scorer),
2362 keys_manager: &chanmon_cfgs[i].keys_manager,
2365 override_init_features: Rc::new(RefCell::new(None)),
2372 pub fn test_default_channel_config() -> UserConfig {
2373 let mut default_config = UserConfig::default();
2374 // Set cltv_expiry_delta slightly lower to keep the final CLTV values inside one byte in our
2375 // tests so that our script-length checks don't fail (see ACCEPTED_HTLC_SCRIPT_WEIGHT).
2376 default_config.channel_config.cltv_expiry_delta = MIN_CLTV_EXPIRY_DELTA;
2377 default_config.channel_handshake_config.announced_channel = true;
2378 default_config.channel_handshake_limits.force_announced_channel_preference = false;
2379 // When most of our tests were written, the default HTLC minimum was fixed at 1000.
2380 // It now defaults to 1, so we simply set it to the expected value here.
2381 default_config.channel_handshake_config.our_htlc_minimum_msat = 1000;
2382 // When most of our tests were written, we didn't have the notion of a `max_dust_htlc_exposure_msat`,
2383 // It now defaults to 5_000_000 msat; to avoid interfering with tests we bump it to 50_000_000 msat.
2384 default_config.channel_config.max_dust_htlc_exposure_msat = 50_000_000;
2388 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>> {
2389 let mut chanmgrs = Vec::new();
2390 for i in 0..node_count {
2391 let network = Network::Testnet;
2392 let params = ChainParameters {
2394 best_block: BestBlock::from_network(network),
2396 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,
2397 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);
2398 chanmgrs.push(node);
2404 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>> {
2405 let mut nodes = Vec::new();
2406 let chan_count = Rc::new(RefCell::new(0));
2407 let payment_count = Rc::new(RefCell::new(0));
2408 let connect_style = Rc::new(RefCell::new(ConnectStyle::random_style()));
2410 for i in 0..node_count {
2411 let gossip_sync = P2PGossipSync::new(cfgs[i].network_graph.as_ref(), None, cfgs[i].logger);
2413 chain_source: cfgs[i].chain_source, tx_broadcaster: cfgs[i].tx_broadcaster,
2414 fee_estimator: cfgs[i].fee_estimator, router: &cfgs[i].router,
2415 chain_monitor: &cfgs[i].chain_monitor, keys_manager: &cfgs[i].keys_manager,
2416 node: &chan_mgrs[i], network_graph: cfgs[i].network_graph.as_ref(), gossip_sync,
2417 node_seed: cfgs[i].node_seed, network_chan_count: chan_count.clone(),
2418 network_payment_count: payment_count.clone(), logger: cfgs[i].logger,
2419 blocks: Arc::clone(&cfgs[i].tx_broadcaster.blocks),
2420 connect_style: Rc::clone(&connect_style),
2421 override_init_features: Rc::clone(&cfgs[i].override_init_features),
2425 for i in 0..node_count {
2426 for j in (i+1)..node_count {
2427 nodes[i].node.peer_connected(&nodes[j].node.get_our_node_id(), &msgs::Init { features: nodes[j].override_init_features.borrow().clone().unwrap_or_else(|| nodes[j].node.init_features()), remote_network_address: None }, true).unwrap();
2428 nodes[j].node.peer_connected(&nodes[i].node.get_our_node_id(), &msgs::Init { features: nodes[i].override_init_features.borrow().clone().unwrap_or_else(|| nodes[i].node.init_features()), remote_network_address: None }, false).unwrap();
2435 // Note that the following only works for CLTV values up to 128
2436 pub const ACCEPTED_HTLC_SCRIPT_WEIGHT: usize = 137; //Here we have a diff due to HTLC CLTV expiry being < 2^15 in test
2438 #[derive(PartialEq)]
2439 pub enum HTLCType { NONE, TIMEOUT, SUCCESS }
2440 /// Tests that the given node has broadcast transactions for the given Channel
2442 /// First checks that the latest holder commitment tx has been broadcast, unless an explicit
2443 /// commitment_tx is provided, which may be used to test that a remote commitment tx was
2444 /// broadcast and the revoked outputs were claimed.
2446 /// Next tests that there is (or is not) a transaction that spends the commitment transaction
2447 /// that appears to be the type of HTLC transaction specified in has_htlc_tx.
2449 /// All broadcast transactions must be accounted for in one of the above three types of we'll
2451 pub fn test_txn_broadcast<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, chan: &(msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction), commitment_tx: Option<Transaction>, has_htlc_tx: HTLCType) -> Vec<Transaction> {
2452 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2453 assert!(node_txn.len() >= if commitment_tx.is_some() { 0 } else { 1 } + if has_htlc_tx == HTLCType::NONE { 0 } else { 1 });
2455 let mut res = Vec::with_capacity(2);
2456 node_txn.retain(|tx| {
2457 if tx.input.len() == 1 && tx.input[0].previous_output.txid == chan.3.txid() {
2458 check_spends!(tx, chan.3);
2459 if commitment_tx.is_none() {
2460 res.push(tx.clone());
2465 if let Some(explicit_tx) = commitment_tx {
2466 res.push(explicit_tx.clone());
2469 assert_eq!(res.len(), 1);
2471 if has_htlc_tx != HTLCType::NONE {
2472 node_txn.retain(|tx| {
2473 if tx.input.len() == 1 && tx.input[0].previous_output.txid == res[0].txid() {
2474 check_spends!(tx, res[0]);
2475 if has_htlc_tx == HTLCType::TIMEOUT {
2476 assert!(tx.lock_time.0 != 0);
2478 assert!(tx.lock_time.0 == 0);
2480 res.push(tx.clone());
2484 assert!(res.len() == 2 || res.len() == 3);
2486 assert_eq!(res[1], res[2]);
2490 assert!(node_txn.is_empty());
2494 /// Tests that the given node has broadcast a claim transaction against the provided revoked
2495 /// HTLC transaction.
2496 pub fn test_revoked_htlc_claim_txn_broadcast<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, revoked_tx: Transaction, commitment_revoked_tx: Transaction) {
2497 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2498 // We may issue multiple claiming transaction on revoked outputs due to block rescan
2499 // for revoked htlc outputs
2500 if node_txn.len() != 1 && node_txn.len() != 2 && node_txn.len() != 3 { assert!(false); }
2501 node_txn.retain(|tx| {
2502 if tx.input.len() == 1 && tx.input[0].previous_output.txid == revoked_tx.txid() {
2503 check_spends!(tx, revoked_tx);
2507 node_txn.retain(|tx| {
2508 check_spends!(tx, commitment_revoked_tx);
2511 assert!(node_txn.is_empty());
2514 pub fn check_preimage_claim<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, prev_txn: &Vec<Transaction>) -> Vec<Transaction> {
2515 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2517 assert!(node_txn.len() >= 1);
2518 assert_eq!(node_txn[0].input.len(), 1);
2519 let mut found_prev = false;
2521 for tx in prev_txn {
2522 if node_txn[0].input[0].previous_output.txid == tx.txid() {
2523 check_spends!(node_txn[0], tx);
2524 let mut iter = node_txn[0].input[0].witness.iter();
2525 iter.next().expect("expected 3 witness items");
2526 iter.next().expect("expected 3 witness items");
2527 assert!(iter.next().expect("expected 3 witness items").len() > 106); // must spend an htlc output
2528 assert_eq!(tx.input.len(), 1); // must spend a commitment tx
2534 assert!(found_prev);
2536 let mut res = Vec::new();
2537 mem::swap(&mut *node_txn, &mut res);
2541 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) {
2542 let events_1 = nodes[a].node.get_and_clear_pending_msg_events();
2543 assert_eq!(events_1.len(), 2);
2544 let as_update = match events_1[0] {
2545 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2548 _ => panic!("Unexpected event"),
2551 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
2552 assert_eq!(node_id, nodes[b].node.get_our_node_id());
2553 assert_eq!(msg.data, expected_error);
2554 if needs_err_handle {
2555 nodes[b].node.handle_error(&nodes[a].node.get_our_node_id(), msg);
2558 _ => panic!("Unexpected event"),
2561 let events_2 = nodes[b].node.get_and_clear_pending_msg_events();
2562 assert_eq!(events_2.len(), if needs_err_handle { 1 } else { 2 });
2563 let bs_update = match events_2[0] {
2564 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2567 _ => panic!("Unexpected event"),
2569 if !needs_err_handle {
2571 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
2572 assert_eq!(node_id, nodes[a].node.get_our_node_id());
2573 assert_eq!(msg.data, expected_error);
2575 _ => panic!("Unexpected event"),
2580 node.gossip_sync.handle_channel_update(&as_update).unwrap();
2581 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
2585 pub fn get_announce_close_broadcast_events<'a, 'b, 'c>(nodes: &Vec<Node<'a, 'b, 'c>>, a: usize, b: usize) {
2586 handle_announce_close_broadcast_events(nodes, a, b, false, "Channel closed because commitment or closing transaction was confirmed on chain.");
2590 macro_rules! get_channel_value_stat {
2591 ($node: expr, $counterparty_node: expr, $channel_id: expr) => {{
2592 let peer_state_lock = $node.node.per_peer_state.read().unwrap();
2593 let chan_lock = peer_state_lock.get(&$counterparty_node.node.get_our_node_id()).unwrap().lock().unwrap();
2594 let chan = chan_lock.channel_by_id.get(&$channel_id).unwrap();
2595 chan.get_value_stat()
2599 macro_rules! get_chan_reestablish_msgs {
2600 ($src_node: expr, $dst_node: expr) => {
2602 let mut announcements = $crate::prelude::HashSet::new();
2603 let mut res = Vec::with_capacity(1);
2604 for msg in $src_node.node.get_and_clear_pending_msg_events() {
2605 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
2606 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2607 res.push(msg.clone());
2608 } else if let MessageSendEvent::SendChannelAnnouncement { ref node_id, ref msg, .. } = msg {
2609 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2610 announcements.insert(msg.contents.short_channel_id);
2612 panic!("Unexpected event")
2615 for chan in $src_node.node.list_channels() {
2616 if chan.is_public && chan.counterparty.node_id != $dst_node.node.get_our_node_id() {
2617 if let Some(scid) = chan.short_channel_id {
2618 assert!(announcements.remove(&scid));
2622 assert!(announcements.is_empty());
2628 macro_rules! handle_chan_reestablish_msgs {
2629 ($src_node: expr, $dst_node: expr) => {
2631 let msg_events = $src_node.node.get_and_clear_pending_msg_events();
2633 let channel_ready = if let Some(&MessageSendEvent::SendChannelReady { ref node_id, ref msg }) = msg_events.get(0) {
2635 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2641 if let Some(&MessageSendEvent::SendAnnouncementSignatures { ref node_id, msg: _ }) = msg_events.get(idx) {
2643 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2646 let mut had_channel_update = false; // ChannelUpdate may be now or later, but not both
2647 if let Some(&MessageSendEvent::SendChannelUpdate { ref node_id, ref msg }) = msg_events.get(idx) {
2648 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2650 assert_eq!(msg.contents.flags & 2, 0); // "disabled" flag must not be set as we just reconnected.
2651 had_channel_update = true;
2654 let mut revoke_and_ack = None;
2655 let mut commitment_update = None;
2656 let order = if let Some(ev) = msg_events.get(idx) {
2658 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
2659 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2660 revoke_and_ack = Some(msg.clone());
2662 RAACommitmentOrder::RevokeAndACKFirst
2664 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
2665 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2666 commitment_update = Some(updates.clone());
2668 RAACommitmentOrder::CommitmentFirst
2670 _ => RAACommitmentOrder::CommitmentFirst,
2673 RAACommitmentOrder::CommitmentFirst
2676 if let Some(ev) = msg_events.get(idx) {
2678 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
2679 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2680 assert!(revoke_and_ack.is_none());
2681 revoke_and_ack = Some(msg.clone());
2684 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
2685 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2686 assert!(commitment_update.is_none());
2687 commitment_update = Some(updates.clone());
2694 if let Some(&MessageSendEvent::SendChannelUpdate { ref node_id, ref msg }) = msg_events.get(idx) {
2695 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2697 assert_eq!(msg.contents.flags & 2, 0); // "disabled" flag must not be set as we just reconnected.
2698 assert!(!had_channel_update);
2701 assert_eq!(msg_events.len(), idx);
2703 (channel_ready, revoke_and_ack, commitment_update, order)
2708 /// pending_htlc_adds includes both the holding cell and in-flight update_add_htlcs, whereas
2709 /// for claims/fails they are separated out.
2710 pub fn reconnect_nodes<'a, 'b, 'c>(node_a: &Node<'a, 'b, 'c>, node_b: &Node<'a, 'b, 'c>, send_channel_ready: (bool, bool), pending_htlc_adds: (i64, i64), pending_htlc_claims: (usize, usize), pending_htlc_fails: (usize, usize), pending_cell_htlc_claims: (usize, usize), pending_cell_htlc_fails: (usize, usize), pending_raa: (bool, bool)) {
2711 node_a.node.peer_connected(&node_b.node.get_our_node_id(), &msgs::Init { features: node_b.node.init_features(), remote_network_address: None }, true).unwrap();
2712 let reestablish_1 = get_chan_reestablish_msgs!(node_a, node_b);
2713 node_b.node.peer_connected(&node_a.node.get_our_node_id(), &msgs::Init { features: node_a.node.init_features(), remote_network_address: None }, false).unwrap();
2714 let reestablish_2 = get_chan_reestablish_msgs!(node_b, node_a);
2716 if send_channel_ready.0 {
2717 // If a expects a channel_ready, it better not think it has received a revoke_and_ack
2719 for reestablish in reestablish_1.iter() {
2720 assert_eq!(reestablish.next_remote_commitment_number, 0);
2723 if send_channel_ready.1 {
2724 // If b expects a channel_ready, it better not think it has received a revoke_and_ack
2726 for reestablish in reestablish_2.iter() {
2727 assert_eq!(reestablish.next_remote_commitment_number, 0);
2730 if send_channel_ready.0 || send_channel_ready.1 {
2731 // If we expect any channel_ready's, both sides better have set
2732 // next_holder_commitment_number to 1
2733 for reestablish in reestablish_1.iter() {
2734 assert_eq!(reestablish.next_local_commitment_number, 1);
2736 for reestablish in reestablish_2.iter() {
2737 assert_eq!(reestablish.next_local_commitment_number, 1);
2741 let mut resp_1 = Vec::new();
2742 for msg in reestablish_1 {
2743 node_b.node.handle_channel_reestablish(&node_a.node.get_our_node_id(), &msg);
2744 resp_1.push(handle_chan_reestablish_msgs!(node_b, node_a));
2746 if pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
2747 check_added_monitors!(node_b, 1);
2749 check_added_monitors!(node_b, 0);
2752 let mut resp_2 = Vec::new();
2753 for msg in reestablish_2 {
2754 node_a.node.handle_channel_reestablish(&node_b.node.get_our_node_id(), &msg);
2755 resp_2.push(handle_chan_reestablish_msgs!(node_a, node_b));
2757 if pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
2758 check_added_monitors!(node_a, 1);
2760 check_added_monitors!(node_a, 0);
2763 // We don't yet support both needing updates, as that would require a different commitment dance:
2764 assert!((pending_htlc_adds.0 == 0 && pending_htlc_claims.0 == 0 && pending_htlc_fails.0 == 0 &&
2765 pending_cell_htlc_claims.0 == 0 && pending_cell_htlc_fails.0 == 0) ||
2766 (pending_htlc_adds.1 == 0 && pending_htlc_claims.1 == 0 && pending_htlc_fails.1 == 0 &&
2767 pending_cell_htlc_claims.1 == 0 && pending_cell_htlc_fails.1 == 0));
2769 for chan_msgs in resp_1.drain(..) {
2770 if send_channel_ready.0 {
2771 node_a.node.handle_channel_ready(&node_b.node.get_our_node_id(), &chan_msgs.0.unwrap());
2772 let announcement_event = node_a.node.get_and_clear_pending_msg_events();
2773 if !announcement_event.is_empty() {
2774 assert_eq!(announcement_event.len(), 1);
2775 if let MessageSendEvent::SendChannelUpdate { .. } = announcement_event[0] {
2776 //TODO: Test announcement_sigs re-sending
2777 } else { panic!("Unexpected event! {:?}", announcement_event[0]); }
2780 assert!(chan_msgs.0.is_none());
2783 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
2784 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap());
2785 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
2786 check_added_monitors!(node_a, 1);
2788 assert!(chan_msgs.1.is_none());
2790 if pending_htlc_adds.0 != 0 || pending_htlc_claims.0 != 0 || pending_htlc_fails.0 != 0 || pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
2791 let commitment_update = chan_msgs.2.unwrap();
2792 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
2793 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.0 as usize);
2795 assert!(commitment_update.update_add_htlcs.is_empty());
2797 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
2798 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_htlc_fails.0 + pending_cell_htlc_fails.0);
2799 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
2800 for update_add in commitment_update.update_add_htlcs {
2801 node_a.node.handle_update_add_htlc(&node_b.node.get_our_node_id(), &update_add);
2803 for update_fulfill in commitment_update.update_fulfill_htlcs {
2804 node_a.node.handle_update_fulfill_htlc(&node_b.node.get_our_node_id(), &update_fulfill);
2806 for update_fail in commitment_update.update_fail_htlcs {
2807 node_a.node.handle_update_fail_htlc(&node_b.node.get_our_node_id(), &update_fail);
2810 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
2811 commitment_signed_dance!(node_a, node_b, commitment_update.commitment_signed, false);
2813 node_a.node.handle_commitment_signed(&node_b.node.get_our_node_id(), &commitment_update.commitment_signed);
2814 check_added_monitors!(node_a, 1);
2815 let as_revoke_and_ack = get_event_msg!(node_a, MessageSendEvent::SendRevokeAndACK, node_b.node.get_our_node_id());
2816 // No commitment_signed so get_event_msg's assert(len == 1) passes
2817 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &as_revoke_and_ack);
2818 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
2819 check_added_monitors!(node_b, 1);
2822 assert!(chan_msgs.2.is_none());
2826 for chan_msgs in resp_2.drain(..) {
2827 if send_channel_ready.1 {
2828 node_b.node.handle_channel_ready(&node_a.node.get_our_node_id(), &chan_msgs.0.unwrap());
2829 let announcement_event = node_b.node.get_and_clear_pending_msg_events();
2830 if !announcement_event.is_empty() {
2831 assert_eq!(announcement_event.len(), 1);
2832 match announcement_event[0] {
2833 MessageSendEvent::SendChannelUpdate { .. } => {},
2834 MessageSendEvent::SendAnnouncementSignatures { .. } => {},
2835 _ => panic!("Unexpected event {:?}!", announcement_event[0]),
2839 assert!(chan_msgs.0.is_none());
2842 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
2843 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap());
2844 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
2845 check_added_monitors!(node_b, 1);
2847 assert!(chan_msgs.1.is_none());
2849 if pending_htlc_adds.1 != 0 || pending_htlc_claims.1 != 0 || pending_htlc_fails.1 != 0 || pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
2850 let commitment_update = chan_msgs.2.unwrap();
2851 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
2852 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.1 as usize);
2854 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.1 + pending_cell_htlc_claims.1);
2855 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_htlc_fails.1 + pending_cell_htlc_fails.1);
2856 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
2857 for update_add in commitment_update.update_add_htlcs {
2858 node_b.node.handle_update_add_htlc(&node_a.node.get_our_node_id(), &update_add);
2860 for update_fulfill in commitment_update.update_fulfill_htlcs {
2861 node_b.node.handle_update_fulfill_htlc(&node_a.node.get_our_node_id(), &update_fulfill);
2863 for update_fail in commitment_update.update_fail_htlcs {
2864 node_b.node.handle_update_fail_htlc(&node_a.node.get_our_node_id(), &update_fail);
2867 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
2868 commitment_signed_dance!(node_b, node_a, commitment_update.commitment_signed, false);
2870 node_b.node.handle_commitment_signed(&node_a.node.get_our_node_id(), &commitment_update.commitment_signed);
2871 check_added_monitors!(node_b, 1);
2872 let bs_revoke_and_ack = get_event_msg!(node_b, MessageSendEvent::SendRevokeAndACK, node_a.node.get_our_node_id());
2873 // No commitment_signed so get_event_msg's assert(len == 1) passes
2874 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &bs_revoke_and_ack);
2875 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
2876 check_added_monitors!(node_a, 1);
2879 assert!(chan_msgs.2.is_none());