Merge pull request #1481 from TheBlueMatt/2022-05-new-chain-tests
[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 chain::{BestBlock, Confirm, Listen, Watch, keysinterface::KeysInterface};
14 use chain::channelmonitor::ChannelMonitor;
15 use chain::transaction::OutPoint;
16 use ln::{PaymentPreimage, PaymentHash, PaymentSecret};
17 use ln::channelmanager::{ChainParameters, ChannelManager, ChannelManagerReadArgs, RAACommitmentOrder, PaymentSendFailure, PaymentId, MIN_CLTV_EXPIRY_DELTA};
18 use routing::network_graph::{NetGraphMsgHandler, NetworkGraph};
19 use routing::router::{PaymentParameters, Route, get_route};
20 use ln::features::{InitFeatures, InvoiceFeatures};
21 use ln::msgs;
22 use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler};
23 use util::enforcing_trait_impls::EnforcingSigner;
24 use util::test_utils;
25 use util::test_utils::{panicking, TestChainMonitor};
26 use util::events::{Event, MessageSendEvent, MessageSendEventsProvider, PaymentPurpose};
27 use util::errors::APIError;
28 use util::config::UserConfig;
29 use util::ser::{ReadableArgs, Writeable, Readable};
30
31 use bitcoin::blockdata::block::{Block, BlockHeader};
32 use bitcoin::blockdata::constants::genesis_block;
33 use bitcoin::blockdata::transaction::{Transaction, TxOut};
34 use bitcoin::network::constants::Network;
35
36 use bitcoin::hash_types::BlockHash;
37
38 use bitcoin::secp256k1::PublicKey;
39
40 use io;
41 use prelude::*;
42 use core::cell::RefCell;
43 use alloc::rc::Rc;
44 use sync::{Arc, Mutex};
45 use core::mem;
46
47 pub const CHAN_CONFIRM_DEPTH: u32 = 10;
48
49 /// Mine the given transaction in the next block and then mine CHAN_CONFIRM_DEPTH - 1 blocks on
50 /// top, giving the given transaction CHAN_CONFIRM_DEPTH confirmations.
51 pub fn confirm_transaction<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, tx: &Transaction) {
52         confirm_transaction_at(node, tx, node.best_block_info().1 + 1);
53         connect_blocks(node, CHAN_CONFIRM_DEPTH - 1);
54 }
55 /// Mine a signle block containing the given transaction
56 pub fn mine_transaction<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, tx: &Transaction) {
57         let height = node.best_block_info().1 + 1;
58         confirm_transaction_at(node, tx, height);
59 }
60 /// Mine the given transaction at the given height, mining blocks as required to build to that
61 /// height
62 pub fn confirm_transaction_at<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, tx: &Transaction, conf_height: u32) {
63         let first_connect_height = node.best_block_info().1 + 1;
64         assert!(first_connect_height <= conf_height);
65         if conf_height > first_connect_height {
66                 connect_blocks(node, conf_height - first_connect_height);
67         }
68         let mut block = Block {
69                 header: BlockHeader { version: 0x20000000, prev_blockhash: node.best_block_hash(), merkle_root: Default::default(), time: conf_height, bits: 42, nonce: 42 },
70                 txdata: Vec::new(),
71         };
72         for _ in 0..*node.network_chan_count.borrow() { // Make sure we don't end up with channels at the same short id by offsetting by chan_count
73                 block.txdata.push(Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() });
74         }
75         block.txdata.push(tx.clone());
76         connect_block(node, &block);
77 }
78
79 /// The possible ways we may notify a ChannelManager of a new block
80 #[derive(Clone, Copy, Debug, PartialEq)]
81 pub enum ConnectStyle {
82         /// Calls `best_block_updated` first, detecting transactions in the block only after receiving
83         /// the header and height information.
84         BestBlockFirst,
85         /// The same as `BestBlockFirst`, however when we have multiple blocks to connect, we only
86         /// make a single `best_block_updated` call.
87         BestBlockFirstSkippingBlocks,
88         /// The same as `BestBlockFirst` when connecting blocks. During disconnection only
89         /// `transaction_unconfirmed` is called.
90         BestBlockFirstReorgsOnlyTip,
91         /// Calls `transactions_confirmed` first, detecting transactions in the block before updating
92         /// the header and height information.
93         TransactionsFirst,
94         /// The same as `TransactionsFirst`, however when we have multiple blocks to connect, we only
95         /// make a single `best_block_updated` call.
96         TransactionsFirstSkippingBlocks,
97         /// The same as `TransactionsFirst` when connecting blocks. During disconnection only
98         /// `transaction_unconfirmed` is called.
99         TransactionsFirstReorgsOnlyTip,
100         /// Provides the full block via the `chain::Listen` interface. In the current code this is
101         /// equivalent to `TransactionsFirst` with some additional assertions.
102         FullBlockViaListen,
103 }
104
105 impl ConnectStyle {
106         fn random_style() -> ConnectStyle {
107                 #[cfg(feature = "std")] {
108                         use core::hash::{BuildHasher, Hasher};
109                         // Get a random value using the only std API to do so - the DefaultHasher
110                         let rand_val = std::collections::hash_map::RandomState::new().build_hasher().finish();
111                         let res = match rand_val % 7 {
112                                 0 => ConnectStyle::BestBlockFirst,
113                                 1 => ConnectStyle::BestBlockFirstSkippingBlocks,
114                                 2 => ConnectStyle::BestBlockFirstReorgsOnlyTip,
115                                 3 => ConnectStyle::TransactionsFirst,
116                                 4 => ConnectStyle::TransactionsFirstSkippingBlocks,
117                                 5 => ConnectStyle::TransactionsFirstReorgsOnlyTip,
118                                 6 => ConnectStyle::FullBlockViaListen,
119                                 _ => unreachable!(),
120                         };
121                         eprintln!("Using Block Connection Style: {:?}", res);
122                         res
123                 }
124                 #[cfg(not(feature = "std"))] {
125                         ConnectStyle::FullBlockViaListen
126                 }
127         }
128 }
129
130 pub fn connect_blocks<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, depth: u32) -> BlockHash {
131         let skip_intermediaries = match *node.connect_style.borrow() {
132                 ConnectStyle::BestBlockFirstSkippingBlocks|ConnectStyle::TransactionsFirstSkippingBlocks|
133                         ConnectStyle::BestBlockFirstReorgsOnlyTip|ConnectStyle::TransactionsFirstReorgsOnlyTip => true,
134                 _ => false,
135         };
136
137         let height = node.best_block_info().1 + 1;
138         let mut block = Block {
139                 header: BlockHeader { version: 0x2000000, prev_blockhash: node.best_block_hash(), merkle_root: Default::default(), time: height, bits: 42, nonce: 42 },
140                 txdata: vec![],
141         };
142         assert!(depth >= 1);
143         for i in 1..depth {
144                 let prev_blockhash = block.header.block_hash();
145                 do_connect_block(node, block, skip_intermediaries);
146                 block = Block {
147                         header: BlockHeader { version: 0x20000000, prev_blockhash, merkle_root: Default::default(), time: height + i, bits: 42, nonce: 42 },
148                         txdata: vec![],
149                 };
150         }
151         let hash = block.header.block_hash();
152         do_connect_block(node, block, false);
153         hash
154 }
155
156 pub fn connect_block<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, block: &Block) {
157         do_connect_block(node, block.clone(), false);
158 }
159
160 fn call_claimable_balances<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>) {
161         // Ensure `get_claimable_balances`' self-tests never panic
162         for funding_outpoint in node.chain_monitor.chain_monitor.list_monitors() {
163                 node.chain_monitor.chain_monitor.get_monitor(funding_outpoint).unwrap().get_claimable_balances();
164         }
165 }
166
167 fn do_connect_block<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, block: Block, skip_intermediaries: bool) {
168         call_claimable_balances(node);
169         let height = node.best_block_info().1 + 1;
170         #[cfg(feature = "std")] {
171                 eprintln!("Connecting block using Block Connection Style: {:?}", *node.connect_style.borrow());
172         }
173         if !skip_intermediaries {
174                 let txdata: Vec<_> = block.txdata.iter().enumerate().collect();
175                 match *node.connect_style.borrow() {
176                         ConnectStyle::BestBlockFirst|ConnectStyle::BestBlockFirstSkippingBlocks|ConnectStyle::BestBlockFirstReorgsOnlyTip => {
177                                 node.chain_monitor.chain_monitor.best_block_updated(&block.header, height);
178                                 call_claimable_balances(node);
179                                 node.chain_monitor.chain_monitor.transactions_confirmed(&block.header, &txdata, height);
180                                 node.node.best_block_updated(&block.header, height);
181                                 node.node.transactions_confirmed(&block.header, &txdata, height);
182                         },
183                         ConnectStyle::TransactionsFirst|ConnectStyle::TransactionsFirstSkippingBlocks|ConnectStyle::TransactionsFirstReorgsOnlyTip => {
184                                 node.chain_monitor.chain_monitor.transactions_confirmed(&block.header, &txdata, height);
185                                 call_claimable_balances(node);
186                                 node.chain_monitor.chain_monitor.best_block_updated(&block.header, height);
187                                 node.node.transactions_confirmed(&block.header, &txdata, height);
188                                 node.node.best_block_updated(&block.header, height);
189                         },
190                         ConnectStyle::FullBlockViaListen => {
191                                 node.chain_monitor.chain_monitor.block_connected(&block, height);
192                                 node.node.block_connected(&block, height);
193                         }
194                 }
195         }
196         call_claimable_balances(node);
197         node.node.test_process_background_events();
198         node.blocks.lock().unwrap().push((block, height));
199 }
200
201 pub fn disconnect_blocks<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, count: u32) {
202         call_claimable_balances(node);
203         #[cfg(feature = "std")] {
204                 eprintln!("Disconnecting {} blocks using Block Connection Style: {:?}", count, *node.connect_style.borrow());
205         }
206         for i in 0..count {
207                 let orig = node.blocks.lock().unwrap().pop().unwrap();
208                 assert!(orig.1 > 0); // Cannot disconnect genesis
209                 let prev = node.blocks.lock().unwrap().last().unwrap().clone();
210
211                 match *node.connect_style.borrow() {
212                         ConnectStyle::FullBlockViaListen => {
213                                 node.chain_monitor.chain_monitor.block_disconnected(&orig.0.header, orig.1);
214                                 Listen::block_disconnected(node.node, &orig.0.header, orig.1);
215                         },
216                         ConnectStyle::BestBlockFirstSkippingBlocks|ConnectStyle::TransactionsFirstSkippingBlocks => {
217                                 if i == count - 1 {
218                                         node.chain_monitor.chain_monitor.best_block_updated(&prev.0.header, prev.1);
219                                         node.node.best_block_updated(&prev.0.header, prev.1);
220                                 }
221                         },
222                         ConnectStyle::BestBlockFirstReorgsOnlyTip|ConnectStyle::TransactionsFirstReorgsOnlyTip => {
223                                 for tx in orig.0.txdata {
224                                         node.chain_monitor.chain_monitor.transaction_unconfirmed(&tx.txid());
225                                         node.node.transaction_unconfirmed(&tx.txid());
226                                 }
227                         },
228                         _ => {
229                                 node.chain_monitor.chain_monitor.best_block_updated(&prev.0.header, prev.1);
230                                 node.node.best_block_updated(&prev.0.header, prev.1);
231                         },
232                 }
233                 call_claimable_balances(node);
234         }
235 }
236
237 pub fn disconnect_all_blocks<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>) {
238         let count = node.blocks.lock().unwrap().len() as u32 - 1;
239         disconnect_blocks(node, count);
240 }
241
242 pub struct TestChanMonCfg {
243         pub tx_broadcaster: test_utils::TestBroadcaster,
244         pub fee_estimator: test_utils::TestFeeEstimator,
245         pub chain_source: test_utils::TestChainSource,
246         pub persister: test_utils::TestPersister,
247         pub logger: test_utils::TestLogger,
248         pub keys_manager: test_utils::TestKeysInterface,
249         pub network_graph: NetworkGraph,
250 }
251
252 pub struct NodeCfg<'a> {
253         pub chain_source: &'a test_utils::TestChainSource,
254         pub tx_broadcaster: &'a test_utils::TestBroadcaster,
255         pub fee_estimator: &'a test_utils::TestFeeEstimator,
256         pub chain_monitor: test_utils::TestChainMonitor<'a>,
257         pub keys_manager: &'a test_utils::TestKeysInterface,
258         pub logger: &'a test_utils::TestLogger,
259         pub network_graph: &'a NetworkGraph,
260         pub node_seed: [u8; 32],
261         pub features: InitFeatures,
262 }
263
264 pub struct Node<'a, 'b: 'a, 'c: 'b> {
265         pub chain_source: &'c test_utils::TestChainSource,
266         pub tx_broadcaster: &'c test_utils::TestBroadcaster,
267         pub chain_monitor: &'b test_utils::TestChainMonitor<'c>,
268         pub keys_manager: &'b test_utils::TestKeysInterface,
269         pub node: &'a ChannelManager<EnforcingSigner, &'b TestChainMonitor<'c>, &'c test_utils::TestBroadcaster, &'b test_utils::TestKeysInterface, &'c test_utils::TestFeeEstimator, &'c test_utils::TestLogger>,
270         pub network_graph: &'c NetworkGraph,
271         pub net_graph_msg_handler: NetGraphMsgHandler<&'c NetworkGraph, &'c test_utils::TestChainSource, &'c test_utils::TestLogger>,
272         pub node_seed: [u8; 32],
273         pub network_payment_count: Rc<RefCell<u8>>,
274         pub network_chan_count: Rc<RefCell<u32>>,
275         pub logger: &'c test_utils::TestLogger,
276         pub blocks: Arc<Mutex<Vec<(Block, u32)>>>,
277         pub connect_style: Rc<RefCell<ConnectStyle>>,
278 }
279 impl<'a, 'b, 'c> Node<'a, 'b, 'c> {
280         pub fn best_block_hash(&self) -> BlockHash {
281                 self.blocks.lock().unwrap().last().unwrap().0.block_hash()
282         }
283         pub fn best_block_info(&self) -> (BlockHash, u32) {
284                 self.blocks.lock().unwrap().last().map(|(a, b)| (a.block_hash(), *b)).unwrap()
285         }
286         pub fn get_block_header(&self, height: u32) -> BlockHeader {
287                 self.blocks.lock().unwrap()[height as usize].0.header
288         }
289 }
290
291 impl<'a, 'b, 'c> Drop for Node<'a, 'b, 'c> {
292         fn drop(&mut self) {
293                 if !panicking() {
294                         // Check that we processed all pending events
295                         assert!(self.node.get_and_clear_pending_msg_events().is_empty());
296                         assert!(self.node.get_and_clear_pending_events().is_empty());
297                         assert!(self.chain_monitor.added_monitors.lock().unwrap().is_empty());
298
299                         // Check that if we serialize the Router, we can deserialize it again.
300                         {
301                                 let mut w = test_utils::TestVecWriter(Vec::new());
302                                 self.network_graph.write(&mut w).unwrap();
303                                 let network_graph_deser = <NetworkGraph>::read(&mut io::Cursor::new(&w.0)).unwrap();
304                                 assert!(network_graph_deser == *self.network_graph);
305                                 let net_graph_msg_handler = NetGraphMsgHandler::new(
306                                         &network_graph_deser, Some(self.chain_source), self.logger
307                                 );
308                                 let mut chan_progress = 0;
309                                 loop {
310                                         let orig_announcements = self.net_graph_msg_handler.get_next_channel_announcements(chan_progress, 255);
311                                         let deserialized_announcements = net_graph_msg_handler.get_next_channel_announcements(chan_progress, 255);
312                                         assert!(orig_announcements == deserialized_announcements);
313                                         chan_progress = match orig_announcements.last() {
314                                                 Some(announcement) => announcement.0.contents.short_channel_id + 1,
315                                                 None => break,
316                                         };
317                                 }
318                                 let mut node_progress = None;
319                                 loop {
320                                         let orig_announcements = self.net_graph_msg_handler.get_next_node_announcements(node_progress.as_ref(), 255);
321                                         let deserialized_announcements = net_graph_msg_handler.get_next_node_announcements(node_progress.as_ref(), 255);
322                                         assert!(orig_announcements == deserialized_announcements);
323                                         node_progress = match orig_announcements.last() {
324                                                 Some(announcement) => Some(announcement.contents.node_id),
325                                                 None => break,
326                                         };
327                                 }
328                         }
329
330                         // Check that if we serialize and then deserialize all our channel monitors we get the
331                         // same set of outputs to watch for on chain as we have now. Note that if we write
332                         // tests that fully close channels and remove the monitors at some point this may break.
333                         let feeest = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
334                         let mut deserialized_monitors = Vec::new();
335                         {
336                                 for outpoint in self.chain_monitor.chain_monitor.list_monitors() {
337                                         let mut w = test_utils::TestVecWriter(Vec::new());
338                                         self.chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut w).unwrap();
339                                         let (_, deserialized_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
340                                                 &mut io::Cursor::new(&w.0), self.keys_manager).unwrap();
341                                         deserialized_monitors.push(deserialized_monitor);
342                                 }
343                         }
344
345                         // Before using all the new monitors to check the watch outpoints, use the full set of
346                         // them to ensure we can write and reload our ChannelManager.
347                         {
348                                 let mut channel_monitors = HashMap::new();
349                                 for monitor in deserialized_monitors.iter_mut() {
350                                         channel_monitors.insert(monitor.get_funding_txo().0, monitor);
351                                 }
352
353                                 let mut w = test_utils::TestVecWriter(Vec::new());
354                                 self.node.write(&mut w).unwrap();
355                                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut io::Cursor::new(w.0), ChannelManagerReadArgs {
356                                         default_config: *self.node.get_current_default_configuration(),
357                                         keys_manager: self.keys_manager,
358                                         fee_estimator: &test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
359                                         chain_monitor: self.chain_monitor,
360                                         tx_broadcaster: &test_utils::TestBroadcaster {
361                                                 txn_broadcasted: Mutex::new(self.tx_broadcaster.txn_broadcasted.lock().unwrap().clone()),
362                                                 blocks: Arc::new(Mutex::new(self.tx_broadcaster.blocks.lock().unwrap().clone())),
363                                         },
364                                         logger: &self.logger,
365                                         channel_monitors,
366                                 }).unwrap();
367                         }
368
369                         let persister = test_utils::TestPersister::new();
370                         let broadcaster = test_utils::TestBroadcaster {
371                                 txn_broadcasted: Mutex::new(self.tx_broadcaster.txn_broadcasted.lock().unwrap().clone()),
372                                 blocks: Arc::new(Mutex::new(self.tx_broadcaster.blocks.lock().unwrap().clone())),
373                         };
374                         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
375                         let chain_monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &broadcaster, &self.logger, &feeest, &persister, &self.keys_manager);
376                         for deserialized_monitor in deserialized_monitors.drain(..) {
377                                 if let Err(_) = chain_monitor.watch_channel(deserialized_monitor.get_funding_txo().0, deserialized_monitor) {
378                                         panic!();
379                                 }
380                         }
381                         assert_eq!(*chain_source.watched_txn.lock().unwrap(), *self.chain_source.watched_txn.lock().unwrap());
382                         assert_eq!(*chain_source.watched_outputs.lock().unwrap(), *self.chain_source.watched_outputs.lock().unwrap());
383                 }
384         }
385 }
386
387 pub fn create_chan_between_nodes<'a, 'b, 'c, 'd>(node_a: &'a Node<'b, 'c, 'd>, node_b: &'a Node<'b, 'c, 'd>, a_flags: InitFeatures, b_flags: InitFeatures) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
388         create_chan_between_nodes_with_value(node_a, node_b, 100000, 10001, a_flags, b_flags)
389 }
390
391 pub fn create_chan_between_nodes_with_value<'a, 'b, 'c, 'd>(node_a: &'a Node<'b, 'c, 'd>, node_b: &'a Node<'b, 'c, 'd>, channel_value: u64, push_msat: u64, a_flags: InitFeatures, b_flags: InitFeatures) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
392         let (funding_locked, channel_id, tx) = create_chan_between_nodes_with_value_a(node_a, node_b, channel_value, push_msat, a_flags, b_flags);
393         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(node_a, node_b, &funding_locked);
394         (announcement, as_update, bs_update, channel_id, tx)
395 }
396
397 #[macro_export]
398 /// Gets an RAA and CS which were sent in response to a commitment update
399 macro_rules! get_revoke_commit_msgs {
400         ($node: expr, $node_id: expr) => {
401                 {
402                         use $crate::util::events::MessageSendEvent;
403                         let events = $node.node.get_and_clear_pending_msg_events();
404                         assert_eq!(events.len(), 2);
405                         (match events[0] {
406                                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
407                                         assert_eq!(*node_id, $node_id);
408                                         (*msg).clone()
409                                 },
410                                 _ => panic!("Unexpected event"),
411                         }, match events[1] {
412                                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
413                                         assert_eq!(*node_id, $node_id);
414                                         assert!(updates.update_add_htlcs.is_empty());
415                                         assert!(updates.update_fulfill_htlcs.is_empty());
416                                         assert!(updates.update_fail_htlcs.is_empty());
417                                         assert!(updates.update_fail_malformed_htlcs.is_empty());
418                                         assert!(updates.update_fee.is_none());
419                                         updates.commitment_signed.clone()
420                                 },
421                                 _ => panic!("Unexpected event"),
422                         })
423                 }
424         }
425 }
426
427 /// Get an specific event message from the pending events queue.
428 #[macro_export]
429 macro_rules! get_event_msg {
430         ($node: expr, $event_type: path, $node_id: expr) => {
431                 {
432                         let events = $node.node.get_and_clear_pending_msg_events();
433                         assert_eq!(events.len(), 1);
434                         match events[0] {
435                                 $event_type { ref node_id, ref msg } => {
436                                         assert_eq!(*node_id, $node_id);
437                                         (*msg).clone()
438                                 },
439                                 _ => panic!("Unexpected event"),
440                         }
441                 }
442         }
443 }
444
445 /// Get an error message from the pending events queue.
446 #[macro_export]
447 macro_rules! get_err_msg {
448         ($node: expr, $node_id: expr) => {
449                 {
450                         let events = $node.node.get_and_clear_pending_msg_events();
451                         assert_eq!(events.len(), 1);
452                         match events[0] {
453                                 $crate::util::events::MessageSendEvent::HandleError {
454                                         action: $crate::ln::msgs::ErrorAction::SendErrorMessage { ref msg }, ref node_id
455                                 } => {
456                                         assert_eq!(*node_id, $node_id);
457                                         (*msg).clone()
458                                 },
459                                 _ => panic!("Unexpected event"),
460                         }
461                 }
462         }
463 }
464
465 /// Get a specific event from the pending events queue.
466 #[macro_export]
467 macro_rules! get_event {
468         ($node: expr, $event_type: path) => {
469                 {
470                         let mut events = $node.node.get_and_clear_pending_events();
471                         assert_eq!(events.len(), 1);
472                         let ev = events.pop().unwrap();
473                         match ev {
474                                 $event_type { .. } => {
475                                         ev
476                                 },
477                                 _ => panic!("Unexpected event"),
478                         }
479                 }
480         }
481 }
482
483 #[macro_export]
484 /// Gets an UpdateHTLCs MessageSendEvent
485 macro_rules! get_htlc_update_msgs {
486         ($node: expr, $node_id: expr) => {
487                 {
488                         let events = $node.node.get_and_clear_pending_msg_events();
489                         assert_eq!(events.len(), 1);
490                         match events[0] {
491                                 $crate::util::events::MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
492                                         assert_eq!(*node_id, $node_id);
493                                         (*updates).clone()
494                                 },
495                                 _ => panic!("Unexpected event"),
496                         }
497                 }
498         }
499 }
500
501 #[cfg(test)]
502 macro_rules! get_channel_ref {
503         ($node: expr, $lock: ident, $channel_id: expr) => {
504                 {
505                         $lock = $node.node.channel_state.lock().unwrap();
506                         $lock.by_id.get_mut(&$channel_id).unwrap()
507                 }
508         }
509 }
510
511 #[cfg(test)]
512 macro_rules! get_feerate {
513         ($node: expr, $channel_id: expr) => {
514                 {
515                         let mut lock;
516                         let chan = get_channel_ref!($node, lock, $channel_id);
517                         chan.get_feerate()
518                 }
519         }
520 }
521
522 #[cfg(test)]
523 macro_rules! get_opt_anchors {
524         ($node: expr, $channel_id: expr) => {
525                 {
526                         let mut lock;
527                         let chan = get_channel_ref!($node, lock, $channel_id);
528                         chan.opt_anchors()
529                 }
530         }
531 }
532
533 /// Returns a channel monitor given a channel id, making some naive assumptions
534 #[macro_export]
535 macro_rules! get_monitor {
536         ($node: expr, $channel_id: expr) => {
537                 {
538                         use bitcoin::hashes::Hash;
539                         let mut monitor = None;
540                         // Assume funding vout is either 0 or 1 blindly
541                         for index in 0..2 {
542                                 if let Ok(mon) = $node.chain_monitor.chain_monitor.get_monitor(
543                                         $crate::chain::transaction::OutPoint {
544                                                 txid: bitcoin::Txid::from_slice(&$channel_id[..]).unwrap(), index
545                                         })
546                                 {
547                                         monitor = Some(mon);
548                                         break;
549                                 }
550                         }
551                         monitor.unwrap()
552                 }
553         }
554 }
555
556 /// Returns any local commitment transactions for the channel.
557 #[macro_export]
558 macro_rules! get_local_commitment_txn {
559         ($node: expr, $channel_id: expr) => {
560                 {
561                         $crate::get_monitor!($node, $channel_id).unsafe_get_latest_holder_commitment_txn(&$node.logger)
562                 }
563         }
564 }
565
566 /// Check the error from attempting a payment.
567 #[macro_export]
568 macro_rules! unwrap_send_err {
569         ($res: expr, $all_failed: expr, $type: pat, $check: expr) => {
570                 match &$res {
571                         &Err(PaymentSendFailure::AllFailedRetrySafe(ref fails)) if $all_failed => {
572                                 assert_eq!(fails.len(), 1);
573                                 match fails[0] {
574                                         $type => { $check },
575                                         _ => panic!(),
576                                 }
577                         },
578                         &Err(PaymentSendFailure::PartialFailure { ref results, .. }) if !$all_failed => {
579                                 assert_eq!(results.len(), 1);
580                                 match results[0] {
581                                         Err($type) => { $check },
582                                         _ => panic!(),
583                                 }
584                         },
585                         _ => panic!(),
586                 }
587         }
588 }
589
590 /// Check whether N channel monitor(s) have been added.
591 #[macro_export]
592 macro_rules! check_added_monitors {
593         ($node: expr, $count: expr) => {
594                 {
595                         let mut added_monitors = $node.chain_monitor.added_monitors.lock().unwrap();
596                         assert_eq!(added_monitors.len(), $count);
597                         added_monitors.clear();
598                 }
599         }
600 }
601
602 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: u64) -> ([u8; 32], Transaction, OutPoint) {
603         let chan_id = *node.network_chan_count.borrow();
604
605         let events = node.node.get_and_clear_pending_events();
606         assert_eq!(events.len(), 1);
607         match events[0] {
608                 Event::FundingGenerationReady { ref temporary_channel_id, ref counterparty_node_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
609                         assert_eq!(counterparty_node_id, expected_counterparty_node_id);
610                         assert_eq!(*channel_value_satoshis, expected_chan_value);
611                         assert_eq!(user_channel_id, expected_user_chan_id);
612
613                         let tx = Transaction { version: chan_id as i32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
614                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
615                         }]};
616                         let funding_outpoint = OutPoint { txid: tx.txid(), index: 0 };
617                         (*temporary_channel_id, tx, funding_outpoint)
618                 },
619                 _ => panic!("Unexpected event"),
620         }
621 }
622 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 {
623         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(node_a, &node_b.node.get_our_node_id(), channel_value, 42);
624         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
625
626         assert!(node_a.node.funding_transaction_generated(&temporary_channel_id, &node_b.node.get_our_node_id(), tx.clone()).is_ok());
627         check_added_monitors!(node_a, 0);
628
629         let funding_created_msg = get_event_msg!(node_a, MessageSendEvent::SendFundingCreated, node_b.node.get_our_node_id());
630         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
631         node_b.node.handle_funding_created(&node_a.node.get_our_node_id(), &funding_created_msg);
632         {
633                 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
634                 assert_eq!(added_monitors.len(), 1);
635                 assert_eq!(added_monitors[0].0, funding_output);
636                 added_monitors.clear();
637         }
638
639         node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id()));
640         {
641                 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
642                 assert_eq!(added_monitors.len(), 1);
643                 assert_eq!(added_monitors[0].0, funding_output);
644                 added_monitors.clear();
645         }
646
647         let events_4 = node_a.node.get_and_clear_pending_events();
648         assert_eq!(events_4.len(), 0);
649
650         assert_eq!(node_a.tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
651         assert_eq!(node_a.tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
652         node_a.tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
653
654         // Ensure that funding_transaction_generated is idempotent.
655         assert!(node_a.node.funding_transaction_generated(&temporary_channel_id, &node_b.node.get_our_node_id(), tx.clone()).is_err());
656         assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
657         check_added_monitors!(node_a, 0);
658
659         tx
660 }
661
662 pub fn create_chan_between_nodes_with_value_init<'a, 'b, 'c>(node_a: &Node<'a, 'b, 'c>, node_b: &Node<'a, 'b, 'c>, channel_value: u64, push_msat: u64, a_flags: InitFeatures, b_flags: InitFeatures) -> Transaction {
663         let create_chan_id = node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
664         let open_channel_msg = get_event_msg!(node_a, MessageSendEvent::SendOpenChannel, node_b.node.get_our_node_id());
665         assert_eq!(open_channel_msg.temporary_channel_id, create_chan_id);
666         node_b.node.handle_open_channel(&node_a.node.get_our_node_id(), a_flags, &open_channel_msg);
667         let accept_channel_msg = get_event_msg!(node_b, MessageSendEvent::SendAcceptChannel, node_a.node.get_our_node_id());
668         assert_eq!(accept_channel_msg.temporary_channel_id, create_chan_id);
669         node_a.node.handle_accept_channel(&node_b.node.get_our_node_id(), b_flags, &accept_channel_msg);
670
671         sign_funding_transaction(node_a, node_b, channel_value, create_chan_id)
672 }
673
674 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) {
675         confirm_transaction_at(node_conf, tx, conf_height);
676         connect_blocks(node_conf, CHAN_CONFIRM_DEPTH - 1);
677         node_recv.node.handle_funding_locked(&node_conf.node.get_our_node_id(), &get_event_msg!(node_conf, MessageSendEvent::SendFundingLocked, node_recv.node.get_our_node_id()));
678 }
679
680 pub fn create_chan_between_nodes_with_value_confirm_second<'a, 'b, 'c>(node_recv: &Node<'a, 'b, 'c>, node_conf: &Node<'a, 'b, 'c>) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32]) {
681         let channel_id;
682         let events_6 = node_conf.node.get_and_clear_pending_msg_events();
683         assert_eq!(events_6.len(), 3);
684         let announcement_sigs_idx = if let MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } = events_6[1] {
685                 assert_eq!(*node_id, node_recv.node.get_our_node_id());
686                 2
687         } else if let MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } = events_6[2] {
688                 assert_eq!(*node_id, node_recv.node.get_our_node_id());
689                 1
690         } else { panic!("Unexpected event: {:?}", events_6[1]); };
691         ((match events_6[0] {
692                 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
693                         channel_id = msg.channel_id.clone();
694                         assert_eq!(*node_id, node_recv.node.get_our_node_id());
695                         msg.clone()
696                 },
697                 _ => panic!("Unexpected event"),
698         }, match events_6[announcement_sigs_idx] {
699                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
700                         assert_eq!(*node_id, node_recv.node.get_our_node_id());
701                         msg.clone()
702                 },
703                 _ => panic!("Unexpected event"),
704         }), channel_id)
705 }
706
707 pub fn create_chan_between_nodes_with_value_confirm<'a, 'b, 'c, 'd>(node_a: &'a Node<'b, 'c, 'd>, node_b: &'a Node<'b, 'c, 'd>, tx: &Transaction) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32]) {
708         let conf_height = core::cmp::max(node_a.best_block_info().1 + 1, node_b.best_block_info().1 + 1);
709         create_chan_between_nodes_with_value_confirm_first(node_a, node_b, tx, conf_height);
710         confirm_transaction_at(node_a, tx, conf_height);
711         connect_blocks(node_a, CHAN_CONFIRM_DEPTH - 1);
712         create_chan_between_nodes_with_value_confirm_second(node_b, node_a)
713 }
714
715 pub fn create_chan_between_nodes_with_value_a<'a, 'b, 'c, 'd>(node_a: &'a Node<'b, 'c, 'd>, node_b: &'a Node<'b, 'c, 'd>, channel_value: u64, push_msat: u64, a_flags: InitFeatures, b_flags: InitFeatures) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32], Transaction) {
716         let tx = create_chan_between_nodes_with_value_init(node_a, node_b, channel_value, push_msat, a_flags, b_flags);
717         let (msgs, chan_id) = create_chan_between_nodes_with_value_confirm(node_a, node_b, &tx);
718         (msgs, chan_id, tx)
719 }
720
721 pub fn create_chan_between_nodes_with_value_b<'a, 'b, 'c>(node_a: &Node<'a, 'b, 'c>, node_b: &Node<'a, 'b, 'c>, as_funding_msgs: &(msgs::FundingLocked, msgs::AnnouncementSignatures)) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate) {
722         node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &as_funding_msgs.0);
723         let bs_announcement_sigs = get_event_msg!(node_b, MessageSendEvent::SendAnnouncementSignatures, node_a.node.get_our_node_id());
724         node_b.node.handle_announcement_signatures(&node_a.node.get_our_node_id(), &as_funding_msgs.1);
725
726         let events_7 = node_b.node.get_and_clear_pending_msg_events();
727         assert_eq!(events_7.len(), 1);
728         let (announcement, bs_update) = match events_7[0] {
729                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
730                         (msg, update_msg)
731                 },
732                 _ => panic!("Unexpected event"),
733         };
734
735         node_a.node.handle_announcement_signatures(&node_b.node.get_our_node_id(), &bs_announcement_sigs);
736         let events_8 = node_a.node.get_and_clear_pending_msg_events();
737         assert_eq!(events_8.len(), 1);
738         let as_update = match events_8[0] {
739                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
740                         assert!(*announcement == *msg);
741                         assert_eq!(update_msg.contents.short_channel_id, announcement.contents.short_channel_id);
742                         assert_eq!(update_msg.contents.short_channel_id, bs_update.contents.short_channel_id);
743                         update_msg
744                 },
745                 _ => panic!("Unexpected event"),
746         };
747
748         *node_a.network_chan_count.borrow_mut() += 1;
749
750         ((*announcement).clone(), (*as_update).clone(), (*bs_update).clone())
751 }
752
753 pub fn create_announced_chan_between_nodes<'a, 'b, 'c, 'd>(nodes: &'a Vec<Node<'b, 'c, 'd>>, a: usize, b: usize, a_flags: InitFeatures, b_flags: InitFeatures) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
754         create_announced_chan_between_nodes_with_value(nodes, a, b, 100000, 10001, a_flags, b_flags)
755 }
756
757 pub fn create_announced_chan_between_nodes_with_value<'a, 'b, 'c, 'd>(nodes: &'a Vec<Node<'b, 'c, 'd>>, a: usize, b: usize, channel_value: u64, push_msat: u64, a_flags: InitFeatures, b_flags: InitFeatures) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
758         let chan_announcement = create_chan_between_nodes_with_value(&nodes[a], &nodes[b], channel_value, push_msat, a_flags, b_flags);
759         update_nodes_with_chan_announce(nodes, a, b, &chan_announcement.0, &chan_announcement.1, &chan_announcement.2);
760         (chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
761 }
762
763 pub fn create_unannounced_chan_between_nodes_with_value<'a, 'b, 'c, 'd>(nodes: &'a Vec<Node<'b, 'c, 'd>>, a: usize, b: usize, channel_value: u64, push_msat: u64, a_flags: InitFeatures, b_flags: InitFeatures) -> (msgs::FundingLocked, Transaction) {
764         let mut no_announce_cfg = test_default_channel_config();
765         no_announce_cfg.channel_options.announced_channel = false;
766         nodes[a].node.create_channel(nodes[b].node.get_our_node_id(), channel_value, push_msat, 42, Some(no_announce_cfg)).unwrap();
767         let open_channel = get_event_msg!(nodes[a], MessageSendEvent::SendOpenChannel, nodes[b].node.get_our_node_id());
768         nodes[b].node.handle_open_channel(&nodes[a].node.get_our_node_id(), a_flags, &open_channel);
769         let accept_channel = get_event_msg!(nodes[b], MessageSendEvent::SendAcceptChannel, nodes[a].node.get_our_node_id());
770         nodes[a].node.handle_accept_channel(&nodes[b].node.get_our_node_id(), b_flags, &accept_channel);
771
772         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[a], &nodes[b].node.get_our_node_id(), channel_value, 42);
773         nodes[a].node.funding_transaction_generated(&temporary_channel_id, &nodes[b].node.get_our_node_id(), tx.clone()).unwrap();
774         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()));
775         check_added_monitors!(nodes[b], 1);
776
777         let cs_funding_signed = get_event_msg!(nodes[b], MessageSendEvent::SendFundingSigned, nodes[a].node.get_our_node_id());
778         nodes[a].node.handle_funding_signed(&nodes[b].node.get_our_node_id(), &cs_funding_signed);
779         check_added_monitors!(nodes[a], 1);
780
781         let conf_height = core::cmp::max(nodes[a].best_block_info().1 + 1, nodes[b].best_block_info().1 + 1);
782         confirm_transaction_at(&nodes[a], &tx, conf_height);
783         connect_blocks(&nodes[a], CHAN_CONFIRM_DEPTH - 1);
784         confirm_transaction_at(&nodes[b], &tx, conf_height);
785         connect_blocks(&nodes[b], CHAN_CONFIRM_DEPTH - 1);
786         let as_funding_locked = get_event_msg!(nodes[a], MessageSendEvent::SendFundingLocked, nodes[b].node.get_our_node_id());
787         nodes[a].node.handle_funding_locked(&nodes[b].node.get_our_node_id(), &get_event_msg!(nodes[b], MessageSendEvent::SendFundingLocked, nodes[a].node.get_our_node_id()));
788         let as_update = get_event_msg!(nodes[a], MessageSendEvent::SendChannelUpdate, nodes[b].node.get_our_node_id());
789         nodes[b].node.handle_funding_locked(&nodes[a].node.get_our_node_id(), &as_funding_locked);
790         let bs_update = get_event_msg!(nodes[b], MessageSendEvent::SendChannelUpdate, nodes[a].node.get_our_node_id());
791
792         nodes[a].node.handle_channel_update(&nodes[b].node.get_our_node_id(), &bs_update);
793         nodes[b].node.handle_channel_update(&nodes[a].node.get_our_node_id(), &as_update);
794
795         let mut found_a = false;
796         for chan in nodes[a].node.list_usable_channels() {
797                 if chan.channel_id == as_funding_locked.channel_id {
798                         assert!(!found_a);
799                         found_a = true;
800                         assert!(!chan.is_public);
801                 }
802         }
803         assert!(found_a);
804
805         let mut found_b = false;
806         for chan in nodes[b].node.list_usable_channels() {
807                 if chan.channel_id == as_funding_locked.channel_id {
808                         assert!(!found_b);
809                         found_b = true;
810                         assert!(!chan.is_public);
811                 }
812         }
813         assert!(found_b);
814
815         (as_funding_locked, tx)
816 }
817
818 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) {
819         nodes[a].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
820         let a_events = nodes[a].node.get_and_clear_pending_msg_events();
821         assert!(a_events.len() >= 2);
822
823         // ann should be re-generated by broadcast_node_announcement - check that we have it.
824         let mut found_ann_1 = false;
825         for event in a_events.iter() {
826                 match event {
827                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
828                                 if msg == ann { found_ann_1 = true; }
829                         },
830                         MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
831                         _ => panic!("Unexpected event {:?}", event),
832                 }
833         }
834         assert!(found_ann_1);
835
836         let a_node_announcement = match a_events.last().unwrap() {
837                 MessageSendEvent::BroadcastNodeAnnouncement { ref msg } => {
838                         (*msg).clone()
839                 },
840                 _ => panic!("Unexpected event"),
841         };
842
843         nodes[b].node.broadcast_node_announcement([1, 1, 1], [1; 32], Vec::new());
844         let b_events = nodes[b].node.get_and_clear_pending_msg_events();
845         assert!(b_events.len() >= 2);
846
847         // ann should be re-generated by broadcast_node_announcement - check that we have it.
848         let mut found_ann_2 = false;
849         for event in b_events.iter() {
850                 match event {
851                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
852                                 if msg == ann { found_ann_2 = true; }
853                         },
854                         MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
855                         _ => panic!("Unexpected event"),
856                 }
857         }
858         assert!(found_ann_2);
859
860         let b_node_announcement = match b_events.last().unwrap() {
861                 MessageSendEvent::BroadcastNodeAnnouncement { ref msg } => {
862                         (*msg).clone()
863                 },
864                 _ => panic!("Unexpected event"),
865         };
866
867         for node in nodes {
868                 assert!(node.net_graph_msg_handler.handle_channel_announcement(ann).unwrap());
869                 node.net_graph_msg_handler.handle_channel_update(upd_1).unwrap();
870                 node.net_graph_msg_handler.handle_channel_update(upd_2).unwrap();
871                 node.net_graph_msg_handler.handle_node_announcement(&a_node_announcement).unwrap();
872                 node.net_graph_msg_handler.handle_node_announcement(&b_node_announcement).unwrap();
873
874                 // Note that channel_updates are also delivered to ChannelManagers to ensure we have
875                 // forwarding info for local channels even if its not accepted in the network graph.
876                 node.node.handle_channel_update(&nodes[a].node.get_our_node_id(), &upd_1);
877                 node.node.handle_channel_update(&nodes[b].node.get_our_node_id(), &upd_2);
878         }
879 }
880
881 #[macro_export]
882 macro_rules! check_spends {
883         ($tx: expr, $($spends_txn: expr),*) => {
884                 {
885                         $(
886                         for outp in $spends_txn.output.iter() {
887                                 assert!(outp.value >= outp.script_pubkey.dust_value().as_sat(), "Input tx output didn't meet dust limit");
888                         }
889                         )*
890                         for outp in $tx.output.iter() {
891                                 assert!(outp.value >= outp.script_pubkey.dust_value().as_sat(), "Spending tx output didn't meet dust limit");
892                         }
893                         let get_output = |out_point: &bitcoin::blockdata::transaction::OutPoint| {
894                                 $(
895                                         if out_point.txid == $spends_txn.txid() {
896                                                 return $spends_txn.output.get(out_point.vout as usize).cloned()
897                                         }
898                                 )*
899                                 None
900                         };
901                         let mut total_value_in = 0;
902                         for input in $tx.input.iter() {
903                                 total_value_in += get_output(&input.previous_output).unwrap().value;
904                         }
905                         let mut total_value_out = 0;
906                         for output in $tx.output.iter() {
907                                 total_value_out += output.value;
908                         }
909                         let min_fee = ($tx.weight() as u64 + 3) / 4; // One sat per vbyte (ie per weight/4, rounded up)
910                         // Input amount - output amount = fee, so check that out + min_fee is smaller than input
911                         assert!(total_value_out + min_fee <= total_value_in);
912                         $tx.verify(get_output).unwrap();
913                 }
914         }
915 }
916
917 macro_rules! get_closing_signed_broadcast {
918         ($node: expr, $dest_pubkey: expr) => {
919                 {
920                         let events = $node.get_and_clear_pending_msg_events();
921                         assert!(events.len() == 1 || events.len() == 2);
922                         (match events[events.len() - 1] {
923                                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
924                                         assert_eq!(msg.contents.flags & 2, 2);
925                                         msg.clone()
926                                 },
927                                 _ => panic!("Unexpected event"),
928                         }, if events.len() == 2 {
929                                 match events[0] {
930                                         MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
931                                                 assert_eq!(*node_id, $dest_pubkey);
932                                                 Some(msg.clone())
933                                         },
934                                         _ => panic!("Unexpected event"),
935                                 }
936                         } else { None })
937                 }
938         }
939 }
940
941 #[cfg(test)]
942 macro_rules! check_warn_msg {
943         ($node: expr, $recipient_node_id: expr, $chan_id: expr) => {{
944                 let msg_events = $node.node.get_and_clear_pending_msg_events();
945                 assert_eq!(msg_events.len(), 1);
946                 match msg_events[0] {
947                         MessageSendEvent::HandleError { action: ErrorAction::SendWarningMessage { ref msg, log_level: _ }, node_id } => {
948                                 assert_eq!(node_id, $recipient_node_id);
949                                 assert_eq!(msg.channel_id, $chan_id);
950                                 msg.data.clone()
951                         },
952                         _ => panic!("Unexpected event"),
953                 }
954         }}
955 }
956
957 /// Check that a channel's closing channel update has been broadcasted, and optionally
958 /// check whether an error message event has occurred.
959 #[macro_export]
960 macro_rules! check_closed_broadcast {
961         ($node: expr, $with_error_msg: expr) => {{
962                 use $crate::util::events::MessageSendEvent;
963                 use $crate::ln::msgs::ErrorAction;
964
965                 let msg_events = $node.node.get_and_clear_pending_msg_events();
966                 assert_eq!(msg_events.len(), if $with_error_msg { 2 } else { 1 });
967                 match msg_events[0] {
968                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
969                                 assert_eq!(msg.contents.flags & 2, 2);
970                         },
971                         _ => panic!("Unexpected event"),
972                 }
973                 if $with_error_msg {
974                         match msg_events[1] {
975                                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
976                                         // TODO: Check node_id
977                                         Some(msg.clone())
978                                 },
979                                 _ => panic!("Unexpected event"),
980                         }
981                 } else { None }
982         }}
983 }
984
985 /// Check that a channel's closing channel events has been issued
986 #[macro_export]
987 macro_rules! check_closed_event {
988         ($node: expr, $events: expr, $reason: expr) => {
989                 check_closed_event!($node, $events, $reason, false);
990         };
991         ($node: expr, $events: expr, $reason: expr, $is_check_discard_funding: expr) => {{
992                 use $crate::util::events::Event;
993
994                 let events = $node.node.get_and_clear_pending_events();
995                 assert_eq!(events.len(), $events);
996                 let expected_reason = $reason;
997                 let mut issues_discard_funding = false;
998                 for event in events {
999                         match event {
1000                                 Event::ChannelClosed { ref reason, .. } => {
1001                                         assert_eq!(*reason, expected_reason);
1002                                 },
1003                                 Event::DiscardFunding { .. } => {
1004                                         issues_discard_funding = true;
1005                                 }
1006                                 _ => panic!("Unexpected event"),
1007                         }
1008                 }
1009                 assert_eq!($is_check_discard_funding, issues_discard_funding);
1010         }}
1011 }
1012
1013 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) {
1014         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) };
1015         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) };
1016         let (tx_a, tx_b);
1017
1018         node_a.close_channel(channel_id, &node_b.get_our_node_id()).unwrap();
1019         node_b.handle_shutdown(&node_a.get_our_node_id(), &InitFeatures::known(), &get_event_msg!(struct_a, MessageSendEvent::SendShutdown, node_b.get_our_node_id()));
1020
1021         let events_1 = node_b.get_and_clear_pending_msg_events();
1022         assert!(events_1.len() >= 1);
1023         let shutdown_b = match events_1[0] {
1024                 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
1025                         assert_eq!(node_id, &node_a.get_our_node_id());
1026                         msg.clone()
1027                 },
1028                 _ => panic!("Unexpected event"),
1029         };
1030
1031         let closing_signed_b = if !close_inbound_first {
1032                 assert_eq!(events_1.len(), 1);
1033                 None
1034         } else {
1035                 Some(match events_1[1] {
1036                         MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
1037                                 assert_eq!(node_id, &node_a.get_our_node_id());
1038                                 msg.clone()
1039                         },
1040                         _ => panic!("Unexpected event"),
1041                 })
1042         };
1043
1044         node_a.handle_shutdown(&node_b.get_our_node_id(), &InitFeatures::known(), &shutdown_b);
1045         let (as_update, bs_update) = if close_inbound_first {
1046                 assert!(node_a.get_and_clear_pending_msg_events().is_empty());
1047                 node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap());
1048
1049                 node_b.handle_closing_signed(&node_a.get_our_node_id(), &get_event_msg!(struct_a, MessageSendEvent::SendClosingSigned, node_b.get_our_node_id()));
1050                 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
1051                 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
1052                 let (bs_update, closing_signed_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
1053
1054                 node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap());
1055                 let (as_update, none_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
1056                 assert!(none_a.is_none());
1057                 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
1058                 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
1059                 (as_update, bs_update)
1060         } else {
1061                 let closing_signed_a = get_event_msg!(struct_a, MessageSendEvent::SendClosingSigned, node_b.get_our_node_id());
1062
1063                 node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a);
1064                 node_a.handle_closing_signed(&node_b.get_our_node_id(), &get_event_msg!(struct_b, MessageSendEvent::SendClosingSigned, node_a.get_our_node_id()));
1065
1066                 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
1067                 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
1068                 let (as_update, closing_signed_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
1069
1070                 node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap());
1071                 let (bs_update, none_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
1072                 assert!(none_b.is_none());
1073                 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
1074                 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
1075                 (as_update, bs_update)
1076         };
1077         assert_eq!(tx_a, tx_b);
1078         check_spends!(tx_a, funding_tx);
1079
1080         (as_update, bs_update, tx_a)
1081 }
1082
1083 pub struct SendEvent {
1084         pub node_id: PublicKey,
1085         pub msgs: Vec<msgs::UpdateAddHTLC>,
1086         pub commitment_msg: msgs::CommitmentSigned,
1087 }
1088 impl SendEvent {
1089         pub fn from_commitment_update(node_id: PublicKey, updates: msgs::CommitmentUpdate) -> SendEvent {
1090                 assert!(updates.update_fulfill_htlcs.is_empty());
1091                 assert!(updates.update_fail_htlcs.is_empty());
1092                 assert!(updates.update_fail_malformed_htlcs.is_empty());
1093                 assert!(updates.update_fee.is_none());
1094                 SendEvent { node_id: node_id, msgs: updates.update_add_htlcs, commitment_msg: updates.commitment_signed }
1095         }
1096
1097         pub fn from_event(event: MessageSendEvent) -> SendEvent {
1098                 match event {
1099                         MessageSendEvent::UpdateHTLCs { node_id, updates } => SendEvent::from_commitment_update(node_id, updates),
1100                         _ => panic!("Unexpected event type!"),
1101                 }
1102         }
1103
1104         pub fn from_node<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>) -> SendEvent {
1105                 let mut events = node.node.get_and_clear_pending_msg_events();
1106                 assert_eq!(events.len(), 1);
1107                 SendEvent::from_event(events.pop().unwrap())
1108         }
1109 }
1110
1111 #[macro_export]
1112 /// Performs the "commitment signed dance" - the series of message exchanges which occur after a
1113 /// commitment update.
1114 macro_rules! commitment_signed_dance {
1115         ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */) => {
1116                 {
1117                         check_added_monitors!($node_a, 0);
1118                         assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
1119                         $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed);
1120                         check_added_monitors!($node_a, 1);
1121                         commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, false);
1122                 }
1123         };
1124         ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */, true /* return last RAA */) => {
1125                 {
1126                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!($node_a, $node_b.node.get_our_node_id());
1127                         check_added_monitors!($node_b, 0);
1128                         assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
1129                         $node_b.node.handle_revoke_and_ack(&$node_a.node.get_our_node_id(), &as_revoke_and_ack);
1130                         assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
1131                         check_added_monitors!($node_b, 1);
1132                         $node_b.node.handle_commitment_signed(&$node_a.node.get_our_node_id(), &as_commitment_signed);
1133                         let (bs_revoke_and_ack, extra_msg_option) = {
1134                                 let events = $node_b.node.get_and_clear_pending_msg_events();
1135                                 assert!(events.len() <= 2);
1136                                 (match events[0] {
1137                                         MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
1138                                                 assert_eq!(*node_id, $node_a.node.get_our_node_id());
1139                                                 (*msg).clone()
1140                                         },
1141                                         _ => panic!("Unexpected event"),
1142                                 }, events.get(1).map(|e| e.clone()))
1143                         };
1144                         check_added_monitors!($node_b, 1);
1145                         if $fail_backwards {
1146                                 assert!($node_a.node.get_and_clear_pending_events().is_empty());
1147                                 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
1148                         }
1149                         (extra_msg_option, bs_revoke_and_ack)
1150                 }
1151         };
1152         ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */, false /* return extra message */, true /* return last RAA */) => {
1153                 {
1154                         check_added_monitors!($node_a, 0);
1155                         assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
1156                         $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed);
1157                         check_added_monitors!($node_a, 1);
1158                         let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
1159                         assert!(extra_msg_option.is_none());
1160                         bs_revoke_and_ack
1161                 }
1162         };
1163         ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */) => {
1164                 {
1165                         let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
1166                         $node_a.node.handle_revoke_and_ack(&$node_b.node.get_our_node_id(), &bs_revoke_and_ack);
1167                         check_added_monitors!($node_a, 1);
1168                         extra_msg_option
1169                 }
1170         };
1171         ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, false /* no extra message */) => {
1172                 {
1173                         assert!(commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true).is_none());
1174                 }
1175         };
1176         ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr) => {
1177                 {
1178                         commitment_signed_dance!($node_a, $node_b, $commitment_signed, $fail_backwards, true);
1179                         if $fail_backwards {
1180                                 $crate::expect_pending_htlcs_forwardable!($node_a);
1181                                 check_added_monitors!($node_a, 1);
1182
1183                                 let channel_state = $node_a.node.channel_state.lock().unwrap();
1184                                 assert_eq!(channel_state.pending_msg_events.len(), 1);
1185                                 if let MessageSendEvent::UpdateHTLCs { ref node_id, .. } = channel_state.pending_msg_events[0] {
1186                                         assert_ne!(*node_id, $node_b.node.get_our_node_id());
1187                                 } else { panic!("Unexpected event"); }
1188                         } else {
1189                                 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
1190                         }
1191                 }
1192         }
1193 }
1194
1195 /// Get a payment preimage and hash.
1196 #[macro_export]
1197 macro_rules! get_payment_preimage_hash {
1198         ($dest_node: expr) => {
1199                 {
1200                         get_payment_preimage_hash!($dest_node, None)
1201                 }
1202         };
1203         ($dest_node: expr, $min_value_msat: expr) => {
1204                 {
1205                         use bitcoin::hashes::Hash as _;
1206                         let mut payment_count = $dest_node.network_payment_count.borrow_mut();
1207                         let payment_preimage = $crate::ln::PaymentPreimage([*payment_count; 32]);
1208                         *payment_count += 1;
1209                         let payment_hash = $crate::ln::PaymentHash(
1210                                 bitcoin::hashes::sha256::Hash::hash(&payment_preimage.0[..]).into_inner());
1211                         let payment_secret = $dest_node.node.create_inbound_payment_for_hash(payment_hash, $min_value_msat, 7200).unwrap();
1212                         (payment_preimage, payment_hash, payment_secret)
1213                 }
1214         }
1215 }
1216
1217 #[macro_export]
1218 macro_rules! get_route {
1219         ($send_node: expr, $payment_params: expr, $recv_value: expr, $cltv: expr) => {{
1220                 use $crate::chain::keysinterface::KeysInterface;
1221                 let scorer = $crate::util::test_utils::TestScorer::with_penalty(0);
1222                 let keys_manager = $crate::util::test_utils::TestKeysInterface::new(&[0u8; 32], bitcoin::network::constants::Network::Testnet);
1223                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
1224                 $crate::routing::router::get_route(
1225                         &$send_node.node.get_our_node_id(), &$payment_params, &$send_node.network_graph.read_only(),
1226                         Some(&$send_node.node.list_usable_channels().iter().collect::<Vec<_>>()),
1227                         $recv_value, $cltv, $send_node.logger, &scorer, &random_seed_bytes
1228                 )
1229         }}
1230 }
1231
1232 #[cfg(test)]
1233 #[macro_export]
1234 macro_rules! get_route_and_payment_hash {
1235         ($send_node: expr, $recv_node: expr, $recv_value: expr) => {{
1236                 let payment_params = $crate::routing::router::PaymentParameters::from_node_id($recv_node.node.get_our_node_id())
1237                         .with_features($crate::ln::features::InvoiceFeatures::known());
1238                 $crate::get_route_and_payment_hash!($send_node, $recv_node, payment_params, $recv_value, TEST_FINAL_CLTV)
1239         }};
1240         ($send_node: expr, $recv_node: expr, $payment_params: expr, $recv_value: expr, $cltv: expr) => {{
1241                 let (payment_preimage, payment_hash, payment_secret) = $crate::get_payment_preimage_hash!($recv_node, Some($recv_value));
1242                 let route = $crate::get_route!($send_node, $payment_params, $recv_value, $cltv);
1243                 (route.unwrap(), payment_hash, payment_preimage, payment_secret)
1244         }}
1245 }
1246
1247 #[macro_export]
1248 /// Clears (and ignores) a PendingHTLCsForwardable event
1249 macro_rules! expect_pending_htlcs_forwardable_ignore {
1250         ($node: expr) => {{
1251                 let events = $node.node.get_and_clear_pending_events();
1252                 assert_eq!(events.len(), 1);
1253                 match events[0] {
1254                         $crate::util::events::Event::PendingHTLCsForwardable { .. } => { },
1255                         _ => panic!("Unexpected event"),
1256                 };
1257         }}
1258 }
1259
1260 #[macro_export]
1261 /// Handles a PendingHTLCsForwardable event
1262 macro_rules! expect_pending_htlcs_forwardable {
1263         ($node: expr) => {{
1264                 $crate::expect_pending_htlcs_forwardable_ignore!($node);
1265                 $node.node.process_pending_htlc_forwards();
1266
1267                 // Ensure process_pending_htlc_forwards is idempotent.
1268                 $node.node.process_pending_htlc_forwards();
1269         }}
1270 }
1271
1272 #[cfg(test)]
1273 macro_rules! expect_pending_htlcs_forwardable_from_events {
1274         ($node: expr, $events: expr, $ignore: expr) => {{
1275                 assert_eq!($events.len(), 1);
1276                 match $events[0] {
1277                         Event::PendingHTLCsForwardable { .. } => { },
1278                         _ => panic!("Unexpected event"),
1279                 };
1280                 if $ignore {
1281                         $node.node.process_pending_htlc_forwards();
1282
1283                         // Ensure process_pending_htlc_forwards is idempotent.
1284                         $node.node.process_pending_htlc_forwards();
1285                 }
1286         }}
1287 }
1288
1289 #[macro_export]
1290 #[cfg(any(test, feature = "_bench_unstable", feature = "_test_utils"))]
1291 macro_rules! expect_payment_received {
1292         ($node: expr, $expected_payment_hash: expr, $expected_payment_secret: expr, $expected_recv_value: expr) => {
1293                 expect_payment_received!($node, $expected_payment_hash, $expected_payment_secret, $expected_recv_value, None)
1294         };
1295         ($node: expr, $expected_payment_hash: expr, $expected_payment_secret: expr, $expected_recv_value: expr, $expected_payment_preimage: expr) => {
1296                 let events = $node.node.get_and_clear_pending_events();
1297                 assert_eq!(events.len(), 1);
1298                 match events[0] {
1299                         $crate::util::events::Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1300                                 assert_eq!($expected_payment_hash, *payment_hash);
1301                                 assert_eq!($expected_recv_value, amt);
1302                                 match purpose {
1303                                         $crate::util::events::PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1304                                                 assert_eq!(&$expected_payment_preimage, payment_preimage);
1305                                                 assert_eq!($expected_payment_secret, *payment_secret);
1306                                         },
1307                                         _ => {},
1308                                 }
1309                         },
1310                         _ => panic!("Unexpected event"),
1311                 }
1312         }
1313 }
1314
1315 #[cfg(test)]
1316 #[macro_export]
1317 macro_rules! expect_payment_sent_without_paths {
1318         ($node: expr, $expected_payment_preimage: expr) => {
1319                 expect_payment_sent!($node, $expected_payment_preimage, None::<u64>, false);
1320         };
1321         ($node: expr, $expected_payment_preimage: expr, $expected_fee_msat_opt: expr) => {
1322                 expect_payment_sent!($node, $expected_payment_preimage, $expected_fee_msat_opt, false);
1323         }
1324 }
1325
1326 #[macro_export]
1327 macro_rules! expect_payment_sent {
1328         ($node: expr, $expected_payment_preimage: expr) => {
1329                 $crate::expect_payment_sent!($node, $expected_payment_preimage, None::<u64>, true);
1330         };
1331         ($node: expr, $expected_payment_preimage: expr, $expected_fee_msat_opt: expr) => {
1332                 $crate::expect_payment_sent!($node, $expected_payment_preimage, $expected_fee_msat_opt, true);
1333         };
1334         ($node: expr, $expected_payment_preimage: expr, $expected_fee_msat_opt: expr, $expect_paths: expr) => { {
1335                 use bitcoin::hashes::Hash as _;
1336                 let events = $node.node.get_and_clear_pending_events();
1337                 let expected_payment_hash = $crate::ln::PaymentHash(
1338                         bitcoin::hashes::sha256::Hash::hash(&$expected_payment_preimage.0).into_inner());
1339                 if $expect_paths {
1340                         assert!(events.len() > 1);
1341                 } else {
1342                         assert_eq!(events.len(), 1);
1343                 }
1344                 let expected_payment_id = match events[0] {
1345                         $crate::util::events::Event::PaymentSent { ref payment_id, ref payment_preimage, ref payment_hash, ref fee_paid_msat } => {
1346                                 assert_eq!($expected_payment_preimage, *payment_preimage);
1347                                 assert_eq!(expected_payment_hash, *payment_hash);
1348                                 assert!(fee_paid_msat.is_some());
1349                                 if $expected_fee_msat_opt.is_some() {
1350                                         assert_eq!(*fee_paid_msat, $expected_fee_msat_opt);
1351                                 }
1352                                 payment_id.unwrap()
1353                         },
1354                         _ => panic!("Unexpected event"),
1355                 };
1356                 if $expect_paths {
1357                         for i in 1..events.len() {
1358                                 match events[i] {
1359                                         $crate::util::events::Event::PaymentPathSuccessful { payment_id, payment_hash, .. } => {
1360                                                 assert_eq!(payment_id, expected_payment_id);
1361                                                 assert_eq!(payment_hash, Some(expected_payment_hash));
1362                                         },
1363                                         _ => panic!("Unexpected event"),
1364                                 }
1365                         }
1366                 }
1367         } }
1368 }
1369
1370 #[cfg(test)]
1371 #[macro_export]
1372 macro_rules! expect_payment_path_successful {
1373         ($node: expr) => {
1374                 let events = $node.node.get_and_clear_pending_events();
1375                 assert_eq!(events.len(), 1);
1376                 match events[0] {
1377                         $crate::util::events::Event::PaymentPathSuccessful { .. } => {},
1378                         _ => panic!("Unexpected event"),
1379                 }
1380         }
1381 }
1382
1383 macro_rules! expect_payment_forwarded {
1384         ($node: expr, $prev_node: expr, $next_node: expr, $expected_fee: expr, $upstream_force_closed: expr, $downstream_force_closed: expr) => {
1385                 let events = $node.node.get_and_clear_pending_events();
1386                 assert_eq!(events.len(), 1);
1387                 match events[0] {
1388                         Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
1389                                 assert_eq!(fee_earned_msat, $expected_fee);
1390                                 if fee_earned_msat.is_some() {
1391                                         // Is the event prev_channel_id in one of the channels between the two nodes?
1392                                         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()));
1393                                 }
1394                                 // We check for force closures since a force closed channel is removed from the
1395                                 // node's channel list
1396                                 if !$downstream_force_closed {
1397                                         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()));
1398                                 }
1399                                 assert_eq!(claim_from_onchain_tx, $upstream_force_closed);
1400                         },
1401                         _ => panic!("Unexpected event"),
1402                 }
1403         }
1404 }
1405
1406 pub struct PaymentFailedConditions<'a> {
1407         pub(crate) expected_htlc_error_data: Option<(u16, &'a [u8])>,
1408         pub(crate) expected_blamed_scid: Option<u64>,
1409         pub(crate) expected_blamed_chan_closed: Option<bool>,
1410         pub(crate) expected_mpp_parts_remain: bool,
1411 }
1412
1413 impl<'a> PaymentFailedConditions<'a> {
1414         pub fn new() -> Self {
1415                 Self {
1416                         expected_htlc_error_data: None,
1417                         expected_blamed_scid: None,
1418                         expected_blamed_chan_closed: None,
1419                         expected_mpp_parts_remain: false,
1420                 }
1421         }
1422         pub fn mpp_parts_remain(mut self) -> Self {
1423                 self.expected_mpp_parts_remain = true;
1424                 self
1425         }
1426         pub fn blamed_scid(mut self, scid: u64) -> Self {
1427                 self.expected_blamed_scid = Some(scid);
1428                 self
1429         }
1430         pub fn blamed_chan_closed(mut self, closed: bool) -> Self {
1431                 self.expected_blamed_chan_closed = Some(closed);
1432                 self
1433         }
1434         pub fn expected_htlc_error_data(mut self, code: u16, data: &'a [u8]) -> Self {
1435                 self.expected_htlc_error_data = Some((code, data));
1436                 self
1437         }
1438 }
1439
1440 #[cfg(test)]
1441 macro_rules! expect_payment_failed_with_update {
1442         ($node: expr, $expected_payment_hash: expr, $rejected_by_dest: expr, $scid: expr, $chan_closed: expr) => {
1443                 expect_payment_failed_conditions!($node, $expected_payment_hash, $rejected_by_dest,
1444                         $crate::ln::functional_test_utils::PaymentFailedConditions::new().blamed_scid($scid).blamed_chan_closed($chan_closed));
1445         }
1446 }
1447
1448 #[cfg(test)]
1449 macro_rules! expect_payment_failed {
1450         ($node: expr, $expected_payment_hash: expr, $rejected_by_dest: expr $(, $expected_error_code: expr, $expected_error_data: expr)*) => {
1451                 #[allow(unused_mut)]
1452                 let mut conditions = $crate::ln::functional_test_utils::PaymentFailedConditions::new();
1453                 $(
1454                         conditions = conditions.expected_htlc_error_data($expected_error_code, &$expected_error_data);
1455                 )*
1456                 expect_payment_failed_conditions!($node, $expected_payment_hash, $rejected_by_dest, conditions);
1457         };
1458 }
1459
1460 #[cfg(test)]
1461 macro_rules! expect_payment_failed_conditions {
1462         ($node: expr, $expected_payment_hash: expr, $rejected_by_dest: expr, $conditions: expr) => {
1463                 let events = $node.node.get_and_clear_pending_events();
1464                 assert_eq!(events.len(), 1);
1465                 let expected_payment_id = match events[0] {
1466                         Event::PaymentPathFailed { ref payment_hash, rejected_by_dest, ref error_code, ref error_data, ref path, ref retry, ref payment_id, ref network_update, .. } => {
1467                                 assert_eq!(*payment_hash, $expected_payment_hash, "unexpected payment_hash");
1468                                 assert_eq!(rejected_by_dest, $rejected_by_dest, "unexpected rejected_by_dest value");
1469                                 assert!(retry.is_some(), "expected retry.is_some()");
1470                                 assert_eq!(retry.as_ref().unwrap().final_value_msat, path.last().unwrap().fee_msat, "Retry amount should match last hop in path");
1471                                 assert_eq!(retry.as_ref().unwrap().payment_params.payee_pubkey, path.last().unwrap().pubkey, "Retry payee node_id should match last hop in path");
1472
1473                                 assert!(error_code.is_some(), "expected error_code.is_some() = true");
1474                                 assert!(error_data.is_some(), "expected error_data.is_some() = true");
1475                                 if let Some((code, data)) = $conditions.expected_htlc_error_data {
1476                                         assert_eq!(error_code.unwrap(), code, "unexpected error code");
1477                                         assert_eq!(&error_data.as_ref().unwrap()[..], data, "unexpected error data");
1478                                 }
1479
1480                                 if let Some(chan_closed) = $conditions.expected_blamed_chan_closed {
1481                                         match network_update {
1482                                                 &Some($crate::routing::network_graph::NetworkUpdate::ChannelUpdateMessage { ref msg }) if !chan_closed => {
1483                                                         if let Some(scid) = $conditions.expected_blamed_scid {
1484                                                                 assert_eq!(msg.contents.short_channel_id, scid);
1485                                                         }
1486                                                         assert_eq!(msg.contents.flags & 2, 0);
1487                                                 },
1488                                                 &Some($crate::routing::network_graph::NetworkUpdate::ChannelClosed { short_channel_id, is_permanent }) if chan_closed => {
1489                                                         if let Some(scid) = $conditions.expected_blamed_scid {
1490                                                                 assert_eq!(short_channel_id, scid);
1491                                                         }
1492                                                         assert!(is_permanent);
1493                                                 },
1494                                                 Some(_) => panic!("Unexpected update type"),
1495                                                 None => panic!("Expected update"),
1496                                         }
1497                                 }
1498
1499                                 payment_id.unwrap()
1500                         },
1501                         _ => panic!("Unexpected event"),
1502                 };
1503                 if !$conditions.expected_mpp_parts_remain {
1504                         $node.node.abandon_payment(expected_payment_id);
1505                         let events = $node.node.get_and_clear_pending_events();
1506                         assert_eq!(events.len(), 1);
1507                         match events[0] {
1508                                 Event::PaymentFailed { ref payment_hash, ref payment_id } => {
1509                                         assert_eq!(*payment_hash, $expected_payment_hash, "unexpected second payment_hash");
1510                                         assert_eq!(*payment_id, expected_payment_id);
1511                                 }
1512                                 _ => panic!("Unexpected second event"),
1513                         }
1514                 }
1515         }
1516 }
1517
1518 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 {
1519         let payment_id = origin_node.node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
1520         check_added_monitors!(origin_node, expected_paths.len());
1521         pass_along_route(origin_node, expected_paths, recv_value, our_payment_hash, our_payment_secret);
1522         payment_id
1523 }
1524
1525 pub fn pass_along_path<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_path: &[&Node<'a, 'b, 'c>], recv_value: u64, our_payment_hash: PaymentHash, our_payment_secret: Option<PaymentSecret>, ev: MessageSendEvent, payment_received_expected: bool, expected_preimage: Option<PaymentPreimage>) {
1526         let mut payment_event = SendEvent::from_event(ev);
1527         let mut prev_node = origin_node;
1528
1529         for (idx, &node) in expected_path.iter().enumerate() {
1530                 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
1531
1532                 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
1533                 check_added_monitors!(node, 0);
1534                 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
1535
1536                 expect_pending_htlcs_forwardable!(node);
1537
1538                 if idx == expected_path.len() - 1 {
1539                         let events_2 = node.node.get_and_clear_pending_events();
1540                         if payment_received_expected {
1541                                 assert_eq!(events_2.len(), 1);
1542                                 match events_2[0] {
1543                                         Event::PaymentReceived { ref payment_hash, ref purpose, amt} => {
1544                                                 assert_eq!(our_payment_hash, *payment_hash);
1545                                                 match &purpose {
1546                                                         PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1547                                                                 assert_eq!(expected_preimage, *payment_preimage);
1548                                                                 assert_eq!(our_payment_secret.unwrap(), *payment_secret);
1549                                                         },
1550                                                         PaymentPurpose::SpontaneousPayment(payment_preimage) => {
1551                                                                 assert_eq!(expected_preimage.unwrap(), *payment_preimage);
1552                                                                 assert!(our_payment_secret.is_none());
1553                                                         },
1554                                                 }
1555                                                 assert_eq!(amt, recv_value);
1556                                         },
1557                                         _ => panic!("Unexpected event"),
1558                                 }
1559                         } else {
1560                                 assert!(events_2.is_empty());
1561                         }
1562                 } else {
1563                         let mut events_2 = node.node.get_and_clear_pending_msg_events();
1564                         assert_eq!(events_2.len(), 1);
1565                         check_added_monitors!(node, 1);
1566                         payment_event = SendEvent::from_event(events_2.remove(0));
1567                         assert_eq!(payment_event.msgs.len(), 1);
1568                 }
1569
1570                 prev_node = node;
1571         }
1572 }
1573
1574 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) {
1575         let mut events = origin_node.node.get_and_clear_pending_msg_events();
1576         assert_eq!(events.len(), expected_route.len());
1577         for (path_idx, (ev, expected_path)) in events.drain(..).zip(expected_route.iter()).enumerate() {
1578                 // Once we've gotten through all the HTLCs, the last one should result in a
1579                 // PaymentReceived (but each previous one should not!), .
1580                 let expect_payment = path_idx == expected_route.len() - 1;
1581                 pass_along_path(origin_node, expected_path, recv_value, our_payment_hash.clone(), Some(our_payment_secret), ev, expect_payment, None);
1582         }
1583 }
1584
1585 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) {
1586         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(expected_route.last().unwrap());
1587         let payment_id = send_along_route_with_secret(origin_node, route, &[expected_route], recv_value, our_payment_hash, our_payment_secret);
1588         (our_payment_preimage, our_payment_hash, our_payment_secret, payment_id)
1589 }
1590
1591 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 {
1592         for path in expected_paths.iter() {
1593                 assert_eq!(path.last().unwrap().node.get_our_node_id(), expected_paths[0].last().unwrap().node.get_our_node_id());
1594         }
1595         assert!(expected_paths[0].last().unwrap().node.claim_funds(our_payment_preimage));
1596         check_added_monitors!(expected_paths[0].last().unwrap(), expected_paths.len());
1597
1598         let mut expected_total_fee_msat = 0;
1599
1600         macro_rules! msgs_from_ev {
1601                 ($ev: expr) => {
1602                         match $ev {
1603                                 &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 } } => {
1604                                         assert!(update_add_htlcs.is_empty());
1605                                         assert_eq!(update_fulfill_htlcs.len(), 1);
1606                                         assert!(update_fail_htlcs.is_empty());
1607                                         assert!(update_fail_malformed_htlcs.is_empty());
1608                                         assert!(update_fee.is_none());
1609                                         ((update_fulfill_htlcs[0].clone(), commitment_signed.clone()), node_id.clone())
1610                                 },
1611                                 _ => panic!("Unexpected event"),
1612                         }
1613                 }
1614         }
1615         let mut per_path_msgs: Vec<((msgs::UpdateFulfillHTLC, msgs::CommitmentSigned), PublicKey)> = Vec::with_capacity(expected_paths.len());
1616         let events = expected_paths[0].last().unwrap().node.get_and_clear_pending_msg_events();
1617         assert_eq!(events.len(), expected_paths.len());
1618         for ev in events.iter() {
1619                 per_path_msgs.push(msgs_from_ev!(ev));
1620         }
1621
1622         for (expected_route, (path_msgs, next_hop)) in expected_paths.iter().zip(per_path_msgs.drain(..)) {
1623                 let mut next_msgs = Some(path_msgs);
1624                 let mut expected_next_node = next_hop;
1625
1626                 macro_rules! last_update_fulfill_dance {
1627                         ($node: expr, $prev_node: expr) => {
1628                                 {
1629                                         $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0);
1630                                         check_added_monitors!($node, 0);
1631                                         assert!($node.node.get_and_clear_pending_msg_events().is_empty());
1632                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
1633                                 }
1634                         }
1635                 }
1636                 macro_rules! mid_update_fulfill_dance {
1637                         ($node: expr, $prev_node: expr, $next_node: expr, $new_msgs: expr) => {
1638                                 {
1639                                         $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0);
1640                                         let fee = $node.node.channel_state.lock().unwrap().by_id.get(&next_msgs.as_ref().unwrap().0.channel_id).unwrap().config.forwarding_fee_base_msat;
1641                                         expect_payment_forwarded!($node, $next_node, $prev_node, Some(fee as u64), false, false);
1642                                         expected_total_fee_msat += fee as u64;
1643                                         check_added_monitors!($node, 1);
1644                                         let new_next_msgs = if $new_msgs {
1645                                                 let events = $node.node.get_and_clear_pending_msg_events();
1646                                                 assert_eq!(events.len(), 1);
1647                                                 let (res, nexthop) = msgs_from_ev!(&events[0]);
1648                                                 expected_next_node = nexthop;
1649                                                 Some(res)
1650                                         } else {
1651                                                 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
1652                                                 None
1653                                         };
1654                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
1655                                         next_msgs = new_next_msgs;
1656                                 }
1657                         }
1658                 }
1659
1660                 let mut prev_node = expected_route.last().unwrap();
1661                 for (idx, node) in expected_route.iter().rev().enumerate().skip(1) {
1662                         assert_eq!(expected_next_node, node.node.get_our_node_id());
1663                         let update_next_msgs = !skip_last || idx != expected_route.len() - 1;
1664                         if next_msgs.is_some() {
1665                                 // Since we are traversing in reverse, next_node is actually the previous node
1666                                 let next_node: &Node;
1667                                 if idx == expected_route.len() - 1 {
1668                                         next_node = origin_node;
1669                                 } else {
1670                                         next_node = expected_route[expected_route.len() - 1 - idx - 1];
1671                                 }
1672                                 mid_update_fulfill_dance!(node, prev_node, next_node, update_next_msgs);
1673                         } else {
1674                                 assert!(!update_next_msgs);
1675                                 assert!(node.node.get_and_clear_pending_msg_events().is_empty());
1676                         }
1677                         if !skip_last && idx == expected_route.len() - 1 {
1678                                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
1679                         }
1680
1681                         prev_node = node;
1682                 }
1683
1684                 if !skip_last {
1685                         last_update_fulfill_dance!(origin_node, expected_route.first().unwrap());
1686                 }
1687         }
1688
1689         // Ensure that claim_funds is idempotent.
1690         assert!(!expected_paths[0].last().unwrap().node.claim_funds(our_payment_preimage));
1691         assert!(expected_paths[0].last().unwrap().node.get_and_clear_pending_msg_events().is_empty());
1692         check_added_monitors!(expected_paths[0].last().unwrap(), 0);
1693
1694         expected_total_fee_msat
1695 }
1696 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) {
1697         let expected_total_fee_msat = do_claim_payment_along_route(origin_node, expected_paths, skip_last, our_payment_preimage);
1698         if !skip_last {
1699                 expect_payment_sent!(origin_node, our_payment_preimage, Some(expected_total_fee_msat));
1700         }
1701 }
1702
1703 pub fn claim_payment<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_route: &[&Node<'a, 'b, 'c>], our_payment_preimage: PaymentPreimage) {
1704         claim_payment_along_route(origin_node, &[expected_route], false, our_payment_preimage);
1705 }
1706
1707 pub const TEST_FINAL_CLTV: u32 = 70;
1708
1709 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) {
1710         let payment_params = PaymentParameters::from_node_id(expected_route.last().unwrap().node.get_our_node_id())
1711                 .with_features(InvoiceFeatures::known());
1712         let route = get_route!(origin_node, payment_params, recv_value, TEST_FINAL_CLTV).unwrap();
1713         assert_eq!(route.paths.len(), 1);
1714         assert_eq!(route.paths[0].len(), expected_route.len());
1715         for (node, hop) in expected_route.iter().zip(route.paths[0].iter()) {
1716                 assert_eq!(hop.pubkey, node.node.get_our_node_id());
1717         }
1718
1719         let res = send_along_route(origin_node, route, expected_route, recv_value);
1720         (res.0, res.1, res.2)
1721 }
1722
1723 pub fn route_over_limit<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_route: &[&Node<'a, 'b, 'c>], recv_value: u64)  {
1724         let payment_params = PaymentParameters::from_node_id(expected_route.last().unwrap().node.get_our_node_id())
1725                 .with_features(InvoiceFeatures::known());
1726         let network_graph = origin_node.network_graph.read_only();
1727         let scorer = test_utils::TestScorer::with_penalty(0);
1728         let seed = [0u8; 32];
1729         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
1730         let random_seed_bytes = keys_manager.get_secure_random_bytes();
1731         let route = get_route(
1732                 &origin_node.node.get_our_node_id(), &payment_params, &network_graph,
1733                 None, recv_value, TEST_FINAL_CLTV, origin_node.logger, &scorer, &random_seed_bytes).unwrap();
1734         assert_eq!(route.paths.len(), 1);
1735         assert_eq!(route.paths[0].len(), expected_route.len());
1736         for (node, hop) in expected_route.iter().zip(route.paths[0].iter()) {
1737                 assert_eq!(hop.pubkey, node.node.get_our_node_id());
1738         }
1739
1740         let (_, our_payment_hash, our_payment_preimage) = get_payment_preimage_hash!(expected_route.last().unwrap());
1741         unwrap_send_err!(origin_node.node.send_payment(&route, our_payment_hash, &Some(our_payment_preimage)), true, APIError::ChannelUnavailable { ref err },
1742                 assert!(err.contains("Cannot send value that would put us over the max HTLC value in flight our peer will accept")));
1743 }
1744
1745 pub fn send_payment<'a, 'b, 'c>(origin: &Node<'a, 'b, 'c>, expected_route: &[&Node<'a, 'b, 'c>], recv_value: u64)  {
1746         let our_payment_preimage = route_payment(&origin, expected_route, recv_value).0;
1747         claim_payment(&origin, expected_route, our_payment_preimage);
1748 }
1749
1750 pub fn fail_payment_along_route<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_paths_slice: &[&[&Node<'a, 'b, 'c>]], skip_last: bool, our_payment_hash: PaymentHash)  {
1751         let mut expected_paths: Vec<_> = expected_paths_slice.iter().collect();
1752         for path in expected_paths.iter() {
1753                 assert_eq!(path.last().unwrap().node.get_our_node_id(), expected_paths[0].last().unwrap().node.get_our_node_id());
1754         }
1755         assert!(expected_paths[0].last().unwrap().node.fail_htlc_backwards(&our_payment_hash));
1756         expect_pending_htlcs_forwardable!(expected_paths[0].last().unwrap());
1757         check_added_monitors!(expected_paths[0].last().unwrap(), expected_paths.len());
1758
1759         let mut per_path_msgs: Vec<((msgs::UpdateFailHTLC, msgs::CommitmentSigned), PublicKey)> = Vec::with_capacity(expected_paths.len());
1760         let events = expected_paths[0].last().unwrap().node.get_and_clear_pending_msg_events();
1761         assert_eq!(events.len(), expected_paths.len());
1762         for ev in events.iter() {
1763                 let (update_fail, commitment_signed, node_id) = match ev {
1764                         &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 } } => {
1765                                 assert!(update_add_htlcs.is_empty());
1766                                 assert!(update_fulfill_htlcs.is_empty());
1767                                 assert_eq!(update_fail_htlcs.len(), 1);
1768                                 assert!(update_fail_malformed_htlcs.is_empty());
1769                                 assert!(update_fee.is_none());
1770                                 (update_fail_htlcs[0].clone(), commitment_signed.clone(), node_id.clone())
1771                         },
1772                         _ => panic!("Unexpected event"),
1773                 };
1774                 per_path_msgs.push(((update_fail, commitment_signed), node_id));
1775         }
1776         per_path_msgs.sort_unstable_by(|(_, node_id_a), (_, node_id_b)| node_id_a.cmp(node_id_b));
1777         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()));
1778
1779         for (i, (expected_route, (path_msgs, next_hop))) in expected_paths.iter().zip(per_path_msgs.drain(..)).enumerate() {
1780                 let mut next_msgs = Some(path_msgs);
1781                 let mut expected_next_node = next_hop;
1782                 let mut prev_node = expected_route.last().unwrap();
1783
1784                 for (idx, node) in expected_route.iter().rev().enumerate().skip(1) {
1785                         assert_eq!(expected_next_node, node.node.get_our_node_id());
1786                         let update_next_node = !skip_last || idx != expected_route.len() - 1;
1787                         if next_msgs.is_some() {
1788                                 node.node.handle_update_fail_htlc(&prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0);
1789                                 commitment_signed_dance!(node, prev_node, next_msgs.as_ref().unwrap().1, update_next_node);
1790                                 if !update_next_node {
1791                                         expect_pending_htlcs_forwardable!(node);
1792                                 }
1793                         }
1794                         let events = node.node.get_and_clear_pending_msg_events();
1795                         if update_next_node {
1796                                 assert_eq!(events.len(), 1);
1797                                 match events[0] {
1798                                         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 } } => {
1799                                                 assert!(update_add_htlcs.is_empty());
1800                                                 assert!(update_fulfill_htlcs.is_empty());
1801                                                 assert_eq!(update_fail_htlcs.len(), 1);
1802                                                 assert!(update_fail_malformed_htlcs.is_empty());
1803                                                 assert!(update_fee.is_none());
1804                                                 expected_next_node = node_id.clone();
1805                                                 next_msgs = Some((update_fail_htlcs[0].clone(), commitment_signed.clone()));
1806                                         },
1807                                         _ => panic!("Unexpected event"),
1808                                 }
1809                         } else {
1810                                 assert!(events.is_empty());
1811                         }
1812                         if !skip_last && idx == expected_route.len() - 1 {
1813                                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
1814                         }
1815
1816                         prev_node = node;
1817                 }
1818
1819                 if !skip_last {
1820                         let prev_node = expected_route.first().unwrap();
1821                         origin_node.node.handle_update_fail_htlc(&prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0);
1822                         check_added_monitors!(origin_node, 0);
1823                         assert!(origin_node.node.get_and_clear_pending_msg_events().is_empty());
1824                         commitment_signed_dance!(origin_node, prev_node, next_msgs.as_ref().unwrap().1, false);
1825                         let events = origin_node.node.get_and_clear_pending_events();
1826                         assert_eq!(events.len(), 1);
1827                         let expected_payment_id = match events[0] {
1828                                 Event::PaymentPathFailed { payment_hash, rejected_by_dest, all_paths_failed, ref path, ref payment_id, .. } => {
1829                                         assert_eq!(payment_hash, our_payment_hash);
1830                                         assert!(rejected_by_dest);
1831                                         assert_eq!(all_paths_failed, i == expected_paths.len() - 1);
1832                                         for (idx, hop) in expected_route.iter().enumerate() {
1833                                                 assert_eq!(hop.node.get_our_node_id(), path[idx].pubkey);
1834                                         }
1835                                         payment_id.unwrap()
1836                                 },
1837                                 _ => panic!("Unexpected event"),
1838                         };
1839                         if i == expected_paths.len() - 1 {
1840                                 origin_node.node.abandon_payment(expected_payment_id);
1841                                 let events = origin_node.node.get_and_clear_pending_events();
1842                                 assert_eq!(events.len(), 1);
1843                                 match events[0] {
1844                                         Event::PaymentFailed { ref payment_hash, ref payment_id } => {
1845                                                 assert_eq!(*payment_hash, our_payment_hash, "unexpected second payment_hash");
1846                                                 assert_eq!(*payment_id, expected_payment_id);
1847                                         }
1848                                         _ => panic!("Unexpected second event"),
1849                                 }
1850                         }
1851                 }
1852         }
1853
1854         // Ensure that fail_htlc_backwards is idempotent.
1855         assert!(!expected_paths[0].last().unwrap().node.fail_htlc_backwards(&our_payment_hash));
1856         assert!(expected_paths[0].last().unwrap().node.get_and_clear_pending_events().is_empty());
1857         assert!(expected_paths[0].last().unwrap().node.get_and_clear_pending_msg_events().is_empty());
1858         check_added_monitors!(expected_paths[0].last().unwrap(), 0);
1859 }
1860
1861 pub fn fail_payment<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_path: &[&Node<'a, 'b, 'c>], our_payment_hash: PaymentHash)  {
1862         fail_payment_along_route(origin_node, &[&expected_path[..]], false, our_payment_hash);
1863 }
1864
1865 pub fn create_chanmon_cfgs(node_count: usize) -> Vec<TestChanMonCfg> {
1866         let mut chan_mon_cfgs = Vec::new();
1867         for i in 0..node_count {
1868                 let tx_broadcaster = test_utils::TestBroadcaster {
1869                         txn_broadcasted: Mutex::new(Vec::new()),
1870                         blocks: Arc::new(Mutex::new(vec![(genesis_block(Network::Testnet), 0)])),
1871                 };
1872                 let fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
1873                 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
1874                 let logger = test_utils::TestLogger::with_id(format!("node {}", i));
1875                 let persister = test_utils::TestPersister::new();
1876                 let seed = [i as u8; 32];
1877                 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
1878                 let network_graph = NetworkGraph::new(chain_source.genesis_hash);
1879
1880                 chan_mon_cfgs.push(TestChanMonCfg{ tx_broadcaster, fee_estimator, chain_source, logger, persister, keys_manager, network_graph });
1881         }
1882
1883         chan_mon_cfgs
1884 }
1885
1886 pub fn create_node_cfgs<'a>(node_count: usize, chanmon_cfgs: &'a Vec<TestChanMonCfg>) -> Vec<NodeCfg<'a>> {
1887         let mut nodes = Vec::new();
1888
1889         for i in 0..node_count {
1890                 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);
1891                 let seed = [i as u8; 32];
1892                 nodes.push(NodeCfg {
1893                         chain_source: &chanmon_cfgs[i].chain_source,
1894                         logger: &chanmon_cfgs[i].logger,
1895                         tx_broadcaster: &chanmon_cfgs[i].tx_broadcaster,
1896                         fee_estimator: &chanmon_cfgs[i].fee_estimator,
1897                         chain_monitor,
1898                         keys_manager: &chanmon_cfgs[i].keys_manager,
1899                         node_seed: seed,
1900                         features: InitFeatures::known(),
1901                         network_graph: &chanmon_cfgs[i].network_graph,
1902                 });
1903         }
1904
1905         nodes
1906 }
1907
1908 pub fn test_default_channel_config() -> UserConfig {
1909         let mut default_config = UserConfig::default();
1910         // Set cltv_expiry_delta slightly lower to keep the final CLTV values inside one byte in our
1911         // tests so that our script-length checks don't fail (see ACCEPTED_HTLC_SCRIPT_WEIGHT).
1912         default_config.channel_options.cltv_expiry_delta = MIN_CLTV_EXPIRY_DELTA;
1913         default_config.channel_options.announced_channel = true;
1914         default_config.peer_channel_config_limits.force_announced_channel_preference = false;
1915         // When most of our tests were written, the default HTLC minimum was fixed at 1000.
1916         // It now defaults to 1, so we simply set it to the expected value here.
1917         default_config.own_channel_config.our_htlc_minimum_msat = 1000;
1918         // When most of our tests were written, we didn't have the notion of a `max_dust_htlc_exposure_msat`,
1919         // It now defaults to 5_000_000 msat; to avoid interfering with tests we bump it to 50_000_000 msat.
1920         default_config.channel_options.max_dust_htlc_exposure_msat = 50_000_000;
1921         default_config
1922 }
1923
1924 pub fn create_node_chanmgrs<'a, 'b>(node_count: usize, cfgs: &'a Vec<NodeCfg<'b>>, node_config: &[Option<UserConfig>]) -> Vec<ChannelManager<EnforcingSigner, &'a TestChainMonitor<'b>, &'b test_utils::TestBroadcaster, &'a test_utils::TestKeysInterface, &'b test_utils::TestFeeEstimator, &'b test_utils::TestLogger>> {
1925         let mut chanmgrs = Vec::new();
1926         for i in 0..node_count {
1927                 let network = Network::Testnet;
1928                 let params = ChainParameters {
1929                         network,
1930                         best_block: BestBlock::from_genesis(network),
1931                 };
1932                 let node = ChannelManager::new(cfgs[i].fee_estimator, &cfgs[i].chain_monitor, cfgs[i].tx_broadcaster, cfgs[i].logger, cfgs[i].keys_manager,
1933                         if node_config[i].is_some() { node_config[i].clone().unwrap() } else { test_default_channel_config() }, params);
1934                 chanmgrs.push(node);
1935         }
1936
1937         chanmgrs
1938 }
1939
1940 pub fn create_network<'a, 'b: 'a, 'c: 'b>(node_count: usize, cfgs: &'b Vec<NodeCfg<'c>>, chan_mgrs: &'a Vec<ChannelManager<EnforcingSigner, &'b TestChainMonitor<'c>, &'c test_utils::TestBroadcaster, &'b test_utils::TestKeysInterface, &'c test_utils::TestFeeEstimator, &'c test_utils::TestLogger>>) -> Vec<Node<'a, 'b, 'c>> {
1941         let mut nodes = Vec::new();
1942         let chan_count = Rc::new(RefCell::new(0));
1943         let payment_count = Rc::new(RefCell::new(0));
1944         let connect_style = Rc::new(RefCell::new(ConnectStyle::random_style()));
1945
1946         for i in 0..node_count {
1947                 let net_graph_msg_handler = NetGraphMsgHandler::new(cfgs[i].network_graph, None, cfgs[i].logger);
1948                 nodes.push(Node{
1949                         chain_source: cfgs[i].chain_source, tx_broadcaster: cfgs[i].tx_broadcaster,
1950                         chain_monitor: &cfgs[i].chain_monitor, keys_manager: &cfgs[i].keys_manager,
1951                         node: &chan_mgrs[i], network_graph: &cfgs[i].network_graph, net_graph_msg_handler,
1952                         node_seed: cfgs[i].node_seed, network_chan_count: chan_count.clone(),
1953                         network_payment_count: payment_count.clone(), logger: cfgs[i].logger,
1954                         blocks: Arc::clone(&cfgs[i].tx_broadcaster.blocks),
1955                         connect_style: Rc::clone(&connect_style),
1956                 })
1957         }
1958
1959         for i in 0..node_count {
1960                 for j in (i+1)..node_count {
1961                         nodes[i].node.peer_connected(&nodes[j].node.get_our_node_id(), &msgs::Init { features: cfgs[j].features.clone(), remote_network_address: None });
1962                         nodes[j].node.peer_connected(&nodes[i].node.get_our_node_id(), &msgs::Init { features: cfgs[i].features.clone(), remote_network_address: None });
1963                 }
1964         }
1965
1966         nodes
1967 }
1968
1969 // Note that the following only works for CLTV values up to 128
1970 pub const ACCEPTED_HTLC_SCRIPT_WEIGHT: usize = 137; //Here we have a diff due to HTLC CLTV expiry being < 2^15 in test
1971 pub const OFFERED_HTLC_SCRIPT_WEIGHT: usize = 133;
1972
1973 #[derive(PartialEq)]
1974 pub enum HTLCType { NONE, TIMEOUT, SUCCESS }
1975 /// Tests that the given node has broadcast transactions for the given Channel
1976 ///
1977 /// First checks that the latest holder commitment tx has been broadcast, unless an explicit
1978 /// commitment_tx is provided, which may be used to test that a remote commitment tx was
1979 /// broadcast and the revoked outputs were claimed.
1980 ///
1981 /// Next tests that there is (or is not) a transaction that spends the commitment transaction
1982 /// that appears to be the type of HTLC transaction specified in has_htlc_tx.
1983 ///
1984 /// All broadcast transactions must be accounted for in one of the above three types of we'll
1985 /// also fail.
1986 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>  {
1987         let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
1988         assert!(node_txn.len() >= if commitment_tx.is_some() { 0 } else { 1 } + if has_htlc_tx == HTLCType::NONE { 0 } else { 1 });
1989
1990         let mut res = Vec::with_capacity(2);
1991         node_txn.retain(|tx| {
1992                 if tx.input.len() == 1 && tx.input[0].previous_output.txid == chan.3.txid() {
1993                         check_spends!(tx, chan.3);
1994                         if commitment_tx.is_none() {
1995                                 res.push(tx.clone());
1996                         }
1997                         false
1998                 } else { true }
1999         });
2000         if let Some(explicit_tx) = commitment_tx {
2001                 res.push(explicit_tx.clone());
2002         }
2003
2004         assert_eq!(res.len(), 1);
2005
2006         if has_htlc_tx != HTLCType::NONE {
2007                 node_txn.retain(|tx| {
2008                         if tx.input.len() == 1 && tx.input[0].previous_output.txid == res[0].txid() {
2009                                 check_spends!(tx, res[0]);
2010                                 if has_htlc_tx == HTLCType::TIMEOUT {
2011                                         assert!(tx.lock_time != 0);
2012                                 } else {
2013                                         assert!(tx.lock_time == 0);
2014                                 }
2015                                 res.push(tx.clone());
2016                                 false
2017                         } else { true }
2018                 });
2019                 assert!(res.len() == 2 || res.len() == 3);
2020                 if res.len() == 3 {
2021                         assert_eq!(res[1], res[2]);
2022                 }
2023         }
2024
2025         assert!(node_txn.is_empty());
2026         res
2027 }
2028
2029 /// Tests that the given node has broadcast a claim transaction against the provided revoked
2030 /// HTLC transaction.
2031 pub fn test_revoked_htlc_claim_txn_broadcast<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, revoked_tx: Transaction, commitment_revoked_tx: Transaction)  {
2032         let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2033         // We may issue multiple claiming transaction on revoked outputs due to block rescan
2034         // for revoked htlc outputs
2035         if node_txn.len() != 1 && node_txn.len() != 2 && node_txn.len() != 3 { assert!(false); }
2036         node_txn.retain(|tx| {
2037                 if tx.input.len() == 1 && tx.input[0].previous_output.txid == revoked_tx.txid() {
2038                         check_spends!(tx, revoked_tx);
2039                         false
2040                 } else { true }
2041         });
2042         node_txn.retain(|tx| {
2043                 check_spends!(tx, commitment_revoked_tx);
2044                 false
2045         });
2046         assert!(node_txn.is_empty());
2047 }
2048
2049 pub fn check_preimage_claim<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, prev_txn: &Vec<Transaction>) -> Vec<Transaction>  {
2050         let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2051
2052         assert!(node_txn.len() >= 1);
2053         assert_eq!(node_txn[0].input.len(), 1);
2054         let mut found_prev = false;
2055
2056         for tx in prev_txn {
2057                 if node_txn[0].input[0].previous_output.txid == tx.txid() {
2058                         check_spends!(node_txn[0], tx);
2059                         let mut iter = node_txn[0].input[0].witness.iter();
2060                         iter.next().expect("expected 3 witness items");
2061                         iter.next().expect("expected 3 witness items");
2062                         assert!(iter.next().expect("expected 3 witness items").len() > 106); // must spend an htlc output
2063                         assert_eq!(tx.input.len(), 1); // must spend a commitment tx
2064
2065                         found_prev = true;
2066                         break;
2067                 }
2068         }
2069         assert!(found_prev);
2070
2071         let mut res = Vec::new();
2072         mem::swap(&mut *node_txn, &mut res);
2073         res
2074 }
2075
2076 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)  {
2077         let events_1 = nodes[a].node.get_and_clear_pending_msg_events();
2078         assert_eq!(events_1.len(), 2);
2079         let as_update = match events_1[0] {
2080                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2081                         msg.clone()
2082                 },
2083                 _ => panic!("Unexpected event"),
2084         };
2085         match events_1[1] {
2086                 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
2087                         assert_eq!(node_id, nodes[b].node.get_our_node_id());
2088                         assert_eq!(msg.data, expected_error);
2089                         if needs_err_handle {
2090                                 nodes[b].node.handle_error(&nodes[a].node.get_our_node_id(), msg);
2091                         }
2092                 },
2093                 _ => panic!("Unexpected event"),
2094         }
2095
2096         let events_2 = nodes[b].node.get_and_clear_pending_msg_events();
2097         assert_eq!(events_2.len(), if needs_err_handle { 1 } else { 2 });
2098         let bs_update = match events_2[0] {
2099                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2100                         msg.clone()
2101                 },
2102                 _ => panic!("Unexpected event"),
2103         };
2104         if !needs_err_handle {
2105                 match events_2[1] {
2106                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
2107                                 assert_eq!(node_id, nodes[a].node.get_our_node_id());
2108                                 assert_eq!(msg.data, expected_error);
2109                         },
2110                         _ => panic!("Unexpected event"),
2111                 }
2112         }
2113
2114         for node in nodes {
2115                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
2116                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
2117         }
2118 }
2119
2120 pub fn get_announce_close_broadcast_events<'a, 'b, 'c>(nodes: &Vec<Node<'a, 'b, 'c>>, a: usize, b: usize)  {
2121         handle_announce_close_broadcast_events(nodes, a, b, false, "Channel closed because commitment or closing transaction was confirmed on chain.");
2122 }
2123
2124 #[cfg(test)]
2125 macro_rules! get_channel_value_stat {
2126         ($node: expr, $channel_id: expr) => {{
2127                 let chan_lock = $node.node.channel_state.lock().unwrap();
2128                 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
2129                 chan.get_value_stat()
2130         }}
2131 }
2132
2133 macro_rules! get_chan_reestablish_msgs {
2134         ($src_node: expr, $dst_node: expr) => {
2135                 {
2136                         let mut res = Vec::with_capacity(1);
2137                         for msg in $src_node.node.get_and_clear_pending_msg_events() {
2138                                 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
2139                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2140                                         res.push(msg.clone());
2141                                 } else {
2142                                         panic!("Unexpected event")
2143                                 }
2144                         }
2145                         res
2146                 }
2147         }
2148 }
2149
2150 macro_rules! handle_chan_reestablish_msgs {
2151         ($src_node: expr, $dst_node: expr) => {
2152                 {
2153                         let msg_events = $src_node.node.get_and_clear_pending_msg_events();
2154                         let mut idx = 0;
2155                         let funding_locked = if let Some(&MessageSendEvent::SendFundingLocked { ref node_id, ref msg }) = msg_events.get(0) {
2156                                 idx += 1;
2157                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2158                                 Some(msg.clone())
2159                         } else {
2160                                 None
2161                         };
2162
2163                         if let Some(&MessageSendEvent::SendAnnouncementSignatures { ref node_id, msg: _ }) = msg_events.get(idx) {
2164                                 idx += 1;
2165                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2166                         }
2167
2168                         let mut revoke_and_ack = None;
2169                         let mut commitment_update = None;
2170                         let order = if let Some(ev) = msg_events.get(idx) {
2171                                 match ev {
2172                                         &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
2173                                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2174                                                 revoke_and_ack = Some(msg.clone());
2175                                                 idx += 1;
2176                                                 RAACommitmentOrder::RevokeAndACKFirst
2177                                         },
2178                                         &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
2179                                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2180                                                 commitment_update = Some(updates.clone());
2181                                                 idx += 1;
2182                                                 RAACommitmentOrder::CommitmentFirst
2183                                         },
2184                                         _ => RAACommitmentOrder::CommitmentFirst,
2185                                 }
2186                         } else {
2187                                 RAACommitmentOrder::CommitmentFirst
2188                         };
2189
2190                         if let Some(ev) = msg_events.get(idx) {
2191                                 match ev {
2192                                         &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
2193                                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2194                                                 assert!(revoke_and_ack.is_none());
2195                                                 revoke_and_ack = Some(msg.clone());
2196                                                 idx += 1;
2197                                         },
2198                                         &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
2199                                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2200                                                 assert!(commitment_update.is_none());
2201                                                 commitment_update = Some(updates.clone());
2202                                                 idx += 1;
2203                                         },
2204                                         _ => {},
2205                                 }
2206                         }
2207
2208                         if let Some(&MessageSendEvent::SendChannelUpdate { ref node_id, ref msg }) = msg_events.get(idx) {
2209                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2210                                 idx += 1;
2211                                 assert_eq!(msg.contents.flags & 2, 0); // "disabled" flag must not be set as we just reconnected.
2212                         }
2213
2214                         assert_eq!(msg_events.len(), idx);
2215
2216                         (funding_locked, revoke_and_ack, commitment_update, order)
2217                 }
2218         }
2219 }
2220
2221 /// pending_htlc_adds includes both the holding cell and in-flight update_add_htlcs, whereas
2222 /// for claims/fails they are separated out.
2223 pub fn reconnect_nodes<'a, 'b, 'c>(node_a: &Node<'a, 'b, 'c>, node_b: &Node<'a, 'b, 'c>, send_funding_locked: (bool, bool), pending_htlc_adds: (i64, i64), pending_htlc_claims: (usize, usize), pending_htlc_fails: (usize, usize), pending_cell_htlc_claims: (usize, usize), pending_cell_htlc_fails: (usize, usize), pending_raa: (bool, bool))  {
2224         node_a.node.peer_connected(&node_b.node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
2225         let reestablish_1 = get_chan_reestablish_msgs!(node_a, node_b);
2226         node_b.node.peer_connected(&node_a.node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
2227         let reestablish_2 = get_chan_reestablish_msgs!(node_b, node_a);
2228
2229         if send_funding_locked.0 {
2230                 // If a expects a funding_locked, it better not think it has received a revoke_and_ack
2231                 // from b
2232                 for reestablish in reestablish_1.iter() {
2233                         assert_eq!(reestablish.next_remote_commitment_number, 0);
2234                 }
2235         }
2236         if send_funding_locked.1 {
2237                 // If b expects a funding_locked, it better not think it has received a revoke_and_ack
2238                 // from a
2239                 for reestablish in reestablish_2.iter() {
2240                         assert_eq!(reestablish.next_remote_commitment_number, 0);
2241                 }
2242         }
2243         if send_funding_locked.0 || send_funding_locked.1 {
2244                 // If we expect any funding_locked's, both sides better have set
2245                 // next_holder_commitment_number to 1
2246                 for reestablish in reestablish_1.iter() {
2247                         assert_eq!(reestablish.next_local_commitment_number, 1);
2248                 }
2249                 for reestablish in reestablish_2.iter() {
2250                         assert_eq!(reestablish.next_local_commitment_number, 1);
2251                 }
2252         }
2253
2254         let mut resp_1 = Vec::new();
2255         for msg in reestablish_1 {
2256                 node_b.node.handle_channel_reestablish(&node_a.node.get_our_node_id(), &msg);
2257                 resp_1.push(handle_chan_reestablish_msgs!(node_b, node_a));
2258         }
2259         if pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
2260                 check_added_monitors!(node_b, 1);
2261         } else {
2262                 check_added_monitors!(node_b, 0);
2263         }
2264
2265         let mut resp_2 = Vec::new();
2266         for msg in reestablish_2 {
2267                 node_a.node.handle_channel_reestablish(&node_b.node.get_our_node_id(), &msg);
2268                 resp_2.push(handle_chan_reestablish_msgs!(node_a, node_b));
2269         }
2270         if pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
2271                 check_added_monitors!(node_a, 1);
2272         } else {
2273                 check_added_monitors!(node_a, 0);
2274         }
2275
2276         // We don't yet support both needing updates, as that would require a different commitment dance:
2277         assert!((pending_htlc_adds.0 == 0 && pending_htlc_claims.0 == 0 && pending_htlc_fails.0 == 0 &&
2278                          pending_cell_htlc_claims.0 == 0 && pending_cell_htlc_fails.0 == 0) ||
2279                         (pending_htlc_adds.1 == 0 && pending_htlc_claims.1 == 0 && pending_htlc_fails.1 == 0 &&
2280                          pending_cell_htlc_claims.1 == 0 && pending_cell_htlc_fails.1 == 0));
2281
2282         for chan_msgs in resp_1.drain(..) {
2283                 if send_funding_locked.0 {
2284                         node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), &chan_msgs.0.unwrap());
2285                         let announcement_event = node_a.node.get_and_clear_pending_msg_events();
2286                         if !announcement_event.is_empty() {
2287                                 assert_eq!(announcement_event.len(), 1);
2288                                 if let MessageSendEvent::SendChannelUpdate { .. } = announcement_event[0] {
2289                                         //TODO: Test announcement_sigs re-sending
2290                                 } else { panic!("Unexpected event! {:?}", announcement_event[0]); }
2291                         }
2292                 } else {
2293                         assert!(chan_msgs.0.is_none());
2294                 }
2295                 if pending_raa.0 {
2296                         assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
2297                         node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap());
2298                         assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
2299                         check_added_monitors!(node_a, 1);
2300                 } else {
2301                         assert!(chan_msgs.1.is_none());
2302                 }
2303                 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 {
2304                         let commitment_update = chan_msgs.2.unwrap();
2305                         if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
2306                                 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.0 as usize);
2307                         } else {
2308                                 assert!(commitment_update.update_add_htlcs.is_empty());
2309                         }
2310                         assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
2311                         assert_eq!(commitment_update.update_fail_htlcs.len(), pending_htlc_fails.0 + pending_cell_htlc_fails.0);
2312                         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
2313                         for update_add in commitment_update.update_add_htlcs {
2314                                 node_a.node.handle_update_add_htlc(&node_b.node.get_our_node_id(), &update_add);
2315                         }
2316                         for update_fulfill in commitment_update.update_fulfill_htlcs {
2317                                 node_a.node.handle_update_fulfill_htlc(&node_b.node.get_our_node_id(), &update_fulfill);
2318                         }
2319                         for update_fail in commitment_update.update_fail_htlcs {
2320                                 node_a.node.handle_update_fail_htlc(&node_b.node.get_our_node_id(), &update_fail);
2321                         }
2322
2323                         if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
2324                                 commitment_signed_dance!(node_a, node_b, commitment_update.commitment_signed, false);
2325                         } else {
2326                                 node_a.node.handle_commitment_signed(&node_b.node.get_our_node_id(), &commitment_update.commitment_signed);
2327                                 check_added_monitors!(node_a, 1);
2328                                 let as_revoke_and_ack = get_event_msg!(node_a, MessageSendEvent::SendRevokeAndACK, node_b.node.get_our_node_id());
2329                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
2330                                 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &as_revoke_and_ack);
2331                                 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
2332                                 check_added_monitors!(node_b, 1);
2333                         }
2334                 } else {
2335                         assert!(chan_msgs.2.is_none());
2336                 }
2337         }
2338
2339         for chan_msgs in resp_2.drain(..) {
2340                 if send_funding_locked.1 {
2341                         node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &chan_msgs.0.unwrap());
2342                         let announcement_event = node_b.node.get_and_clear_pending_msg_events();
2343                         if !announcement_event.is_empty() {
2344                                 assert_eq!(announcement_event.len(), 1);
2345                                 match announcement_event[0] {
2346                                         MessageSendEvent::SendChannelUpdate { .. } => {},
2347                                         MessageSendEvent::SendAnnouncementSignatures { .. } => {},
2348                                         _ => panic!("Unexpected event {:?}!", announcement_event[0]),
2349                                 }
2350                         }
2351                 } else {
2352                         assert!(chan_msgs.0.is_none());
2353                 }
2354                 if pending_raa.1 {
2355                         assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
2356                         node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap());
2357                         assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
2358                         check_added_monitors!(node_b, 1);
2359                 } else {
2360                         assert!(chan_msgs.1.is_none());
2361                 }
2362                 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 {
2363                         let commitment_update = chan_msgs.2.unwrap();
2364                         if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
2365                                 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.1 as usize);
2366                         }
2367                         assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.1 + pending_cell_htlc_claims.1);
2368                         assert_eq!(commitment_update.update_fail_htlcs.len(), pending_htlc_fails.1 + pending_cell_htlc_fails.1);
2369                         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
2370                         for update_add in commitment_update.update_add_htlcs {
2371                                 node_b.node.handle_update_add_htlc(&node_a.node.get_our_node_id(), &update_add);
2372                         }
2373                         for update_fulfill in commitment_update.update_fulfill_htlcs {
2374                                 node_b.node.handle_update_fulfill_htlc(&node_a.node.get_our_node_id(), &update_fulfill);
2375                         }
2376                         for update_fail in commitment_update.update_fail_htlcs {
2377                                 node_b.node.handle_update_fail_htlc(&node_a.node.get_our_node_id(), &update_fail);
2378                         }
2379
2380                         if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
2381                                 commitment_signed_dance!(node_b, node_a, commitment_update.commitment_signed, false);
2382                         } else {
2383                                 node_b.node.handle_commitment_signed(&node_a.node.get_our_node_id(), &commitment_update.commitment_signed);
2384                                 check_added_monitors!(node_b, 1);
2385                                 let bs_revoke_and_ack = get_event_msg!(node_b, MessageSendEvent::SendRevokeAndACK, node_a.node.get_our_node_id());
2386                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
2387                                 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &bs_revoke_and_ack);
2388                                 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
2389                                 check_added_monitors!(node_a, 1);
2390                         }
2391                 } else {
2392                         assert!(chan_msgs.2.is_none());
2393                 }
2394         }
2395 }