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 chain::{BestBlock, Confirm, Listen, Watch, keysinterface::KeysInterface};
14 use chain::channelmonitor::ChannelMonitor;
15 use chain::transaction::OutPoint;
16 use ln::{PaymentPreimage, PaymentHash, PaymentSecret};
17 use ln::channelmanager::{ChainParameters, ChannelManager, ChannelManagerReadArgs, RAACommitmentOrder, PaymentSendFailure, PaymentId, MIN_CLTV_EXPIRY_DELTA};
18 use routing::network_graph::{NetGraphMsgHandler, NetworkGraph};
19 use routing::router::{PaymentParameters, Route, get_route};
20 use ln::features::{InitFeatures, InvoiceFeatures};
22 use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler};
23 use util::enforcing_trait_impls::EnforcingSigner;
25 use util::test_utils::{panicking, TestChainMonitor};
26 use util::events::{Event, MessageSendEvent, MessageSendEventsProvider, PaymentPurpose};
27 use util::errors::APIError;
28 use util::config::UserConfig;
29 use util::ser::{ReadableArgs, Writeable, Readable};
31 use bitcoin::blockdata::block::{Block, BlockHeader};
32 use bitcoin::blockdata::constants::genesis_block;
33 use bitcoin::blockdata::transaction::{Transaction, TxOut};
34 use bitcoin::network::constants::Network;
36 use bitcoin::hash_types::BlockHash;
38 use bitcoin::secp256k1::PublicKey;
42 use core::cell::RefCell;
44 use sync::{Arc, Mutex};
47 pub const CHAN_CONFIRM_DEPTH: u32 = 10;
49 /// Mine the given transaction in the next block and then mine CHAN_CONFIRM_DEPTH - 1 blocks on
50 /// top, giving the given transaction CHAN_CONFIRM_DEPTH confirmations.
51 pub fn confirm_transaction<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, tx: &Transaction) {
52 confirm_transaction_at(node, tx, node.best_block_info().1 + 1);
53 connect_blocks(node, CHAN_CONFIRM_DEPTH - 1);
55 /// Mine a signle block containing the given transaction
56 pub fn mine_transaction<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, tx: &Transaction) {
57 let height = node.best_block_info().1 + 1;
58 confirm_transaction_at(node, tx, height);
60 /// Mine the given transaction at the given height, mining blocks as required to build to that
62 pub fn confirm_transaction_at<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, tx: &Transaction, conf_height: u32) {
63 let first_connect_height = node.best_block_info().1 + 1;
64 assert!(first_connect_height <= conf_height);
65 if conf_height > first_connect_height {
66 connect_blocks(node, conf_height - first_connect_height);
68 let mut block = Block {
69 header: BlockHeader { version: 0x20000000, prev_blockhash: node.best_block_hash(), merkle_root: Default::default(), time: conf_height, bits: 42, nonce: 42 },
72 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
73 block.txdata.push(Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() });
75 block.txdata.push(tx.clone());
76 connect_block(node, &block);
79 /// The possible ways we may notify a ChannelManager of a new block
80 #[derive(Clone, Copy, Debug, PartialEq)]
81 pub enum ConnectStyle {
82 /// Calls `best_block_updated` first, detecting transactions in the block only after receiving
83 /// the header and height information.
85 /// The same as `BestBlockFirst`, however when we have multiple blocks to connect, we only
86 /// make a single `best_block_updated` call.
87 BestBlockFirstSkippingBlocks,
88 /// The same as `BestBlockFirst` when connecting blocks. During disconnection only
89 /// `transaction_unconfirmed` is called.
90 BestBlockFirstReorgsOnlyTip,
91 /// Calls `transactions_confirmed` first, detecting transactions in the block before updating
92 /// the header and height information.
94 /// The same as `TransactionsFirst`, however when we have multiple blocks to connect, we only
95 /// make a single `best_block_updated` call.
96 TransactionsFirstSkippingBlocks,
97 /// The same as `TransactionsFirst` when connecting blocks. During disconnection only
98 /// `transaction_unconfirmed` is called.
99 TransactionsFirstReorgsOnlyTip,
100 /// Provides the full block via the `chain::Listen` interface. In the current code this is
101 /// equivalent to `TransactionsFirst` with some additional assertions.
106 fn random_style() -> ConnectStyle {
107 #[cfg(feature = "std")] {
108 use core::hash::{BuildHasher, Hasher};
109 // Get a random value using the only std API to do so - the DefaultHasher
110 let rand_val = std::collections::hash_map::RandomState::new().build_hasher().finish();
111 let res = match rand_val % 7 {
112 0 => ConnectStyle::BestBlockFirst,
113 1 => ConnectStyle::BestBlockFirstSkippingBlocks,
114 2 => ConnectStyle::BestBlockFirstReorgsOnlyTip,
115 3 => ConnectStyle::TransactionsFirst,
116 4 => ConnectStyle::TransactionsFirstSkippingBlocks,
117 5 => ConnectStyle::TransactionsFirstReorgsOnlyTip,
118 6 => ConnectStyle::FullBlockViaListen,
121 eprintln!("Using Block Connection Style: {:?}", res);
124 #[cfg(not(feature = "std"))] {
125 ConnectStyle::FullBlockViaListen
130 pub fn connect_blocks<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, depth: u32) -> BlockHash {
131 let skip_intermediaries = match *node.connect_style.borrow() {
132 ConnectStyle::BestBlockFirstSkippingBlocks|ConnectStyle::TransactionsFirstSkippingBlocks|
133 ConnectStyle::BestBlockFirstReorgsOnlyTip|ConnectStyle::TransactionsFirstReorgsOnlyTip => true,
137 let height = node.best_block_info().1 + 1;
138 let mut block = Block {
139 header: BlockHeader { version: 0x2000000, prev_blockhash: node.best_block_hash(), merkle_root: Default::default(), time: height, bits: 42, nonce: 42 },
144 let prev_blockhash = block.header.block_hash();
145 do_connect_block(node, block, skip_intermediaries);
147 header: BlockHeader { version: 0x20000000, prev_blockhash, merkle_root: Default::default(), time: height + i, bits: 42, nonce: 42 },
151 let hash = block.header.block_hash();
152 do_connect_block(node, block, false);
156 pub fn connect_block<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, block: &Block) {
157 do_connect_block(node, block.clone(), false);
160 fn call_claimable_balances<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>) {
161 // Ensure `get_claimable_balances`' self-tests never panic
162 for funding_outpoint in node.chain_monitor.chain_monitor.list_monitors() {
163 node.chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances();
167 fn do_connect_block<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, block: Block, skip_intermediaries: bool) {
168 call_claimable_balances(node);
169 let height = node.best_block_info().1 + 1;
170 #[cfg(feature = "std")] {
171 eprintln!("Connecting block using Block Connection Style: {:?}", *node.connect_style.borrow());
173 if !skip_intermediaries {
174 let txdata: Vec<_> = block.txdata.iter().enumerate().collect();
175 match *node.connect_style.borrow() {
176 ConnectStyle::BestBlockFirst|ConnectStyle::BestBlockFirstSkippingBlocks|ConnectStyle::BestBlockFirstReorgsOnlyTip => {
177 node.chain_monitor.chain_monitor.best_block_updated(&block.header, height);
178 call_claimable_balances(node);
179 node.chain_monitor.chain_monitor.transactions_confirmed(&block.header, &txdata, height);
180 node.node.best_block_updated(&block.header, height);
181 node.node.transactions_confirmed(&block.header, &txdata, height);
183 ConnectStyle::TransactionsFirst|ConnectStyle::TransactionsFirstSkippingBlocks|ConnectStyle::TransactionsFirstReorgsOnlyTip => {
184 node.chain_monitor.chain_monitor.transactions_confirmed(&block.header, &txdata, height);
185 call_claimable_balances(node);
186 node.chain_monitor.chain_monitor.best_block_updated(&block.header, height);
187 node.node.transactions_confirmed(&block.header, &txdata, height);
188 node.node.best_block_updated(&block.header, height);
190 ConnectStyle::FullBlockViaListen => {
191 node.chain_monitor.chain_monitor.block_connected(&block, height);
192 node.node.block_connected(&block, height);
196 call_claimable_balances(node);
197 node.node.test_process_background_events();
198 node.blocks.lock().unwrap().push((block, height));
201 pub fn disconnect_blocks<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, count: u32) {
202 call_claimable_balances(node);
203 #[cfg(feature = "std")] {
204 eprintln!("Disconnecting {} blocks using Block Connection Style: {:?}", count, *node.connect_style.borrow());
207 let orig = node.blocks.lock().unwrap().pop().unwrap();
208 assert!(orig.1 > 0); // Cannot disconnect genesis
209 let prev = node.blocks.lock().unwrap().last().unwrap().clone();
211 match *node.connect_style.borrow() {
212 ConnectStyle::FullBlockViaListen => {
213 node.chain_monitor.chain_monitor.block_disconnected(&orig.0.header, orig.1);
214 Listen::block_disconnected(node.node, &orig.0.header, orig.1);
216 ConnectStyle::BestBlockFirstSkippingBlocks|ConnectStyle::TransactionsFirstSkippingBlocks => {
218 node.chain_monitor.chain_monitor.best_block_updated(&prev.0.header, prev.1);
219 node.node.best_block_updated(&prev.0.header, prev.1);
222 ConnectStyle::BestBlockFirstReorgsOnlyTip|ConnectStyle::TransactionsFirstReorgsOnlyTip => {
223 for tx in orig.0.txdata {
224 node.chain_monitor.chain_monitor.transaction_unconfirmed(&tx.txid());
225 node.node.transaction_unconfirmed(&tx.txid());
229 node.chain_monitor.chain_monitor.best_block_updated(&prev.0.header, prev.1);
230 node.node.best_block_updated(&prev.0.header, prev.1);
233 call_claimable_balances(node);
237 pub fn disconnect_all_blocks<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>) {
238 let count = node.blocks.lock().unwrap().len() as u32 - 1;
239 disconnect_blocks(node, count);
242 pub struct TestChanMonCfg {
243 pub tx_broadcaster: test_utils::TestBroadcaster,
244 pub fee_estimator: test_utils::TestFeeEstimator,
245 pub chain_source: test_utils::TestChainSource,
246 pub persister: test_utils::TestPersister,
247 pub logger: test_utils::TestLogger,
248 pub keys_manager: test_utils::TestKeysInterface,
249 pub network_graph: NetworkGraph,
252 pub struct NodeCfg<'a> {
253 pub chain_source: &'a test_utils::TestChainSource,
254 pub tx_broadcaster: &'a test_utils::TestBroadcaster,
255 pub fee_estimator: &'a test_utils::TestFeeEstimator,
256 pub chain_monitor: test_utils::TestChainMonitor<'a>,
257 pub keys_manager: &'a test_utils::TestKeysInterface,
258 pub logger: &'a test_utils::TestLogger,
259 pub network_graph: &'a NetworkGraph,
260 pub node_seed: [u8; 32],
261 pub features: InitFeatures,
264 pub struct Node<'a, 'b: 'a, 'c: 'b> {
265 pub chain_source: &'c test_utils::TestChainSource,
266 pub tx_broadcaster: &'c test_utils::TestBroadcaster,
267 pub chain_monitor: &'b test_utils::TestChainMonitor<'c>,
268 pub keys_manager: &'b test_utils::TestKeysInterface,
269 pub node: &'a ChannelManager<EnforcingSigner, &'b TestChainMonitor<'c>, &'c test_utils::TestBroadcaster, &'b test_utils::TestKeysInterface, &'c test_utils::TestFeeEstimator, &'c test_utils::TestLogger>,
270 pub network_graph: &'c NetworkGraph,
271 pub net_graph_msg_handler: NetGraphMsgHandler<&'c NetworkGraph, &'c test_utils::TestChainSource, &'c test_utils::TestLogger>,
272 pub node_seed: [u8; 32],
273 pub network_payment_count: Rc<RefCell<u8>>,
274 pub network_chan_count: Rc<RefCell<u32>>,
275 pub logger: &'c test_utils::TestLogger,
276 pub blocks: Arc<Mutex<Vec<(Block, u32)>>>,
277 pub connect_style: Rc<RefCell<ConnectStyle>>,
279 impl<'a, 'b, 'c> Node<'a, 'b, 'c> {
280 pub fn best_block_hash(&self) -> BlockHash {
281 self.blocks.lock().unwrap().last().unwrap().0.block_hash()
283 pub fn best_block_info(&self) -> (BlockHash, u32) {
284 self.blocks.lock().unwrap().last().map(|(a, b)| (a.block_hash(), *b)).unwrap()
286 pub fn get_block_header(&self, height: u32) -> BlockHeader {
287 self.blocks.lock().unwrap()[height as usize].0.header
291 impl<'a, 'b, 'c> Drop for Node<'a, 'b, 'c> {
294 // Check that we processed all pending events
295 assert!(self.node.get_and_clear_pending_msg_events().is_empty());
296 assert!(self.node.get_and_clear_pending_events().is_empty());
297 assert!(self.chain_monitor.added_monitors.lock().unwrap().is_empty());
299 // Check that if we serialize the Router, we can deserialize it again.
301 let mut w = test_utils::TestVecWriter(Vec::new());
302 self.network_graph.write(&mut w).unwrap();
303 let network_graph_deser = <NetworkGraph>::read(&mut io::Cursor::new(&w.0)).unwrap();
304 assert!(network_graph_deser == *self.network_graph);
305 let net_graph_msg_handler = NetGraphMsgHandler::new(
306 &network_graph_deser, Some(self.chain_source), self.logger
308 let mut chan_progress = 0;
310 let orig_announcements = self.net_graph_msg_handler.get_next_channel_announcements(chan_progress, 255);
311 let deserialized_announcements = net_graph_msg_handler.get_next_channel_announcements(chan_progress, 255);
312 assert!(orig_announcements == deserialized_announcements);
313 chan_progress = match orig_announcements.last() {
314 Some(announcement) => announcement.0.contents.short_channel_id + 1,
318 let mut node_progress = None;
320 let orig_announcements = self.net_graph_msg_handler.get_next_node_announcements(node_progress.as_ref(), 255);
321 let deserialized_announcements = net_graph_msg_handler.get_next_node_announcements(node_progress.as_ref(), 255);
322 assert!(orig_announcements == deserialized_announcements);
323 node_progress = match orig_announcements.last() {
324 Some(announcement) => Some(announcement.contents.node_id),
330 // Check that if we serialize and then deserialize all our channel monitors we get the
331 // same set of outputs to watch for on chain as we have now. Note that if we write
332 // tests that fully close channels and remove the monitors at some point this may break.
333 let feeest = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
334 let mut deserialized_monitors = Vec::new();
336 for outpoint in self.chain_monitor.chain_monitor.list_monitors() {
337 let mut w = test_utils::TestVecWriter(Vec::new());
338 self.chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut w).unwrap();
339 let (_, deserialized_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
340 &mut io::Cursor::new(&w.0), self.keys_manager).unwrap();
341 deserialized_monitors.push(deserialized_monitor);
345 // Before using all the new monitors to check the watch outpoints, use the full set of
346 // them to ensure we can write and reload our ChannelManager.
348 let mut channel_monitors = HashMap::new();
349 for monitor in deserialized_monitors.iter_mut() {
350 channel_monitors.insert(monitor.get_funding_txo().0, monitor);
353 let mut w = test_utils::TestVecWriter(Vec::new());
354 self.node.write(&mut w).unwrap();
355 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut io::Cursor::new(w.0), ChannelManagerReadArgs {
356 default_config: *self.node.get_current_default_configuration(),
357 keys_manager: self.keys_manager,
358 fee_estimator: &test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
359 chain_monitor: self.chain_monitor,
360 tx_broadcaster: &test_utils::TestBroadcaster {
361 txn_broadcasted: Mutex::new(self.tx_broadcaster.txn_broadcasted.lock().unwrap().clone()),
362 blocks: Arc::new(Mutex::new(self.tx_broadcaster.blocks.lock().unwrap().clone())),
364 logger: &self.logger,
369 let persister = test_utils::TestPersister::new();
370 let broadcaster = test_utils::TestBroadcaster {
371 txn_broadcasted: Mutex::new(self.tx_broadcaster.txn_broadcasted.lock().unwrap().clone()),
372 blocks: Arc::new(Mutex::new(self.tx_broadcaster.blocks.lock().unwrap().clone())),
374 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
375 let chain_monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &broadcaster, &self.logger, &feeest, &persister, &self.keys_manager);
376 for deserialized_monitor in deserialized_monitors.drain(..) {
377 if let Err(_) = chain_monitor.watch_channel(deserialized_monitor.get_funding_txo().0, deserialized_monitor) {
381 assert_eq!(*chain_source.watched_txn.lock().unwrap(), *self.chain_source.watched_txn.lock().unwrap());
382 assert_eq!(*chain_source.watched_outputs.lock().unwrap(), *self.chain_source.watched_outputs.lock().unwrap());
387 pub fn create_chan_between_nodes<'a, 'b, 'c, 'd>(node_a: &'a Node<'b, 'c, 'd>, node_b: &'a Node<'b, 'c, 'd>, a_flags: InitFeatures, b_flags: InitFeatures) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
388 create_chan_between_nodes_with_value(node_a, node_b, 100000, 10001, a_flags, b_flags)
391 pub fn create_chan_between_nodes_with_value<'a, 'b, 'c, 'd>(node_a: &'a Node<'b, 'c, 'd>, node_b: &'a Node<'b, 'c, 'd>, channel_value: u64, push_msat: u64, a_flags: InitFeatures, b_flags: InitFeatures) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
392 let (funding_locked, channel_id, tx) = create_chan_between_nodes_with_value_a(node_a, node_b, channel_value, push_msat, a_flags, b_flags);
393 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(node_a, node_b, &funding_locked);
394 (announcement, as_update, bs_update, channel_id, tx)
398 /// Gets an RAA and CS which were sent in response to a commitment update
399 macro_rules! get_revoke_commit_msgs {
400 ($node: expr, $node_id: expr) => {
402 use $crate::util::events::MessageSendEvent;
403 let events = $node.node.get_and_clear_pending_msg_events();
404 assert_eq!(events.len(), 2);
406 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
407 assert_eq!(*node_id, $node_id);
410 _ => panic!("Unexpected event"),
412 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
413 assert_eq!(*node_id, $node_id);
414 assert!(updates.update_add_htlcs.is_empty());
415 assert!(updates.update_fulfill_htlcs.is_empty());
416 assert!(updates.update_fail_htlcs.is_empty());
417 assert!(updates.update_fail_malformed_htlcs.is_empty());
418 assert!(updates.update_fee.is_none());
419 updates.commitment_signed.clone()
421 _ => panic!("Unexpected event"),
427 /// Get an specific event message from the pending events queue.
429 macro_rules! get_event_msg {
430 ($node: expr, $event_type: path, $node_id: expr) => {
432 let events = $node.node.get_and_clear_pending_msg_events();
433 assert_eq!(events.len(), 1);
435 $event_type { ref node_id, ref msg } => {
436 assert_eq!(*node_id, $node_id);
439 _ => panic!("Unexpected event"),
445 /// Get an error message from the pending events queue.
447 macro_rules! get_err_msg {
448 ($node: expr, $node_id: expr) => {
450 let events = $node.node.get_and_clear_pending_msg_events();
451 assert_eq!(events.len(), 1);
453 $crate::util::events::MessageSendEvent::HandleError {
454 action: $crate::ln::msgs::ErrorAction::SendErrorMessage { ref msg }, ref node_id
456 assert_eq!(*node_id, $node_id);
459 _ => panic!("Unexpected event"),
465 /// Get a specific event from the pending events queue.
467 macro_rules! get_event {
468 ($node: expr, $event_type: path) => {
470 let mut events = $node.node.get_and_clear_pending_events();
471 assert_eq!(events.len(), 1);
472 let ev = events.pop().unwrap();
474 $event_type { .. } => {
477 _ => panic!("Unexpected event"),
484 /// Gets an UpdateHTLCs MessageSendEvent
485 macro_rules! get_htlc_update_msgs {
486 ($node: expr, $node_id: expr) => {
488 let events = $node.node.get_and_clear_pending_msg_events();
489 assert_eq!(events.len(), 1);
491 $crate::util::events::MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
492 assert_eq!(*node_id, $node_id);
495 _ => panic!("Unexpected event"),
502 macro_rules! get_channel_ref {
503 ($node: expr, $lock: ident, $channel_id: expr) => {
505 $lock = $node.node.channel_state.lock().unwrap();
506 $lock.by_id.get_mut(&$channel_id).unwrap()
512 macro_rules! get_feerate {
513 ($node: expr, $channel_id: expr) => {
516 let chan = get_channel_ref!($node, lock, $channel_id);
523 macro_rules! get_opt_anchors {
524 ($node: expr, $channel_id: expr) => {
527 let chan = get_channel_ref!($node, lock, $channel_id);
533 /// Returns a channel monitor given a channel id, making some naive assumptions
535 macro_rules! get_monitor {
536 ($node: expr, $channel_id: expr) => {
538 use bitcoin::hashes::Hash;
539 let mut monitor = None;
540 // Assume funding vout is either 0 or 1 blindly
542 if let Ok(mon) = $node.chain_monitor.chain_monitor.get_monitor(
543 $crate::chain::transaction::OutPoint {
544 txid: bitcoin::Txid::from_slice(&$channel_id[..]).unwrap(), index
556 /// Returns any local commitment transactions for the channel.
558 macro_rules! get_local_commitment_txn {
559 ($node: expr, $channel_id: expr) => {
561 $crate::get_monitor!($node, $channel_id).unsafe_get_latest_holder_commitment_txn(&$node.logger)
566 /// Check the error from attempting a payment.
568 macro_rules! unwrap_send_err {
569 ($res: expr, $all_failed: expr, $type: pat, $check: expr) => {
571 &Err(PaymentSendFailure::AllFailedRetrySafe(ref fails)) if $all_failed => {
572 assert_eq!(fails.len(), 1);
578 &Err(PaymentSendFailure::PartialFailure { ref results, .. }) if !$all_failed => {
579 assert_eq!(results.len(), 1);
581 Err($type) => { $check },
590 /// Check whether N channel monitor(s) have been added.
592 macro_rules! check_added_monitors {
593 ($node: expr, $count: expr) => {
595 let mut added_monitors = $node.chain_monitor.added_monitors.lock().unwrap();
596 assert_eq!(added_monitors.len(), $count);
597 added_monitors.clear();
602 pub fn create_funding_transaction<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, expected_chan_value: u64, expected_user_chan_id: u64) -> ([u8; 32], Transaction, OutPoint) {
603 let chan_id = *node.network_chan_count.borrow();
605 let events = node.node.get_and_clear_pending_events();
606 assert_eq!(events.len(), 1);
608 Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
609 assert_eq!(*channel_value_satoshis, expected_chan_value);
610 assert_eq!(user_channel_id, expected_user_chan_id);
612 let tx = Transaction { version: chan_id as i32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
613 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
615 let funding_outpoint = OutPoint { txid: tx.txid(), index: 0 };
616 (*temporary_channel_id, tx, funding_outpoint)
618 _ => panic!("Unexpected event"),
621 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 {
622 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(node_a, channel_value, 42);
623 assert_eq!(temporary_channel_id, expected_temporary_channel_id);
625 assert!(node_a.node.funding_transaction_generated(&temporary_channel_id, tx.clone()).is_ok());
626 check_added_monitors!(node_a, 0);
628 let funding_created_msg = get_event_msg!(node_a, MessageSendEvent::SendFundingCreated, node_b.node.get_our_node_id());
629 assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
630 node_b.node.handle_funding_created(&node_a.node.get_our_node_id(), &funding_created_msg);
632 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
633 assert_eq!(added_monitors.len(), 1);
634 assert_eq!(added_monitors[0].0, funding_output);
635 added_monitors.clear();
638 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()));
640 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
641 assert_eq!(added_monitors.len(), 1);
642 assert_eq!(added_monitors[0].0, funding_output);
643 added_monitors.clear();
646 let events_4 = node_a.node.get_and_clear_pending_events();
647 assert_eq!(events_4.len(), 0);
649 assert_eq!(node_a.tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
650 assert_eq!(node_a.tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
651 node_a.tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
653 // Ensure that funding_transaction_generated is idempotent.
654 assert!(node_a.node.funding_transaction_generated(&temporary_channel_id, tx.clone()).is_err());
655 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
656 check_added_monitors!(node_a, 0);
661 pub fn create_chan_between_nodes_with_value_init<'a, 'b, 'c>(node_a: &Node<'a, 'b, 'c>, node_b: &Node<'a, 'b, 'c>, channel_value: u64, push_msat: u64, a_flags: InitFeatures, b_flags: InitFeatures) -> Transaction {
662 let create_chan_id = node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
663 let open_channel_msg = get_event_msg!(node_a, MessageSendEvent::SendOpenChannel, node_b.node.get_our_node_id());
664 assert_eq!(open_channel_msg.temporary_channel_id, create_chan_id);
665 node_b.node.handle_open_channel(&node_a.node.get_our_node_id(), a_flags, &open_channel_msg);
666 let accept_channel_msg = get_event_msg!(node_b, MessageSendEvent::SendAcceptChannel, node_a.node.get_our_node_id());
667 assert_eq!(accept_channel_msg.temporary_channel_id, create_chan_id);
668 node_a.node.handle_accept_channel(&node_b.node.get_our_node_id(), b_flags, &accept_channel_msg);
670 sign_funding_transaction(node_a, node_b, channel_value, create_chan_id)
673 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) {
674 confirm_transaction_at(node_conf, tx, conf_height);
675 connect_blocks(node_conf, CHAN_CONFIRM_DEPTH - 1);
676 node_recv.node.handle_funding_locked(&node_conf.node.get_our_node_id(), &get_event_msg!(node_conf, MessageSendEvent::SendFundingLocked, node_recv.node.get_our_node_id()));
679 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::FundingLocked, msgs::AnnouncementSignatures), [u8; 32]) {
681 let events_6 = node_conf.node.get_and_clear_pending_msg_events();
682 assert_eq!(events_6.len(), 3);
683 let announcement_sigs_idx = if let MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } = events_6[1] {
684 assert_eq!(*node_id, node_recv.node.get_our_node_id());
686 } else if let MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } = events_6[2] {
687 assert_eq!(*node_id, node_recv.node.get_our_node_id());
689 } else { panic!("Unexpected event: {:?}", events_6[1]); };
690 ((match events_6[0] {
691 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
692 channel_id = msg.channel_id.clone();
693 assert_eq!(*node_id, node_recv.node.get_our_node_id());
696 _ => panic!("Unexpected event"),
697 }, match events_6[announcement_sigs_idx] {
698 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
699 assert_eq!(*node_id, node_recv.node.get_our_node_id());
702 _ => panic!("Unexpected event"),
706 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::FundingLocked, msgs::AnnouncementSignatures), [u8; 32]) {
707 let conf_height = core::cmp::max(node_a.best_block_info().1 + 1, node_b.best_block_info().1 + 1);
708 create_chan_between_nodes_with_value_confirm_first(node_a, node_b, tx, conf_height);
709 confirm_transaction_at(node_a, tx, conf_height);
710 connect_blocks(node_a, CHAN_CONFIRM_DEPTH - 1);
711 create_chan_between_nodes_with_value_confirm_second(node_b, node_a)
714 pub fn create_chan_between_nodes_with_value_a<'a, 'b, 'c, 'd>(node_a: &'a Node<'b, 'c, 'd>, node_b: &'a Node<'b, 'c, 'd>, channel_value: u64, push_msat: u64, a_flags: InitFeatures, b_flags: InitFeatures) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32], Transaction) {
715 let tx = create_chan_between_nodes_with_value_init(node_a, node_b, channel_value, push_msat, a_flags, b_flags);
716 let (msgs, chan_id) = create_chan_between_nodes_with_value_confirm(node_a, node_b, &tx);
720 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::FundingLocked, msgs::AnnouncementSignatures)) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate) {
721 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &as_funding_msgs.0);
722 let bs_announcement_sigs = get_event_msg!(node_b, MessageSendEvent::SendAnnouncementSignatures, node_a.node.get_our_node_id());
723 node_b.node.handle_announcement_signatures(&node_a.node.get_our_node_id(), &as_funding_msgs.1);
725 let events_7 = node_b.node.get_and_clear_pending_msg_events();
726 assert_eq!(events_7.len(), 1);
727 let (announcement, bs_update) = match events_7[0] {
728 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
731 _ => panic!("Unexpected event"),
734 node_a.node.handle_announcement_signatures(&node_b.node.get_our_node_id(), &bs_announcement_sigs);
735 let events_8 = node_a.node.get_and_clear_pending_msg_events();
736 assert_eq!(events_8.len(), 1);
737 let as_update = match events_8[0] {
738 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
739 assert!(*announcement == *msg);
740 assert_eq!(update_msg.contents.short_channel_id, announcement.contents.short_channel_id);
741 assert_eq!(update_msg.contents.short_channel_id, bs_update.contents.short_channel_id);
744 _ => panic!("Unexpected event"),
747 *node_a.network_chan_count.borrow_mut() += 1;
749 ((*announcement).clone(), (*as_update).clone(), (*bs_update).clone())
752 pub fn create_announced_chan_between_nodes<'a, 'b, 'c, 'd>(nodes: &'a Vec<Node<'b, 'c, 'd>>, a: usize, b: usize, a_flags: InitFeatures, b_flags: InitFeatures) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
753 create_announced_chan_between_nodes_with_value(nodes, a, b, 100000, 10001, a_flags, b_flags)
756 pub fn create_announced_chan_between_nodes_with_value<'a, 'b, 'c, 'd>(nodes: &'a Vec<Node<'b, 'c, 'd>>, a: usize, b: usize, channel_value: u64, push_msat: u64, a_flags: InitFeatures, b_flags: InitFeatures) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
757 let chan_announcement = create_chan_between_nodes_with_value(&nodes[a], &nodes[b], channel_value, push_msat, a_flags, b_flags);
758 update_nodes_with_chan_announce(nodes, a, b, &chan_announcement.0, &chan_announcement.1, &chan_announcement.2);
759 (chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
762 pub fn create_unannounced_chan_between_nodes_with_value<'a, 'b, 'c, 'd>(nodes: &'a Vec<Node<'b, 'c, 'd>>, a: usize, b: usize, channel_value: u64, push_msat: u64, a_flags: InitFeatures, b_flags: InitFeatures) -> (msgs::FundingLocked, Transaction) {
763 let mut no_announce_cfg = test_default_channel_config();
764 no_announce_cfg.channel_options.announced_channel = false;
765 nodes[a].node.create_channel(nodes[b].node.get_our_node_id(), channel_value, push_msat, 42, Some(no_announce_cfg)).unwrap();
766 let open_channel = get_event_msg!(nodes[a], MessageSendEvent::SendOpenChannel, nodes[b].node.get_our_node_id());
767 nodes[b].node.handle_open_channel(&nodes[a].node.get_our_node_id(), a_flags, &open_channel);
768 let accept_channel = get_event_msg!(nodes[b], MessageSendEvent::SendAcceptChannel, nodes[a].node.get_our_node_id());
769 nodes[a].node.handle_accept_channel(&nodes[b].node.get_our_node_id(), b_flags, &accept_channel);
771 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[a], channel_value, 42);
772 nodes[a].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
773 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()));
774 check_added_monitors!(nodes[b], 1);
776 let cs_funding_signed = get_event_msg!(nodes[b], MessageSendEvent::SendFundingSigned, nodes[a].node.get_our_node_id());
777 nodes[a].node.handle_funding_signed(&nodes[b].node.get_our_node_id(), &cs_funding_signed);
778 check_added_monitors!(nodes[a], 1);
780 let conf_height = core::cmp::max(nodes[a].best_block_info().1 + 1, nodes[b].best_block_info().1 + 1);
781 confirm_transaction_at(&nodes[a], &tx, conf_height);
782 connect_blocks(&nodes[a], CHAN_CONFIRM_DEPTH - 1);
783 confirm_transaction_at(&nodes[b], &tx, conf_height);
784 connect_blocks(&nodes[b], CHAN_CONFIRM_DEPTH - 1);
785 let as_funding_locked = get_event_msg!(nodes[a], MessageSendEvent::SendFundingLocked, nodes[b].node.get_our_node_id());
786 nodes[a].node.handle_funding_locked(&nodes[b].node.get_our_node_id(), &get_event_msg!(nodes[b], MessageSendEvent::SendFundingLocked, nodes[a].node.get_our_node_id()));
787 let as_update = get_event_msg!(nodes[a], MessageSendEvent::SendChannelUpdate, nodes[b].node.get_our_node_id());
788 nodes[b].node.handle_funding_locked(&nodes[a].node.get_our_node_id(), &as_funding_locked);
789 let bs_update = get_event_msg!(nodes[b], MessageSendEvent::SendChannelUpdate, nodes[a].node.get_our_node_id());
791 nodes[a].node.handle_channel_update(&nodes[b].node.get_our_node_id(), &bs_update);
792 nodes[b].node.handle_channel_update(&nodes[a].node.get_our_node_id(), &as_update);
794 let mut found_a = false;
795 for chan in nodes[a].node.list_usable_channels() {
796 if chan.channel_id == as_funding_locked.channel_id {
799 assert!(!chan.is_public);
804 let mut found_b = false;
805 for chan in nodes[b].node.list_usable_channels() {
806 if chan.channel_id == as_funding_locked.channel_id {
809 assert!(!chan.is_public);
814 (as_funding_locked, tx)
817 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) {
818 nodes[a].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
819 let a_events = nodes[a].node.get_and_clear_pending_msg_events();
820 assert!(a_events.len() >= 2);
822 // ann should be re-generated by broadcast_node_announcement - check that we have it.
823 let mut found_ann_1 = false;
824 for event in a_events.iter() {
826 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
827 if msg == ann { found_ann_1 = true; }
829 MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
830 _ => panic!("Unexpected event {:?}", event),
833 assert!(found_ann_1);
835 let a_node_announcement = match a_events.last().unwrap() {
836 MessageSendEvent::BroadcastNodeAnnouncement { ref msg } => {
839 _ => panic!("Unexpected event"),
842 nodes[b].node.broadcast_node_announcement([1, 1, 1], [1; 32], Vec::new());
843 let b_events = nodes[b].node.get_and_clear_pending_msg_events();
844 assert!(b_events.len() >= 2);
846 // ann should be re-generated by broadcast_node_announcement - check that we have it.
847 let mut found_ann_2 = false;
848 for event in b_events.iter() {
850 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
851 if msg == ann { found_ann_2 = true; }
853 MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
854 _ => panic!("Unexpected event"),
857 assert!(found_ann_2);
859 let b_node_announcement = match b_events.last().unwrap() {
860 MessageSendEvent::BroadcastNodeAnnouncement { ref msg } => {
863 _ => panic!("Unexpected event"),
867 assert!(node.net_graph_msg_handler.handle_channel_announcement(ann).unwrap());
868 node.net_graph_msg_handler.handle_channel_update(upd_1).unwrap();
869 node.net_graph_msg_handler.handle_channel_update(upd_2).unwrap();
870 node.net_graph_msg_handler.handle_node_announcement(&a_node_announcement).unwrap();
871 node.net_graph_msg_handler.handle_node_announcement(&b_node_announcement).unwrap();
873 // Note that channel_updates are also delivered to ChannelManagers to ensure we have
874 // forwarding info for local channels even if its not accepted in the network graph.
875 node.node.handle_channel_update(&nodes[a].node.get_our_node_id(), &upd_1);
876 node.node.handle_channel_update(&nodes[b].node.get_our_node_id(), &upd_2);
881 macro_rules! check_spends {
882 ($tx: expr, $($spends_txn: expr),*) => {
885 for outp in $spends_txn.output.iter() {
886 assert!(outp.value >= outp.script_pubkey.dust_value().as_sat(), "Input tx output didn't meet dust limit");
889 for outp in $tx.output.iter() {
890 assert!(outp.value >= outp.script_pubkey.dust_value().as_sat(), "Spending tx output didn't meet dust limit");
892 let get_output = |out_point: &bitcoin::blockdata::transaction::OutPoint| {
894 if out_point.txid == $spends_txn.txid() {
895 return $spends_txn.output.get(out_point.vout as usize).cloned()
900 let mut total_value_in = 0;
901 for input in $tx.input.iter() {
902 total_value_in += get_output(&input.previous_output).unwrap().value;
904 let mut total_value_out = 0;
905 for output in $tx.output.iter() {
906 total_value_out += output.value;
908 let min_fee = ($tx.weight() as u64 + 3) / 4; // One sat per vbyte (ie per weight/4, rounded up)
909 // Input amount - output amount = fee, so check that out + min_fee is smaller than input
910 assert!(total_value_out + min_fee <= total_value_in);
911 $tx.verify(get_output).unwrap();
916 macro_rules! get_closing_signed_broadcast {
917 ($node: expr, $dest_pubkey: expr) => {
919 let events = $node.get_and_clear_pending_msg_events();
920 assert!(events.len() == 1 || events.len() == 2);
921 (match events[events.len() - 1] {
922 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
923 assert_eq!(msg.contents.flags & 2, 2);
926 _ => panic!("Unexpected event"),
927 }, if events.len() == 2 {
929 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
930 assert_eq!(*node_id, $dest_pubkey);
933 _ => panic!("Unexpected event"),
941 macro_rules! check_warn_msg {
942 ($node: expr, $recipient_node_id: expr, $chan_id: expr) => {{
943 let msg_events = $node.node.get_and_clear_pending_msg_events();
944 assert_eq!(msg_events.len(), 1);
945 match msg_events[0] {
946 MessageSendEvent::HandleError { action: ErrorAction::SendWarningMessage { ref msg, log_level: _ }, node_id } => {
947 assert_eq!(node_id, $recipient_node_id);
948 assert_eq!(msg.channel_id, $chan_id);
951 _ => panic!("Unexpected event"),
956 /// Check that a channel's closing channel update has been broadcasted, and optionally
957 /// check whether an error message event has occurred.
959 macro_rules! check_closed_broadcast {
960 ($node: expr, $with_error_msg: expr) => {{
961 use $crate::util::events::MessageSendEvent;
962 use $crate::ln::msgs::ErrorAction;
964 let msg_events = $node.node.get_and_clear_pending_msg_events();
965 assert_eq!(msg_events.len(), if $with_error_msg { 2 } else { 1 });
966 match msg_events[0] {
967 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
968 assert_eq!(msg.contents.flags & 2, 2);
970 _ => panic!("Unexpected event"),
973 match msg_events[1] {
974 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
975 // TODO: Check node_id
978 _ => panic!("Unexpected event"),
984 /// Check that a channel's closing channel events has been issued
986 macro_rules! check_closed_event {
987 ($node: expr, $events: expr, $reason: expr) => {
988 check_closed_event!($node, $events, $reason, false);
990 ($node: expr, $events: expr, $reason: expr, $is_check_discard_funding: expr) => {{
991 use $crate::util::events::Event;
993 let events = $node.node.get_and_clear_pending_events();
994 assert_eq!(events.len(), $events);
995 let expected_reason = $reason;
996 let mut issues_discard_funding = false;
997 for event in events {
999 Event::ChannelClosed { ref reason, .. } => {
1000 assert_eq!(*reason, expected_reason);
1002 Event::DiscardFunding { .. } => {
1003 issues_discard_funding = true;
1005 _ => panic!("Unexpected event"),
1008 assert_eq!($is_check_discard_funding, issues_discard_funding);
1012 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) {
1013 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) };
1014 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) };
1017 node_a.close_channel(channel_id).unwrap();
1018 node_b.handle_shutdown(&node_a.get_our_node_id(), &InitFeatures::known(), &get_event_msg!(struct_a, MessageSendEvent::SendShutdown, node_b.get_our_node_id()));
1020 let events_1 = node_b.get_and_clear_pending_msg_events();
1021 assert!(events_1.len() >= 1);
1022 let shutdown_b = match events_1[0] {
1023 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
1024 assert_eq!(node_id, &node_a.get_our_node_id());
1027 _ => panic!("Unexpected event"),
1030 let closing_signed_b = if !close_inbound_first {
1031 assert_eq!(events_1.len(), 1);
1034 Some(match events_1[1] {
1035 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
1036 assert_eq!(node_id, &node_a.get_our_node_id());
1039 _ => panic!("Unexpected event"),
1043 node_a.handle_shutdown(&node_b.get_our_node_id(), &InitFeatures::known(), &shutdown_b);
1044 let (as_update, bs_update) = if close_inbound_first {
1045 assert!(node_a.get_and_clear_pending_msg_events().is_empty());
1046 node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap());
1048 node_b.handle_closing_signed(&node_a.get_our_node_id(), &get_event_msg!(struct_a, MessageSendEvent::SendClosingSigned, node_b.get_our_node_id()));
1049 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
1050 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
1051 let (bs_update, closing_signed_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
1053 node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap());
1054 let (as_update, none_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
1055 assert!(none_a.is_none());
1056 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
1057 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
1058 (as_update, bs_update)
1060 let closing_signed_a = get_event_msg!(struct_a, MessageSendEvent::SendClosingSigned, node_b.get_our_node_id());
1062 node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a);
1063 node_a.handle_closing_signed(&node_b.get_our_node_id(), &get_event_msg!(struct_b, MessageSendEvent::SendClosingSigned, node_a.get_our_node_id()));
1065 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
1066 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
1067 let (as_update, closing_signed_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
1069 node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap());
1070 let (bs_update, none_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
1071 assert!(none_b.is_none());
1072 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
1073 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
1074 (as_update, bs_update)
1076 assert_eq!(tx_a, tx_b);
1077 check_spends!(tx_a, funding_tx);
1079 (as_update, bs_update, tx_a)
1082 pub struct SendEvent {
1083 pub node_id: PublicKey,
1084 pub msgs: Vec<msgs::UpdateAddHTLC>,
1085 pub commitment_msg: msgs::CommitmentSigned,
1088 pub fn from_commitment_update(node_id: PublicKey, updates: msgs::CommitmentUpdate) -> SendEvent {
1089 assert!(updates.update_fulfill_htlcs.is_empty());
1090 assert!(updates.update_fail_htlcs.is_empty());
1091 assert!(updates.update_fail_malformed_htlcs.is_empty());
1092 assert!(updates.update_fee.is_none());
1093 SendEvent { node_id: node_id, msgs: updates.update_add_htlcs, commitment_msg: updates.commitment_signed }
1096 pub fn from_event(event: MessageSendEvent) -> SendEvent {
1098 MessageSendEvent::UpdateHTLCs { node_id, updates } => SendEvent::from_commitment_update(node_id, updates),
1099 _ => panic!("Unexpected event type!"),
1103 pub fn from_node<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>) -> SendEvent {
1104 let mut events = node.node.get_and_clear_pending_msg_events();
1105 assert_eq!(events.len(), 1);
1106 SendEvent::from_event(events.pop().unwrap())
1111 /// Performs the "commitment signed dance" - the series of message exchanges which occur after a
1112 /// commitment update.
1113 macro_rules! commitment_signed_dance {
1114 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */) => {
1116 check_added_monitors!($node_a, 0);
1117 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
1118 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed);
1119 check_added_monitors!($node_a, 1);
1120 commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, false);
1123 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */, true /* return last RAA */) => {
1125 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!($node_a, $node_b.node.get_our_node_id());
1126 check_added_monitors!($node_b, 0);
1127 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
1128 $node_b.node.handle_revoke_and_ack(&$node_a.node.get_our_node_id(), &as_revoke_and_ack);
1129 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
1130 check_added_monitors!($node_b, 1);
1131 $node_b.node.handle_commitment_signed(&$node_a.node.get_our_node_id(), &as_commitment_signed);
1132 let (bs_revoke_and_ack, extra_msg_option) = {
1133 let events = $node_b.node.get_and_clear_pending_msg_events();
1134 assert!(events.len() <= 2);
1136 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
1137 assert_eq!(*node_id, $node_a.node.get_our_node_id());
1140 _ => panic!("Unexpected event"),
1141 }, events.get(1).map(|e| e.clone()))
1143 check_added_monitors!($node_b, 1);
1144 if $fail_backwards {
1145 assert!($node_a.node.get_and_clear_pending_events().is_empty());
1146 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
1148 (extra_msg_option, bs_revoke_and_ack)
1151 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */, false /* return extra message */, true /* return last RAA */) => {
1153 check_added_monitors!($node_a, 0);
1154 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
1155 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed);
1156 check_added_monitors!($node_a, 1);
1157 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
1158 assert!(extra_msg_option.is_none());
1162 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */) => {
1164 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
1165 $node_a.node.handle_revoke_and_ack(&$node_b.node.get_our_node_id(), &bs_revoke_and_ack);
1166 check_added_monitors!($node_a, 1);
1170 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, false /* no extra message */) => {
1172 assert!(commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true).is_none());
1175 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr) => {
1177 commitment_signed_dance!($node_a, $node_b, $commitment_signed, $fail_backwards, true);
1178 if $fail_backwards {
1179 $crate::expect_pending_htlcs_forwardable!($node_a);
1180 check_added_monitors!($node_a, 1);
1182 let channel_state = $node_a.node.channel_state.lock().unwrap();
1183 assert_eq!(channel_state.pending_msg_events.len(), 1);
1184 if let MessageSendEvent::UpdateHTLCs { ref node_id, .. } = channel_state.pending_msg_events[0] {
1185 assert_ne!(*node_id, $node_b.node.get_our_node_id());
1186 } else { panic!("Unexpected event"); }
1188 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
1194 /// Get a payment preimage and hash.
1196 macro_rules! get_payment_preimage_hash {
1197 ($dest_node: expr) => {
1199 get_payment_preimage_hash!($dest_node, None)
1202 ($dest_node: expr, $min_value_msat: expr) => {
1204 use bitcoin::hashes::Hash as _;
1205 let mut payment_count = $dest_node.network_payment_count.borrow_mut();
1206 let payment_preimage = $crate::ln::PaymentPreimage([*payment_count; 32]);
1207 *payment_count += 1;
1208 let payment_hash = $crate::ln::PaymentHash(
1209 bitcoin::hashes::sha256::Hash::hash(&payment_preimage.0[..]).into_inner());
1210 let payment_secret = $dest_node.node.create_inbound_payment_for_hash(payment_hash, $min_value_msat, 7200).unwrap();
1211 (payment_preimage, payment_hash, payment_secret)
1217 macro_rules! get_route {
1218 ($send_node: expr, $payment_params: expr, $recv_value: expr, $cltv: expr) => {{
1219 use $crate::chain::keysinterface::KeysInterface;
1220 let scorer = $crate::util::test_utils::TestScorer::with_penalty(0);
1221 let keys_manager = $crate::util::test_utils::TestKeysInterface::new(&[0u8; 32], bitcoin::network::constants::Network::Testnet);
1222 let random_seed_bytes = keys_manager.get_secure_random_bytes();
1223 $crate::routing::router::get_route(
1224 &$send_node.node.get_our_node_id(), &$payment_params, &$send_node.network_graph.read_only(),
1225 Some(&$send_node.node.list_usable_channels().iter().collect::<Vec<_>>()),
1226 $recv_value, $cltv, $send_node.logger, &scorer, &random_seed_bytes
1233 macro_rules! get_route_and_payment_hash {
1234 ($send_node: expr, $recv_node: expr, $recv_value: expr) => {{
1235 let payment_params = $crate::routing::router::PaymentParameters::from_node_id($recv_node.node.get_our_node_id())
1236 .with_features($crate::ln::features::InvoiceFeatures::known());
1237 $crate::get_route_and_payment_hash!($send_node, $recv_node, payment_params, $recv_value, TEST_FINAL_CLTV)
1239 ($send_node: expr, $recv_node: expr, $payment_params: expr, $recv_value: expr, $cltv: expr) => {{
1240 let (payment_preimage, payment_hash, payment_secret) = $crate::get_payment_preimage_hash!($recv_node, Some($recv_value));
1241 let route = $crate::get_route!($send_node, $payment_params, $recv_value, $cltv);
1242 (route.unwrap(), payment_hash, payment_preimage, payment_secret)
1247 /// Clears (and ignores) a PendingHTLCsForwardable event
1248 macro_rules! expect_pending_htlcs_forwardable_ignore {
1250 let events = $node.node.get_and_clear_pending_events();
1251 assert_eq!(events.len(), 1);
1253 $crate::util::events::Event::PendingHTLCsForwardable { .. } => { },
1254 _ => panic!("Unexpected event"),
1260 /// Handles a PendingHTLCsForwardable event
1261 macro_rules! expect_pending_htlcs_forwardable {
1263 $crate::expect_pending_htlcs_forwardable_ignore!($node);
1264 $node.node.process_pending_htlc_forwards();
1266 // Ensure process_pending_htlc_forwards is idempotent.
1267 $node.node.process_pending_htlc_forwards();
1272 macro_rules! expect_pending_htlcs_forwardable_from_events {
1273 ($node: expr, $events: expr, $ignore: expr) => {{
1274 assert_eq!($events.len(), 1);
1276 Event::PendingHTLCsForwardable { .. } => { },
1277 _ => panic!("Unexpected event"),
1280 $node.node.process_pending_htlc_forwards();
1282 // Ensure process_pending_htlc_forwards is idempotent.
1283 $node.node.process_pending_htlc_forwards();
1289 #[cfg(any(test, feature = "_bench_unstable", feature = "_test_utils"))]
1290 macro_rules! expect_payment_received {
1291 ($node: expr, $expected_payment_hash: expr, $expected_payment_secret: expr, $expected_recv_value: expr) => {
1292 expect_payment_received!($node, $expected_payment_hash, $expected_payment_secret, $expected_recv_value, None)
1294 ($node: expr, $expected_payment_hash: expr, $expected_payment_secret: expr, $expected_recv_value: expr, $expected_payment_preimage: expr) => {
1295 let events = $node.node.get_and_clear_pending_events();
1296 assert_eq!(events.len(), 1);
1298 $crate::util::events::Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1299 assert_eq!($expected_payment_hash, *payment_hash);
1300 assert_eq!($expected_recv_value, amt);
1302 $crate::util::events::PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1303 assert_eq!(&$expected_payment_preimage, payment_preimage);
1304 assert_eq!($expected_payment_secret, *payment_secret);
1309 _ => panic!("Unexpected event"),
1316 macro_rules! expect_payment_sent_without_paths {
1317 ($node: expr, $expected_payment_preimage: expr) => {
1318 expect_payment_sent!($node, $expected_payment_preimage, None::<u64>, false);
1320 ($node: expr, $expected_payment_preimage: expr, $expected_fee_msat_opt: expr) => {
1321 expect_payment_sent!($node, $expected_payment_preimage, $expected_fee_msat_opt, false);
1326 macro_rules! expect_payment_sent {
1327 ($node: expr, $expected_payment_preimage: expr) => {
1328 $crate::expect_payment_sent!($node, $expected_payment_preimage, None::<u64>, true);
1330 ($node: expr, $expected_payment_preimage: expr, $expected_fee_msat_opt: expr) => {
1331 $crate::expect_payment_sent!($node, $expected_payment_preimage, $expected_fee_msat_opt, true);
1333 ($node: expr, $expected_payment_preimage: expr, $expected_fee_msat_opt: expr, $expect_paths: expr) => { {
1334 use bitcoin::hashes::Hash as _;
1335 let events = $node.node.get_and_clear_pending_events();
1336 let expected_payment_hash = $crate::ln::PaymentHash(
1337 bitcoin::hashes::sha256::Hash::hash(&$expected_payment_preimage.0).into_inner());
1339 assert!(events.len() > 1);
1341 assert_eq!(events.len(), 1);
1343 let expected_payment_id = match events[0] {
1344 $crate::util::events::Event::PaymentSent { ref payment_id, ref payment_preimage, ref payment_hash, ref fee_paid_msat } => {
1345 assert_eq!($expected_payment_preimage, *payment_preimage);
1346 assert_eq!(expected_payment_hash, *payment_hash);
1347 assert!(fee_paid_msat.is_some());
1348 if $expected_fee_msat_opt.is_some() {
1349 assert_eq!(*fee_paid_msat, $expected_fee_msat_opt);
1353 _ => panic!("Unexpected event"),
1356 for i in 1..events.len() {
1358 $crate::util::events::Event::PaymentPathSuccessful { payment_id, payment_hash, .. } => {
1359 assert_eq!(payment_id, expected_payment_id);
1360 assert_eq!(payment_hash, Some(expected_payment_hash));
1362 _ => panic!("Unexpected event"),
1371 macro_rules! expect_payment_path_successful {
1373 let events = $node.node.get_and_clear_pending_events();
1374 assert_eq!(events.len(), 1);
1376 $crate::util::events::Event::PaymentPathSuccessful { .. } => {},
1377 _ => panic!("Unexpected event"),
1382 macro_rules! expect_payment_forwarded {
1383 ($node: expr, $source_node: expr, $expected_fee: expr, $upstream_force_closed: expr) => {
1384 let events = $node.node.get_and_clear_pending_events();
1385 assert_eq!(events.len(), 1);
1387 Event::PaymentForwarded { fee_earned_msat, source_channel_id, claim_from_onchain_tx } => {
1388 assert_eq!(fee_earned_msat, $expected_fee);
1389 if fee_earned_msat.is_some() {
1390 // Is the event channel_id in one of the channels between the two nodes?
1391 assert!($node.node.list_channels().iter().any(|x| x.counterparty.node_id == $source_node.node.get_our_node_id() && x.channel_id == source_channel_id.unwrap()));
1393 assert_eq!(claim_from_onchain_tx, $upstream_force_closed);
1395 _ => panic!("Unexpected event"),
1400 pub struct PaymentFailedConditions<'a> {
1401 pub(crate) expected_htlc_error_data: Option<(u16, &'a [u8])>,
1402 pub(crate) expected_blamed_scid: Option<u64>,
1403 pub(crate) expected_blamed_chan_closed: Option<bool>,
1404 pub(crate) expected_mpp_parts_remain: bool,
1407 impl<'a> PaymentFailedConditions<'a> {
1408 pub fn new() -> Self {
1410 expected_htlc_error_data: None,
1411 expected_blamed_scid: None,
1412 expected_blamed_chan_closed: None,
1413 expected_mpp_parts_remain: false,
1416 pub fn mpp_parts_remain(mut self) -> Self {
1417 self.expected_mpp_parts_remain = true;
1420 pub fn blamed_scid(mut self, scid: u64) -> Self {
1421 self.expected_blamed_scid = Some(scid);
1424 pub fn blamed_chan_closed(mut self, closed: bool) -> Self {
1425 self.expected_blamed_chan_closed = Some(closed);
1428 pub fn expected_htlc_error_data(mut self, code: u16, data: &'a [u8]) -> Self {
1429 self.expected_htlc_error_data = Some((code, data));
1435 macro_rules! expect_payment_failed_with_update {
1436 ($node: expr, $expected_payment_hash: expr, $rejected_by_dest: expr, $scid: expr, $chan_closed: expr) => {
1437 expect_payment_failed_conditions!($node, $expected_payment_hash, $rejected_by_dest,
1438 $crate::ln::functional_test_utils::PaymentFailedConditions::new().blamed_scid($scid).blamed_chan_closed($chan_closed));
1443 macro_rules! expect_payment_failed {
1444 ($node: expr, $expected_payment_hash: expr, $rejected_by_dest: expr $(, $expected_error_code: expr, $expected_error_data: expr)*) => {
1445 #[allow(unused_mut)]
1446 let mut conditions = $crate::ln::functional_test_utils::PaymentFailedConditions::new();
1448 conditions = conditions.expected_htlc_error_data($expected_error_code, &$expected_error_data);
1450 expect_payment_failed_conditions!($node, $expected_payment_hash, $rejected_by_dest, conditions);
1455 macro_rules! expect_payment_failed_conditions {
1456 ($node: expr, $expected_payment_hash: expr, $rejected_by_dest: expr, $conditions: expr) => {
1457 let events = $node.node.get_and_clear_pending_events();
1458 assert_eq!(events.len(), 1);
1459 let expected_payment_id = match events[0] {
1460 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest, ref error_code, ref error_data, ref path, ref retry, ref payment_id, ref network_update, .. } => {
1461 assert_eq!(*payment_hash, $expected_payment_hash, "unexpected payment_hash");
1462 assert_eq!(rejected_by_dest, $rejected_by_dest, "unexpected rejected_by_dest value");
1463 assert!(retry.is_some(), "expected retry.is_some()");
1464 assert_eq!(retry.as_ref().unwrap().final_value_msat, path.last().unwrap().fee_msat, "Retry amount should match last hop in path");
1465 assert_eq!(retry.as_ref().unwrap().payment_params.payee_pubkey, path.last().unwrap().pubkey, "Retry payee node_id should match last hop in path");
1467 assert!(error_code.is_some(), "expected error_code.is_some() = true");
1468 assert!(error_data.is_some(), "expected error_data.is_some() = true");
1469 if let Some((code, data)) = $conditions.expected_htlc_error_data {
1470 assert_eq!(error_code.unwrap(), code, "unexpected error code");
1471 assert_eq!(&error_data.as_ref().unwrap()[..], data, "unexpected error data");
1474 if let Some(chan_closed) = $conditions.expected_blamed_chan_closed {
1475 match network_update {
1476 &Some($crate::routing::network_graph::NetworkUpdate::ChannelUpdateMessage { ref msg }) if !chan_closed => {
1477 if let Some(scid) = $conditions.expected_blamed_scid {
1478 assert_eq!(msg.contents.short_channel_id, scid);
1480 assert_eq!(msg.contents.flags & 2, 0);
1482 &Some($crate::routing::network_graph::NetworkUpdate::ChannelClosed { short_channel_id, is_permanent }) if chan_closed => {
1483 if let Some(scid) = $conditions.expected_blamed_scid {
1484 assert_eq!(short_channel_id, scid);
1486 assert!(is_permanent);
1488 Some(_) => panic!("Unexpected update type"),
1489 None => panic!("Expected update"),
1495 _ => panic!("Unexpected event"),
1497 if !$conditions.expected_mpp_parts_remain {
1498 $node.node.abandon_payment(expected_payment_id);
1499 let events = $node.node.get_and_clear_pending_events();
1500 assert_eq!(events.len(), 1);
1502 Event::PaymentFailed { ref payment_hash, ref payment_id } => {
1503 assert_eq!(*payment_hash, $expected_payment_hash, "unexpected second payment_hash");
1504 assert_eq!(*payment_id, expected_payment_id);
1506 _ => panic!("Unexpected second event"),
1512 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 {
1513 let payment_id = origin_node.node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
1514 check_added_monitors!(origin_node, expected_paths.len());
1515 pass_along_route(origin_node, expected_paths, recv_value, our_payment_hash, our_payment_secret);
1519 pub fn pass_along_path<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_path: &[&Node<'a, 'b, 'c>], recv_value: u64, our_payment_hash: PaymentHash, our_payment_secret: Option<PaymentSecret>, ev: MessageSendEvent, payment_received_expected: bool, expected_preimage: Option<PaymentPreimage>) {
1520 let mut payment_event = SendEvent::from_event(ev);
1521 let mut prev_node = origin_node;
1523 for (idx, &node) in expected_path.iter().enumerate() {
1524 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
1526 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
1527 check_added_monitors!(node, 0);
1528 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
1530 expect_pending_htlcs_forwardable!(node);
1532 if idx == expected_path.len() - 1 {
1533 let events_2 = node.node.get_and_clear_pending_events();
1534 if payment_received_expected {
1535 assert_eq!(events_2.len(), 1);
1537 Event::PaymentReceived { ref payment_hash, ref purpose, amt} => {
1538 assert_eq!(our_payment_hash, *payment_hash);
1540 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1541 assert_eq!(expected_preimage, *payment_preimage);
1542 assert_eq!(our_payment_secret.unwrap(), *payment_secret);
1544 PaymentPurpose::SpontaneousPayment(payment_preimage) => {
1545 assert_eq!(expected_preimage.unwrap(), *payment_preimage);
1546 assert!(our_payment_secret.is_none());
1549 assert_eq!(amt, recv_value);
1551 _ => panic!("Unexpected event"),
1554 assert!(events_2.is_empty());
1557 let mut events_2 = node.node.get_and_clear_pending_msg_events();
1558 assert_eq!(events_2.len(), 1);
1559 check_added_monitors!(node, 1);
1560 payment_event = SendEvent::from_event(events_2.remove(0));
1561 assert_eq!(payment_event.msgs.len(), 1);
1568 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) {
1569 let mut events = origin_node.node.get_and_clear_pending_msg_events();
1570 assert_eq!(events.len(), expected_route.len());
1571 for (path_idx, (ev, expected_path)) in events.drain(..).zip(expected_route.iter()).enumerate() {
1572 // Once we've gotten through all the HTLCs, the last one should result in a
1573 // PaymentReceived (but each previous one should not!), .
1574 let expect_payment = path_idx == expected_route.len() - 1;
1575 pass_along_path(origin_node, expected_path, recv_value, our_payment_hash.clone(), Some(our_payment_secret), ev, expect_payment, None);
1579 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) {
1580 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(expected_route.last().unwrap());
1581 let payment_id = send_along_route_with_secret(origin_node, route, &[expected_route], recv_value, our_payment_hash, our_payment_secret);
1582 (our_payment_preimage, our_payment_hash, our_payment_secret, payment_id)
1585 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 {
1586 for path in expected_paths.iter() {
1587 assert_eq!(path.last().unwrap().node.get_our_node_id(), expected_paths[0].last().unwrap().node.get_our_node_id());
1589 assert!(expected_paths[0].last().unwrap().node.claim_funds(our_payment_preimage));
1590 check_added_monitors!(expected_paths[0].last().unwrap(), expected_paths.len());
1592 let mut expected_total_fee_msat = 0;
1594 macro_rules! msgs_from_ev {
1597 &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 } } => {
1598 assert!(update_add_htlcs.is_empty());
1599 assert_eq!(update_fulfill_htlcs.len(), 1);
1600 assert!(update_fail_htlcs.is_empty());
1601 assert!(update_fail_malformed_htlcs.is_empty());
1602 assert!(update_fee.is_none());
1603 ((update_fulfill_htlcs[0].clone(), commitment_signed.clone()), node_id.clone())
1605 _ => panic!("Unexpected event"),
1609 let mut per_path_msgs: Vec<((msgs::UpdateFulfillHTLC, msgs::CommitmentSigned), PublicKey)> = Vec::with_capacity(expected_paths.len());
1610 let events = expected_paths[0].last().unwrap().node.get_and_clear_pending_msg_events();
1611 assert_eq!(events.len(), expected_paths.len());
1612 for ev in events.iter() {
1613 per_path_msgs.push(msgs_from_ev!(ev));
1616 for (expected_route, (path_msgs, next_hop)) in expected_paths.iter().zip(per_path_msgs.drain(..)) {
1617 let mut next_msgs = Some(path_msgs);
1618 let mut expected_next_node = next_hop;
1620 macro_rules! last_update_fulfill_dance {
1621 ($node: expr, $prev_node: expr) => {
1623 $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0);
1624 check_added_monitors!($node, 0);
1625 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
1626 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
1630 macro_rules! mid_update_fulfill_dance {
1631 ($node: expr, $prev_node: expr, $next_node: expr, $new_msgs: expr) => {
1633 $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0);
1634 let fee = $node.node.channel_state.lock().unwrap().by_id.get(&next_msgs.as_ref().unwrap().0.channel_id).unwrap().config.forwarding_fee_base_msat;
1635 expect_payment_forwarded!($node, $next_node, Some(fee as u64), false);
1636 expected_total_fee_msat += fee as u64;
1637 check_added_monitors!($node, 1);
1638 let new_next_msgs = if $new_msgs {
1639 let events = $node.node.get_and_clear_pending_msg_events();
1640 assert_eq!(events.len(), 1);
1641 let (res, nexthop) = msgs_from_ev!(&events[0]);
1642 expected_next_node = nexthop;
1645 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
1648 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
1649 next_msgs = new_next_msgs;
1654 let mut prev_node = expected_route.last().unwrap();
1655 for (idx, node) in expected_route.iter().rev().enumerate().skip(1) {
1656 assert_eq!(expected_next_node, node.node.get_our_node_id());
1657 let update_next_msgs = !skip_last || idx != expected_route.len() - 1;
1658 if next_msgs.is_some() {
1659 // Since we are traversing in reverse, next_node is actually the previous node
1660 let next_node: &Node;
1661 if idx == expected_route.len() - 1 {
1662 next_node = origin_node;
1664 next_node = expected_route[expected_route.len() - 1 - idx - 1];
1666 mid_update_fulfill_dance!(node, prev_node, next_node, update_next_msgs);
1668 assert!(!update_next_msgs);
1669 assert!(node.node.get_and_clear_pending_msg_events().is_empty());
1671 if !skip_last && idx == expected_route.len() - 1 {
1672 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
1679 last_update_fulfill_dance!(origin_node, expected_route.first().unwrap());
1683 // Ensure that claim_funds is idempotent.
1684 assert!(!expected_paths[0].last().unwrap().node.claim_funds(our_payment_preimage));
1685 assert!(expected_paths[0].last().unwrap().node.get_and_clear_pending_msg_events().is_empty());
1686 check_added_monitors!(expected_paths[0].last().unwrap(), 0);
1688 expected_total_fee_msat
1690 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) {
1691 let expected_total_fee_msat = do_claim_payment_along_route(origin_node, expected_paths, skip_last, our_payment_preimage);
1693 expect_payment_sent!(origin_node, our_payment_preimage, Some(expected_total_fee_msat));
1697 pub fn claim_payment<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_route: &[&Node<'a, 'b, 'c>], our_payment_preimage: PaymentPreimage) {
1698 claim_payment_along_route(origin_node, &[expected_route], false, our_payment_preimage);
1701 pub const TEST_FINAL_CLTV: u32 = 70;
1703 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) {
1704 let payment_params = PaymentParameters::from_node_id(expected_route.last().unwrap().node.get_our_node_id())
1705 .with_features(InvoiceFeatures::known());
1706 let route = get_route!(origin_node, payment_params, recv_value, TEST_FINAL_CLTV).unwrap();
1707 assert_eq!(route.paths.len(), 1);
1708 assert_eq!(route.paths[0].len(), expected_route.len());
1709 for (node, hop) in expected_route.iter().zip(route.paths[0].iter()) {
1710 assert_eq!(hop.pubkey, node.node.get_our_node_id());
1713 let res = send_along_route(origin_node, route, expected_route, recv_value);
1714 (res.0, res.1, res.2)
1717 pub fn route_over_limit<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_route: &[&Node<'a, 'b, 'c>], recv_value: u64) {
1718 let payment_params = PaymentParameters::from_node_id(expected_route.last().unwrap().node.get_our_node_id())
1719 .with_features(InvoiceFeatures::known());
1720 let network_graph = origin_node.network_graph.read_only();
1721 let scorer = test_utils::TestScorer::with_penalty(0);
1722 let seed = [0u8; 32];
1723 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
1724 let random_seed_bytes = keys_manager.get_secure_random_bytes();
1725 let route = get_route(
1726 &origin_node.node.get_our_node_id(), &payment_params, &network_graph,
1727 None, recv_value, TEST_FINAL_CLTV, origin_node.logger, &scorer, &random_seed_bytes).unwrap();
1728 assert_eq!(route.paths.len(), 1);
1729 assert_eq!(route.paths[0].len(), expected_route.len());
1730 for (node, hop) in expected_route.iter().zip(route.paths[0].iter()) {
1731 assert_eq!(hop.pubkey, node.node.get_our_node_id());
1734 let (_, our_payment_hash, our_payment_preimage) = get_payment_preimage_hash!(expected_route.last().unwrap());
1735 unwrap_send_err!(origin_node.node.send_payment(&route, our_payment_hash, &Some(our_payment_preimage)), true, APIError::ChannelUnavailable { ref err },
1736 assert!(err.contains("Cannot send value that would put us over the max HTLC value in flight our peer will accept")));
1739 pub fn send_payment<'a, 'b, 'c>(origin: &Node<'a, 'b, 'c>, expected_route: &[&Node<'a, 'b, 'c>], recv_value: u64) {
1740 let our_payment_preimage = route_payment(&origin, expected_route, recv_value).0;
1741 claim_payment(&origin, expected_route, our_payment_preimage);
1744 pub fn fail_payment_along_route<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_paths_slice: &[&[&Node<'a, 'b, 'c>]], skip_last: bool, our_payment_hash: PaymentHash) {
1745 let mut expected_paths: Vec<_> = expected_paths_slice.iter().collect();
1746 for path in expected_paths.iter() {
1747 assert_eq!(path.last().unwrap().node.get_our_node_id(), expected_paths[0].last().unwrap().node.get_our_node_id());
1749 assert!(expected_paths[0].last().unwrap().node.fail_htlc_backwards(&our_payment_hash));
1750 expect_pending_htlcs_forwardable!(expected_paths[0].last().unwrap());
1751 check_added_monitors!(expected_paths[0].last().unwrap(), expected_paths.len());
1753 let mut per_path_msgs: Vec<((msgs::UpdateFailHTLC, msgs::CommitmentSigned), PublicKey)> = Vec::with_capacity(expected_paths.len());
1754 let events = expected_paths[0].last().unwrap().node.get_and_clear_pending_msg_events();
1755 assert_eq!(events.len(), expected_paths.len());
1756 for ev in events.iter() {
1757 let (update_fail, commitment_signed, node_id) = match ev {
1758 &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 } } => {
1759 assert!(update_add_htlcs.is_empty());
1760 assert!(update_fulfill_htlcs.is_empty());
1761 assert_eq!(update_fail_htlcs.len(), 1);
1762 assert!(update_fail_malformed_htlcs.is_empty());
1763 assert!(update_fee.is_none());
1764 (update_fail_htlcs[0].clone(), commitment_signed.clone(), node_id.clone())
1766 _ => panic!("Unexpected event"),
1768 per_path_msgs.push(((update_fail, commitment_signed), node_id));
1770 per_path_msgs.sort_unstable_by(|(_, node_id_a), (_, node_id_b)| node_id_a.cmp(node_id_b));
1771 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()));
1773 for (i, (expected_route, (path_msgs, next_hop))) in expected_paths.iter().zip(per_path_msgs.drain(..)).enumerate() {
1774 let mut next_msgs = Some(path_msgs);
1775 let mut expected_next_node = next_hop;
1776 let mut prev_node = expected_route.last().unwrap();
1778 for (idx, node) in expected_route.iter().rev().enumerate().skip(1) {
1779 assert_eq!(expected_next_node, node.node.get_our_node_id());
1780 let update_next_node = !skip_last || idx != expected_route.len() - 1;
1781 if next_msgs.is_some() {
1782 node.node.handle_update_fail_htlc(&prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0);
1783 commitment_signed_dance!(node, prev_node, next_msgs.as_ref().unwrap().1, update_next_node);
1784 if !update_next_node {
1785 expect_pending_htlcs_forwardable!(node);
1788 let events = node.node.get_and_clear_pending_msg_events();
1789 if update_next_node {
1790 assert_eq!(events.len(), 1);
1792 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 } } => {
1793 assert!(update_add_htlcs.is_empty());
1794 assert!(update_fulfill_htlcs.is_empty());
1795 assert_eq!(update_fail_htlcs.len(), 1);
1796 assert!(update_fail_malformed_htlcs.is_empty());
1797 assert!(update_fee.is_none());
1798 expected_next_node = node_id.clone();
1799 next_msgs = Some((update_fail_htlcs[0].clone(), commitment_signed.clone()));
1801 _ => panic!("Unexpected event"),
1804 assert!(events.is_empty());
1806 if !skip_last && idx == expected_route.len() - 1 {
1807 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
1814 let prev_node = expected_route.first().unwrap();
1815 origin_node.node.handle_update_fail_htlc(&prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0);
1816 check_added_monitors!(origin_node, 0);
1817 assert!(origin_node.node.get_and_clear_pending_msg_events().is_empty());
1818 commitment_signed_dance!(origin_node, prev_node, next_msgs.as_ref().unwrap().1, false);
1819 let events = origin_node.node.get_and_clear_pending_events();
1820 assert_eq!(events.len(), 1);
1821 let expected_payment_id = match events[0] {
1822 Event::PaymentPathFailed { payment_hash, rejected_by_dest, all_paths_failed, ref path, ref payment_id, .. } => {
1823 assert_eq!(payment_hash, our_payment_hash);
1824 assert!(rejected_by_dest);
1825 assert_eq!(all_paths_failed, i == expected_paths.len() - 1);
1826 for (idx, hop) in expected_route.iter().enumerate() {
1827 assert_eq!(hop.node.get_our_node_id(), path[idx].pubkey);
1831 _ => panic!("Unexpected event"),
1833 if i == expected_paths.len() - 1 {
1834 origin_node.node.abandon_payment(expected_payment_id);
1835 let events = origin_node.node.get_and_clear_pending_events();
1836 assert_eq!(events.len(), 1);
1838 Event::PaymentFailed { ref payment_hash, ref payment_id } => {
1839 assert_eq!(*payment_hash, our_payment_hash, "unexpected second payment_hash");
1840 assert_eq!(*payment_id, expected_payment_id);
1842 _ => panic!("Unexpected second event"),
1848 // Ensure that fail_htlc_backwards is idempotent.
1849 assert!(!expected_paths[0].last().unwrap().node.fail_htlc_backwards(&our_payment_hash));
1850 assert!(expected_paths[0].last().unwrap().node.get_and_clear_pending_events().is_empty());
1851 assert!(expected_paths[0].last().unwrap().node.get_and_clear_pending_msg_events().is_empty());
1852 check_added_monitors!(expected_paths[0].last().unwrap(), 0);
1855 pub fn fail_payment<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_path: &[&Node<'a, 'b, 'c>], our_payment_hash: PaymentHash) {
1856 fail_payment_along_route(origin_node, &[&expected_path[..]], false, our_payment_hash);
1859 pub fn create_chanmon_cfgs(node_count: usize) -> Vec<TestChanMonCfg> {
1860 let mut chan_mon_cfgs = Vec::new();
1861 for i in 0..node_count {
1862 let tx_broadcaster = test_utils::TestBroadcaster {
1863 txn_broadcasted: Mutex::new(Vec::new()),
1864 blocks: Arc::new(Mutex::new(vec![(genesis_block(Network::Testnet), 0)])),
1866 let fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
1867 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
1868 let logger = test_utils::TestLogger::with_id(format!("node {}", i));
1869 let persister = test_utils::TestPersister::new();
1870 let seed = [i as u8; 32];
1871 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
1872 let network_graph = NetworkGraph::new(chain_source.genesis_hash);
1874 chan_mon_cfgs.push(TestChanMonCfg{ tx_broadcaster, fee_estimator, chain_source, logger, persister, keys_manager, network_graph });
1880 pub fn create_node_cfgs<'a>(node_count: usize, chanmon_cfgs: &'a Vec<TestChanMonCfg>) -> Vec<NodeCfg<'a>> {
1881 let mut nodes = Vec::new();
1883 for i in 0..node_count {
1884 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);
1885 let seed = [i as u8; 32];
1886 nodes.push(NodeCfg {
1887 chain_source: &chanmon_cfgs[i].chain_source,
1888 logger: &chanmon_cfgs[i].logger,
1889 tx_broadcaster: &chanmon_cfgs[i].tx_broadcaster,
1890 fee_estimator: &chanmon_cfgs[i].fee_estimator,
1892 keys_manager: &chanmon_cfgs[i].keys_manager,
1894 features: InitFeatures::known(),
1895 network_graph: &chanmon_cfgs[i].network_graph,
1902 pub fn test_default_channel_config() -> UserConfig {
1903 let mut default_config = UserConfig::default();
1904 // Set cltv_expiry_delta slightly lower to keep the final CLTV values inside one byte in our
1905 // tests so that our script-length checks don't fail (see ACCEPTED_HTLC_SCRIPT_WEIGHT).
1906 default_config.channel_options.cltv_expiry_delta = MIN_CLTV_EXPIRY_DELTA;
1907 default_config.channel_options.announced_channel = true;
1908 default_config.peer_channel_config_limits.force_announced_channel_preference = false;
1909 // When most of our tests were written, the default HTLC minimum was fixed at 1000.
1910 // It now defaults to 1, so we simply set it to the expected value here.
1911 default_config.own_channel_config.our_htlc_minimum_msat = 1000;
1912 // When most of our tests were written, we didn't have the notion of a `max_dust_htlc_exposure_msat`,
1913 // It now defaults to 5_000_000 msat; to avoid interfering with tests we bump it to 50_000_000 msat.
1914 default_config.channel_options.max_dust_htlc_exposure_msat = 50_000_000;
1918 pub fn create_node_chanmgrs<'a, 'b>(node_count: usize, cfgs: &'a Vec<NodeCfg<'b>>, node_config: &[Option<UserConfig>]) -> Vec<ChannelManager<EnforcingSigner, &'a TestChainMonitor<'b>, &'b test_utils::TestBroadcaster, &'a test_utils::TestKeysInterface, &'b test_utils::TestFeeEstimator, &'b test_utils::TestLogger>> {
1919 let mut chanmgrs = Vec::new();
1920 for i in 0..node_count {
1921 let network = Network::Testnet;
1922 let params = ChainParameters {
1924 best_block: BestBlock::from_genesis(network),
1926 let node = ChannelManager::new(cfgs[i].fee_estimator, &cfgs[i].chain_monitor, cfgs[i].tx_broadcaster, cfgs[i].logger, cfgs[i].keys_manager,
1927 if node_config[i].is_some() { node_config[i].clone().unwrap() } else { test_default_channel_config() }, params);
1928 chanmgrs.push(node);
1934 pub fn create_network<'a, 'b: 'a, 'c: 'b>(node_count: usize, cfgs: &'b Vec<NodeCfg<'c>>, chan_mgrs: &'a Vec<ChannelManager<EnforcingSigner, &'b TestChainMonitor<'c>, &'c test_utils::TestBroadcaster, &'b test_utils::TestKeysInterface, &'c test_utils::TestFeeEstimator, &'c test_utils::TestLogger>>) -> Vec<Node<'a, 'b, 'c>> {
1935 let mut nodes = Vec::new();
1936 let chan_count = Rc::new(RefCell::new(0));
1937 let payment_count = Rc::new(RefCell::new(0));
1938 let connect_style = Rc::new(RefCell::new(ConnectStyle::random_style()));
1940 for i in 0..node_count {
1941 let net_graph_msg_handler = NetGraphMsgHandler::new(cfgs[i].network_graph, None, cfgs[i].logger);
1943 chain_source: cfgs[i].chain_source, tx_broadcaster: cfgs[i].tx_broadcaster,
1944 chain_monitor: &cfgs[i].chain_monitor, keys_manager: &cfgs[i].keys_manager,
1945 node: &chan_mgrs[i], network_graph: &cfgs[i].network_graph, net_graph_msg_handler,
1946 node_seed: cfgs[i].node_seed, network_chan_count: chan_count.clone(),
1947 network_payment_count: payment_count.clone(), logger: cfgs[i].logger,
1948 blocks: Arc::clone(&cfgs[i].tx_broadcaster.blocks),
1949 connect_style: Rc::clone(&connect_style),
1953 for i in 0..node_count {
1954 for j in (i+1)..node_count {
1955 nodes[i].node.peer_connected(&nodes[j].node.get_our_node_id(), &msgs::Init { features: cfgs[j].features.clone(), remote_network_address: None });
1956 nodes[j].node.peer_connected(&nodes[i].node.get_our_node_id(), &msgs::Init { features: cfgs[i].features.clone(), remote_network_address: None });
1963 // Note that the following only works for CLTV values up to 128
1964 pub const ACCEPTED_HTLC_SCRIPT_WEIGHT: usize = 137; //Here we have a diff due to HTLC CLTV expiry being < 2^15 in test
1965 pub const OFFERED_HTLC_SCRIPT_WEIGHT: usize = 133;
1967 #[derive(PartialEq)]
1968 pub enum HTLCType { NONE, TIMEOUT, SUCCESS }
1969 /// Tests that the given node has broadcast transactions for the given Channel
1971 /// First checks that the latest holder commitment tx has been broadcast, unless an explicit
1972 /// commitment_tx is provided, which may be used to test that a remote commitment tx was
1973 /// broadcast and the revoked outputs were claimed.
1975 /// Next tests that there is (or is not) a transaction that spends the commitment transaction
1976 /// that appears to be the type of HTLC transaction specified in has_htlc_tx.
1978 /// All broadcast transactions must be accounted for in one of the above three types of we'll
1980 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> {
1981 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
1982 assert!(node_txn.len() >= if commitment_tx.is_some() { 0 } else { 1 } + if has_htlc_tx == HTLCType::NONE { 0 } else { 1 });
1984 let mut res = Vec::with_capacity(2);
1985 node_txn.retain(|tx| {
1986 if tx.input.len() == 1 && tx.input[0].previous_output.txid == chan.3.txid() {
1987 check_spends!(tx, chan.3);
1988 if commitment_tx.is_none() {
1989 res.push(tx.clone());
1994 if let Some(explicit_tx) = commitment_tx {
1995 res.push(explicit_tx.clone());
1998 assert_eq!(res.len(), 1);
2000 if has_htlc_tx != HTLCType::NONE {
2001 node_txn.retain(|tx| {
2002 if tx.input.len() == 1 && tx.input[0].previous_output.txid == res[0].txid() {
2003 check_spends!(tx, res[0]);
2004 if has_htlc_tx == HTLCType::TIMEOUT {
2005 assert!(tx.lock_time != 0);
2007 assert!(tx.lock_time == 0);
2009 res.push(tx.clone());
2013 assert!(res.len() == 2 || res.len() == 3);
2015 assert_eq!(res[1], res[2]);
2019 assert!(node_txn.is_empty());
2023 /// Tests that the given node has broadcast a claim transaction against the provided revoked
2024 /// HTLC transaction.
2025 pub fn test_revoked_htlc_claim_txn_broadcast<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, revoked_tx: Transaction, commitment_revoked_tx: Transaction) {
2026 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2027 // We may issue multiple claiming transaction on revoked outputs due to block rescan
2028 // for revoked htlc outputs
2029 if node_txn.len() != 1 && node_txn.len() != 2 && node_txn.len() != 3 { assert!(false); }
2030 node_txn.retain(|tx| {
2031 if tx.input.len() == 1 && tx.input[0].previous_output.txid == revoked_tx.txid() {
2032 check_spends!(tx, revoked_tx);
2036 node_txn.retain(|tx| {
2037 check_spends!(tx, commitment_revoked_tx);
2040 assert!(node_txn.is_empty());
2043 pub fn check_preimage_claim<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, prev_txn: &Vec<Transaction>) -> Vec<Transaction> {
2044 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2046 assert!(node_txn.len() >= 1);
2047 assert_eq!(node_txn[0].input.len(), 1);
2048 let mut found_prev = false;
2050 for tx in prev_txn {
2051 if node_txn[0].input[0].previous_output.txid == tx.txid() {
2052 check_spends!(node_txn[0], tx);
2053 let mut iter = node_txn[0].input[0].witness.iter();
2054 iter.next().expect("expected 3 witness items");
2055 iter.next().expect("expected 3 witness items");
2056 assert!(iter.next().expect("expected 3 witness items").len() > 106); // must spend an htlc output
2057 assert_eq!(tx.input.len(), 1); // must spend a commitment tx
2063 assert!(found_prev);
2065 let mut res = Vec::new();
2066 mem::swap(&mut *node_txn, &mut res);
2070 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) {
2071 let events_1 = nodes[a].node.get_and_clear_pending_msg_events();
2072 assert_eq!(events_1.len(), 2);
2073 let as_update = match events_1[0] {
2074 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2077 _ => panic!("Unexpected event"),
2080 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
2081 assert_eq!(node_id, nodes[b].node.get_our_node_id());
2082 assert_eq!(msg.data, expected_error);
2083 if needs_err_handle {
2084 nodes[b].node.handle_error(&nodes[a].node.get_our_node_id(), msg);
2087 _ => panic!("Unexpected event"),
2090 let events_2 = nodes[b].node.get_and_clear_pending_msg_events();
2091 assert_eq!(events_2.len(), if needs_err_handle { 1 } else { 2 });
2092 let bs_update = match events_2[0] {
2093 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2096 _ => panic!("Unexpected event"),
2098 if !needs_err_handle {
2100 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
2101 assert_eq!(node_id, nodes[a].node.get_our_node_id());
2102 assert_eq!(msg.data, expected_error);
2104 _ => panic!("Unexpected event"),
2109 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
2110 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
2114 pub fn get_announce_close_broadcast_events<'a, 'b, 'c>(nodes: &Vec<Node<'a, 'b, 'c>>, a: usize, b: usize) {
2115 handle_announce_close_broadcast_events(nodes, a, b, false, "Channel closed because commitment or closing transaction was confirmed on chain.");
2119 macro_rules! get_channel_value_stat {
2120 ($node: expr, $channel_id: expr) => {{
2121 let chan_lock = $node.node.channel_state.lock().unwrap();
2122 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
2123 chan.get_value_stat()
2127 macro_rules! get_chan_reestablish_msgs {
2128 ($src_node: expr, $dst_node: expr) => {
2130 let mut res = Vec::with_capacity(1);
2131 for msg in $src_node.node.get_and_clear_pending_msg_events() {
2132 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
2133 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2134 res.push(msg.clone());
2136 panic!("Unexpected event")
2144 macro_rules! handle_chan_reestablish_msgs {
2145 ($src_node: expr, $dst_node: expr) => {
2147 let msg_events = $src_node.node.get_and_clear_pending_msg_events();
2149 let funding_locked = if let Some(&MessageSendEvent::SendFundingLocked { ref node_id, ref msg }) = msg_events.get(0) {
2151 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2157 if let Some(&MessageSendEvent::SendAnnouncementSignatures { ref node_id, msg: _ }) = msg_events.get(idx) {
2159 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2162 let mut revoke_and_ack = None;
2163 let mut commitment_update = None;
2164 let order = if let Some(ev) = msg_events.get(idx) {
2166 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
2167 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2168 revoke_and_ack = Some(msg.clone());
2170 RAACommitmentOrder::RevokeAndACKFirst
2172 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
2173 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2174 commitment_update = Some(updates.clone());
2176 RAACommitmentOrder::CommitmentFirst
2178 _ => RAACommitmentOrder::CommitmentFirst,
2181 RAACommitmentOrder::CommitmentFirst
2184 if let Some(ev) = msg_events.get(idx) {
2186 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
2187 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2188 assert!(revoke_and_ack.is_none());
2189 revoke_and_ack = Some(msg.clone());
2192 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
2193 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2194 assert!(commitment_update.is_none());
2195 commitment_update = Some(updates.clone());
2202 if let Some(&MessageSendEvent::SendChannelUpdate { ref node_id, ref msg }) = msg_events.get(idx) {
2203 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2205 assert_eq!(msg.contents.flags & 2, 0); // "disabled" flag must not be set as we just reconnected.
2208 assert_eq!(msg_events.len(), idx);
2210 (funding_locked, revoke_and_ack, commitment_update, order)
2215 /// pending_htlc_adds includes both the holding cell and in-flight update_add_htlcs, whereas
2216 /// for claims/fails they are separated out.
2217 pub fn reconnect_nodes<'a, 'b, 'c>(node_a: &Node<'a, 'b, 'c>, node_b: &Node<'a, 'b, 'c>, send_funding_locked: (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)) {
2218 node_a.node.peer_connected(&node_b.node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
2219 let reestablish_1 = get_chan_reestablish_msgs!(node_a, node_b);
2220 node_b.node.peer_connected(&node_a.node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
2221 let reestablish_2 = get_chan_reestablish_msgs!(node_b, node_a);
2223 if send_funding_locked.0 {
2224 // If a expects a funding_locked, it better not think it has received a revoke_and_ack
2226 for reestablish in reestablish_1.iter() {
2227 assert_eq!(reestablish.next_remote_commitment_number, 0);
2230 if send_funding_locked.1 {
2231 // If b expects a funding_locked, it better not think it has received a revoke_and_ack
2233 for reestablish in reestablish_2.iter() {
2234 assert_eq!(reestablish.next_remote_commitment_number, 0);
2237 if send_funding_locked.0 || send_funding_locked.1 {
2238 // If we expect any funding_locked's, both sides better have set
2239 // next_holder_commitment_number to 1
2240 for reestablish in reestablish_1.iter() {
2241 assert_eq!(reestablish.next_local_commitment_number, 1);
2243 for reestablish in reestablish_2.iter() {
2244 assert_eq!(reestablish.next_local_commitment_number, 1);
2248 let mut resp_1 = Vec::new();
2249 for msg in reestablish_1 {
2250 node_b.node.handle_channel_reestablish(&node_a.node.get_our_node_id(), &msg);
2251 resp_1.push(handle_chan_reestablish_msgs!(node_b, node_a));
2253 if pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
2254 check_added_monitors!(node_b, 1);
2256 check_added_monitors!(node_b, 0);
2259 let mut resp_2 = Vec::new();
2260 for msg in reestablish_2 {
2261 node_a.node.handle_channel_reestablish(&node_b.node.get_our_node_id(), &msg);
2262 resp_2.push(handle_chan_reestablish_msgs!(node_a, node_b));
2264 if pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
2265 check_added_monitors!(node_a, 1);
2267 check_added_monitors!(node_a, 0);
2270 // We don't yet support both needing updates, as that would require a different commitment dance:
2271 assert!((pending_htlc_adds.0 == 0 && pending_htlc_claims.0 == 0 && pending_htlc_fails.0 == 0 &&
2272 pending_cell_htlc_claims.0 == 0 && pending_cell_htlc_fails.0 == 0) ||
2273 (pending_htlc_adds.1 == 0 && pending_htlc_claims.1 == 0 && pending_htlc_fails.1 == 0 &&
2274 pending_cell_htlc_claims.1 == 0 && pending_cell_htlc_fails.1 == 0));
2276 for chan_msgs in resp_1.drain(..) {
2277 if send_funding_locked.0 {
2278 node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), &chan_msgs.0.unwrap());
2279 let announcement_event = node_a.node.get_and_clear_pending_msg_events();
2280 if !announcement_event.is_empty() {
2281 assert_eq!(announcement_event.len(), 1);
2282 if let MessageSendEvent::SendChannelUpdate { .. } = announcement_event[0] {
2283 //TODO: Test announcement_sigs re-sending
2284 } else { panic!("Unexpected event! {:?}", announcement_event[0]); }
2287 assert!(chan_msgs.0.is_none());
2290 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
2291 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap());
2292 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
2293 check_added_monitors!(node_a, 1);
2295 assert!(chan_msgs.1.is_none());
2297 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 {
2298 let commitment_update = chan_msgs.2.unwrap();
2299 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
2300 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.0 as usize);
2302 assert!(commitment_update.update_add_htlcs.is_empty());
2304 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
2305 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_htlc_fails.0 + pending_cell_htlc_fails.0);
2306 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
2307 for update_add in commitment_update.update_add_htlcs {
2308 node_a.node.handle_update_add_htlc(&node_b.node.get_our_node_id(), &update_add);
2310 for update_fulfill in commitment_update.update_fulfill_htlcs {
2311 node_a.node.handle_update_fulfill_htlc(&node_b.node.get_our_node_id(), &update_fulfill);
2313 for update_fail in commitment_update.update_fail_htlcs {
2314 node_a.node.handle_update_fail_htlc(&node_b.node.get_our_node_id(), &update_fail);
2317 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
2318 commitment_signed_dance!(node_a, node_b, commitment_update.commitment_signed, false);
2320 node_a.node.handle_commitment_signed(&node_b.node.get_our_node_id(), &commitment_update.commitment_signed);
2321 check_added_monitors!(node_a, 1);
2322 let as_revoke_and_ack = get_event_msg!(node_a, MessageSendEvent::SendRevokeAndACK, node_b.node.get_our_node_id());
2323 // No commitment_signed so get_event_msg's assert(len == 1) passes
2324 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &as_revoke_and_ack);
2325 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
2326 check_added_monitors!(node_b, 1);
2329 assert!(chan_msgs.2.is_none());
2333 for chan_msgs in resp_2.drain(..) {
2334 if send_funding_locked.1 {
2335 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &chan_msgs.0.unwrap());
2336 let announcement_event = node_b.node.get_and_clear_pending_msg_events();
2337 if !announcement_event.is_empty() {
2338 assert_eq!(announcement_event.len(), 1);
2339 match announcement_event[0] {
2340 MessageSendEvent::SendChannelUpdate { .. } => {},
2341 MessageSendEvent::SendAnnouncementSignatures { .. } => {},
2342 _ => panic!("Unexpected event {:?}!", announcement_event[0]),
2346 assert!(chan_msgs.0.is_none());
2349 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
2350 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap());
2351 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
2352 check_added_monitors!(node_b, 1);
2354 assert!(chan_msgs.1.is_none());
2356 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 {
2357 let commitment_update = chan_msgs.2.unwrap();
2358 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
2359 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.1 as usize);
2361 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.1 + pending_cell_htlc_claims.1);
2362 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_htlc_fails.1 + pending_cell_htlc_fails.1);
2363 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
2364 for update_add in commitment_update.update_add_htlcs {
2365 node_b.node.handle_update_add_htlc(&node_a.node.get_our_node_id(), &update_add);
2367 for update_fulfill in commitment_update.update_fulfill_htlcs {
2368 node_b.node.handle_update_fulfill_htlc(&node_a.node.get_our_node_id(), &update_fulfill);
2370 for update_fail in commitment_update.update_fail_htlcs {
2371 node_b.node.handle_update_fail_htlc(&node_a.node.get_our_node_id(), &update_fail);
2374 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
2375 commitment_signed_dance!(node_b, node_a, commitment_update.commitment_signed, false);
2377 node_b.node.handle_commitment_signed(&node_a.node.get_our_node_id(), &commitment_update.commitment_signed);
2378 check_added_monitors!(node_b, 1);
2379 let bs_revoke_and_ack = get_event_msg!(node_b, MessageSendEvent::SendRevokeAndACK, node_a.node.get_our_node_id());
2380 // No commitment_signed so get_event_msg's assert(len == 1) passes
2381 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &bs_revoke_and_ack);
2382 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
2383 check_added_monitors!(node_a, 1);
2386 assert!(chan_msgs.2.is_none());