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