Randomize the `ConnectStyle` during 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_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 channel_value_satoshis, ref output_script, user_channel_id } => {
609                         assert_eq!(*channel_value_satoshis, expected_chan_value);
610                         assert_eq!(user_channel_id, expected_user_chan_id);
611
612                         let tx = Transaction { version: chan_id as i32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
613                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
614                         }]};
615                         let funding_outpoint = OutPoint { txid: tx.txid(), index: 0 };
616                         (*temporary_channel_id, tx, funding_outpoint)
617                 },
618                 _ => panic!("Unexpected event"),
619         }
620 }
621 pub fn sign_funding_transaction<'a, 'b, 'c>(node_a: &Node<'a, 'b, 'c>, node_b: &Node<'a, 'b, 'c>, channel_value: u64, expected_temporary_channel_id: [u8; 32]) -> Transaction {
622         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(node_a, channel_value, 42);
623         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
624
625         assert!(node_a.node.funding_transaction_generated(&temporary_channel_id, tx.clone()).is_ok());
626         check_added_monitors!(node_a, 0);
627
628         let funding_created_msg = get_event_msg!(node_a, MessageSendEvent::SendFundingCreated, node_b.node.get_our_node_id());
629         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
630         node_b.node.handle_funding_created(&node_a.node.get_our_node_id(), &funding_created_msg);
631         {
632                 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
633                 assert_eq!(added_monitors.len(), 1);
634                 assert_eq!(added_monitors[0].0, funding_output);
635                 added_monitors.clear();
636         }
637
638         node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id()));
639         {
640                 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
641                 assert_eq!(added_monitors.len(), 1);
642                 assert_eq!(added_monitors[0].0, funding_output);
643                 added_monitors.clear();
644         }
645
646         let events_4 = node_a.node.get_and_clear_pending_events();
647         assert_eq!(events_4.len(), 0);
648
649         assert_eq!(node_a.tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
650         assert_eq!(node_a.tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
651         node_a.tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
652
653         // Ensure that funding_transaction_generated is idempotent.
654         assert!(node_a.node.funding_transaction_generated(&temporary_channel_id, tx.clone()).is_err());
655         assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
656         check_added_monitors!(node_a, 0);
657
658         tx
659 }
660
661 pub fn create_chan_between_nodes_with_value_init<'a, 'b, 'c>(node_a: &Node<'a, 'b, 'c>, node_b: &Node<'a, 'b, 'c>, channel_value: u64, push_msat: u64, a_flags: InitFeatures, b_flags: InitFeatures) -> Transaction {
662         let create_chan_id = node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
663         let open_channel_msg = get_event_msg!(node_a, MessageSendEvent::SendOpenChannel, node_b.node.get_our_node_id());
664         assert_eq!(open_channel_msg.temporary_channel_id, create_chan_id);
665         node_b.node.handle_open_channel(&node_a.node.get_our_node_id(), a_flags, &open_channel_msg);
666         let accept_channel_msg = get_event_msg!(node_b, MessageSendEvent::SendAcceptChannel, node_a.node.get_our_node_id());
667         assert_eq!(accept_channel_msg.temporary_channel_id, create_chan_id);
668         node_a.node.handle_accept_channel(&node_b.node.get_our_node_id(), b_flags, &accept_channel_msg);
669
670         sign_funding_transaction(node_a, node_b, channel_value, create_chan_id)
671 }
672
673 pub fn create_chan_between_nodes_with_value_confirm_first<'a, 'b, 'c, 'd>(node_recv: &'a Node<'b, 'c, 'c>, node_conf: &'a Node<'b, 'c, 'd>, tx: &Transaction, conf_height: u32) {
674         confirm_transaction_at(node_conf, tx, conf_height);
675         connect_blocks(node_conf, CHAN_CONFIRM_DEPTH - 1);
676         node_recv.node.handle_funding_locked(&node_conf.node.get_our_node_id(), &get_event_msg!(node_conf, MessageSendEvent::SendFundingLocked, node_recv.node.get_our_node_id()));
677 }
678
679 pub fn create_chan_between_nodes_with_value_confirm_second<'a, 'b, 'c>(node_recv: &Node<'a, 'b, 'c>, node_conf: &Node<'a, 'b, 'c>) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32]) {
680         let channel_id;
681         let events_6 = node_conf.node.get_and_clear_pending_msg_events();
682         assert_eq!(events_6.len(), 3);
683         let announcement_sigs_idx = if let MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } = events_6[1] {
684                 assert_eq!(*node_id, node_recv.node.get_our_node_id());
685                 2
686         } else if let MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } = events_6[2] {
687                 assert_eq!(*node_id, node_recv.node.get_our_node_id());
688                 1
689         } else { panic!("Unexpected event: {:?}", events_6[1]); };
690         ((match events_6[0] {
691                 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
692                         channel_id = msg.channel_id.clone();
693                         assert_eq!(*node_id, node_recv.node.get_our_node_id());
694                         msg.clone()
695                 },
696                 _ => panic!("Unexpected event"),
697         }, match events_6[announcement_sigs_idx] {
698                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
699                         assert_eq!(*node_id, node_recv.node.get_our_node_id());
700                         msg.clone()
701                 },
702                 _ => panic!("Unexpected event"),
703         }), channel_id)
704 }
705
706 pub fn create_chan_between_nodes_with_value_confirm<'a, 'b, 'c, 'd>(node_a: &'a Node<'b, 'c, 'd>, node_b: &'a Node<'b, 'c, 'd>, tx: &Transaction) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32]) {
707         let conf_height = core::cmp::max(node_a.best_block_info().1 + 1, node_b.best_block_info().1 + 1);
708         create_chan_between_nodes_with_value_confirm_first(node_a, node_b, tx, conf_height);
709         confirm_transaction_at(node_a, tx, conf_height);
710         connect_blocks(node_a, CHAN_CONFIRM_DEPTH - 1);
711         create_chan_between_nodes_with_value_confirm_second(node_b, node_a)
712 }
713
714 pub fn create_chan_between_nodes_with_value_a<'a, 'b, 'c, 'd>(node_a: &'a Node<'b, 'c, 'd>, node_b: &'a Node<'b, 'c, 'd>, channel_value: u64, push_msat: u64, a_flags: InitFeatures, b_flags: InitFeatures) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32], Transaction) {
715         let tx = create_chan_between_nodes_with_value_init(node_a, node_b, channel_value, push_msat, a_flags, b_flags);
716         let (msgs, chan_id) = create_chan_between_nodes_with_value_confirm(node_a, node_b, &tx);
717         (msgs, chan_id, tx)
718 }
719
720 pub fn create_chan_between_nodes_with_value_b<'a, 'b, 'c>(node_a: &Node<'a, 'b, 'c>, node_b: &Node<'a, 'b, 'c>, as_funding_msgs: &(msgs::FundingLocked, msgs::AnnouncementSignatures)) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate) {
721         node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &as_funding_msgs.0);
722         let bs_announcement_sigs = get_event_msg!(node_b, MessageSendEvent::SendAnnouncementSignatures, node_a.node.get_our_node_id());
723         node_b.node.handle_announcement_signatures(&node_a.node.get_our_node_id(), &as_funding_msgs.1);
724
725         let events_7 = node_b.node.get_and_clear_pending_msg_events();
726         assert_eq!(events_7.len(), 1);
727         let (announcement, bs_update) = match events_7[0] {
728                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
729                         (msg, update_msg)
730                 },
731                 _ => panic!("Unexpected event"),
732         };
733
734         node_a.node.handle_announcement_signatures(&node_b.node.get_our_node_id(), &bs_announcement_sigs);
735         let events_8 = node_a.node.get_and_clear_pending_msg_events();
736         assert_eq!(events_8.len(), 1);
737         let as_update = match events_8[0] {
738                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
739                         assert!(*announcement == *msg);
740                         assert_eq!(update_msg.contents.short_channel_id, announcement.contents.short_channel_id);
741                         assert_eq!(update_msg.contents.short_channel_id, bs_update.contents.short_channel_id);
742                         update_msg
743                 },
744                 _ => panic!("Unexpected event"),
745         };
746
747         *node_a.network_chan_count.borrow_mut() += 1;
748
749         ((*announcement).clone(), (*as_update).clone(), (*bs_update).clone())
750 }
751
752 pub fn create_announced_chan_between_nodes<'a, 'b, 'c, 'd>(nodes: &'a Vec<Node<'b, 'c, 'd>>, a: usize, b: usize, a_flags: InitFeatures, b_flags: InitFeatures) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
753         create_announced_chan_between_nodes_with_value(nodes, a, b, 100000, 10001, a_flags, b_flags)
754 }
755
756 pub fn create_announced_chan_between_nodes_with_value<'a, 'b, 'c, 'd>(nodes: &'a Vec<Node<'b, 'c, 'd>>, a: usize, b: usize, channel_value: u64, push_msat: u64, a_flags: InitFeatures, b_flags: InitFeatures) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
757         let chan_announcement = create_chan_between_nodes_with_value(&nodes[a], &nodes[b], channel_value, push_msat, a_flags, b_flags);
758         update_nodes_with_chan_announce(nodes, a, b, &chan_announcement.0, &chan_announcement.1, &chan_announcement.2);
759         (chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
760 }
761
762 pub fn create_unannounced_chan_between_nodes_with_value<'a, 'b, 'c, 'd>(nodes: &'a Vec<Node<'b, 'c, 'd>>, a: usize, b: usize, channel_value: u64, push_msat: u64, a_flags: InitFeatures, b_flags: InitFeatures) -> (msgs::FundingLocked, Transaction) {
763         let mut no_announce_cfg = test_default_channel_config();
764         no_announce_cfg.channel_options.announced_channel = false;
765         nodes[a].node.create_channel(nodes[b].node.get_our_node_id(), channel_value, push_msat, 42, Some(no_announce_cfg)).unwrap();
766         let open_channel = get_event_msg!(nodes[a], MessageSendEvent::SendOpenChannel, nodes[b].node.get_our_node_id());
767         nodes[b].node.handle_open_channel(&nodes[a].node.get_our_node_id(), a_flags, &open_channel);
768         let accept_channel = get_event_msg!(nodes[b], MessageSendEvent::SendAcceptChannel, nodes[a].node.get_our_node_id());
769         nodes[a].node.handle_accept_channel(&nodes[b].node.get_our_node_id(), b_flags, &accept_channel);
770
771         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[a], channel_value, 42);
772         nodes[a].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
773         nodes[b].node.handle_funding_created(&nodes[a].node.get_our_node_id(), &get_event_msg!(nodes[a], MessageSendEvent::SendFundingCreated, nodes[b].node.get_our_node_id()));
774         check_added_monitors!(nodes[b], 1);
775
776         let cs_funding_signed = get_event_msg!(nodes[b], MessageSendEvent::SendFundingSigned, nodes[a].node.get_our_node_id());
777         nodes[a].node.handle_funding_signed(&nodes[b].node.get_our_node_id(), &cs_funding_signed);
778         check_added_monitors!(nodes[a], 1);
779
780         let conf_height = core::cmp::max(nodes[a].best_block_info().1 + 1, nodes[b].best_block_info().1 + 1);
781         confirm_transaction_at(&nodes[a], &tx, conf_height);
782         connect_blocks(&nodes[a], CHAN_CONFIRM_DEPTH - 1);
783         confirm_transaction_at(&nodes[b], &tx, conf_height);
784         connect_blocks(&nodes[b], CHAN_CONFIRM_DEPTH - 1);
785         let as_funding_locked = get_event_msg!(nodes[a], MessageSendEvent::SendFundingLocked, nodes[b].node.get_our_node_id());
786         nodes[a].node.handle_funding_locked(&nodes[b].node.get_our_node_id(), &get_event_msg!(nodes[b], MessageSendEvent::SendFundingLocked, nodes[a].node.get_our_node_id()));
787         let as_update = get_event_msg!(nodes[a], MessageSendEvent::SendChannelUpdate, nodes[b].node.get_our_node_id());
788         nodes[b].node.handle_funding_locked(&nodes[a].node.get_our_node_id(), &as_funding_locked);
789         let bs_update = get_event_msg!(nodes[b], MessageSendEvent::SendChannelUpdate, nodes[a].node.get_our_node_id());
790
791         nodes[a].node.handle_channel_update(&nodes[b].node.get_our_node_id(), &bs_update);
792         nodes[b].node.handle_channel_update(&nodes[a].node.get_our_node_id(), &as_update);
793
794         let mut found_a = false;
795         for chan in nodes[a].node.list_usable_channels() {
796                 if chan.channel_id == as_funding_locked.channel_id {
797                         assert!(!found_a);
798                         found_a = true;
799                         assert!(!chan.is_public);
800                 }
801         }
802         assert!(found_a);
803
804         let mut found_b = false;
805         for chan in nodes[b].node.list_usable_channels() {
806                 if chan.channel_id == as_funding_locked.channel_id {
807                         assert!(!found_b);
808                         found_b = true;
809                         assert!(!chan.is_public);
810                 }
811         }
812         assert!(found_b);
813
814         (as_funding_locked, tx)
815 }
816
817 pub fn update_nodes_with_chan_announce<'a, 'b, 'c, 'd>(nodes: &'a Vec<Node<'b, 'c, 'd>>, a: usize, b: usize, ann: &msgs::ChannelAnnouncement, upd_1: &msgs::ChannelUpdate, upd_2: &msgs::ChannelUpdate) {
818         nodes[a].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
819         let a_events = nodes[a].node.get_and_clear_pending_msg_events();
820         assert!(a_events.len() >= 2);
821
822         // ann should be re-generated by broadcast_node_announcement - check that we have it.
823         let mut found_ann_1 = false;
824         for event in a_events.iter() {
825                 match event {
826                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
827                                 if msg == ann { found_ann_1 = true; }
828                         },
829                         MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
830                         _ => panic!("Unexpected event {:?}", event),
831                 }
832         }
833         assert!(found_ann_1);
834
835         let a_node_announcement = match a_events.last().unwrap() {
836                 MessageSendEvent::BroadcastNodeAnnouncement { ref msg } => {
837                         (*msg).clone()
838                 },
839                 _ => panic!("Unexpected event"),
840         };
841
842         nodes[b].node.broadcast_node_announcement([1, 1, 1], [1; 32], Vec::new());
843         let b_events = nodes[b].node.get_and_clear_pending_msg_events();
844         assert!(b_events.len() >= 2);
845
846         // ann should be re-generated by broadcast_node_announcement - check that we have it.
847         let mut found_ann_2 = false;
848         for event in b_events.iter() {
849                 match event {
850                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
851                                 if msg == ann { found_ann_2 = true; }
852                         },
853                         MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
854                         _ => panic!("Unexpected event"),
855                 }
856         }
857         assert!(found_ann_2);
858
859         let b_node_announcement = match b_events.last().unwrap() {
860                 MessageSendEvent::BroadcastNodeAnnouncement { ref msg } => {
861                         (*msg).clone()
862                 },
863                 _ => panic!("Unexpected event"),
864         };
865
866         for node in nodes {
867                 assert!(node.net_graph_msg_handler.handle_channel_announcement(ann).unwrap());
868                 node.net_graph_msg_handler.handle_channel_update(upd_1).unwrap();
869                 node.net_graph_msg_handler.handle_channel_update(upd_2).unwrap();
870                 node.net_graph_msg_handler.handle_node_announcement(&a_node_announcement).unwrap();
871                 node.net_graph_msg_handler.handle_node_announcement(&b_node_announcement).unwrap();
872
873                 // Note that channel_updates are also delivered to ChannelManagers to ensure we have
874                 // forwarding info for local channels even if its not accepted in the network graph.
875                 node.node.handle_channel_update(&nodes[a].node.get_our_node_id(), &upd_1);
876                 node.node.handle_channel_update(&nodes[b].node.get_our_node_id(), &upd_2);
877         }
878 }
879
880 #[macro_export]
881 macro_rules! check_spends {
882         ($tx: expr, $($spends_txn: expr),*) => {
883                 {
884                         $(
885                         for outp in $spends_txn.output.iter() {
886                                 assert!(outp.value >= outp.script_pubkey.dust_value().as_sat(), "Input tx output didn't meet dust limit");
887                         }
888                         )*
889                         for outp in $tx.output.iter() {
890                                 assert!(outp.value >= outp.script_pubkey.dust_value().as_sat(), "Spending tx output didn't meet dust limit");
891                         }
892                         let get_output = |out_point: &bitcoin::blockdata::transaction::OutPoint| {
893                                 $(
894                                         if out_point.txid == $spends_txn.txid() {
895                                                 return $spends_txn.output.get(out_point.vout as usize).cloned()
896                                         }
897                                 )*
898                                 None
899                         };
900                         let mut total_value_in = 0;
901                         for input in $tx.input.iter() {
902                                 total_value_in += get_output(&input.previous_output).unwrap().value;
903                         }
904                         let mut total_value_out = 0;
905                         for output in $tx.output.iter() {
906                                 total_value_out += output.value;
907                         }
908                         let min_fee = ($tx.weight() as u64 + 3) / 4; // One sat per vbyte (ie per weight/4, rounded up)
909                         // Input amount - output amount = fee, so check that out + min_fee is smaller than input
910                         assert!(total_value_out + min_fee <= total_value_in);
911                         $tx.verify(get_output).unwrap();
912                 }
913         }
914 }
915
916 macro_rules! get_closing_signed_broadcast {
917         ($node: expr, $dest_pubkey: expr) => {
918                 {
919                         let events = $node.get_and_clear_pending_msg_events();
920                         assert!(events.len() == 1 || events.len() == 2);
921                         (match events[events.len() - 1] {
922                                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
923                                         assert_eq!(msg.contents.flags & 2, 2);
924                                         msg.clone()
925                                 },
926                                 _ => panic!("Unexpected event"),
927                         }, if events.len() == 2 {
928                                 match events[0] {
929                                         MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
930                                                 assert_eq!(*node_id, $dest_pubkey);
931                                                 Some(msg.clone())
932                                         },
933                                         _ => panic!("Unexpected event"),
934                                 }
935                         } else { None })
936                 }
937         }
938 }
939
940 #[cfg(test)]
941 macro_rules! check_warn_msg {
942         ($node: expr, $recipient_node_id: expr, $chan_id: expr) => {{
943                 let msg_events = $node.node.get_and_clear_pending_msg_events();
944                 assert_eq!(msg_events.len(), 1);
945                 match msg_events[0] {
946                         MessageSendEvent::HandleError { action: ErrorAction::SendWarningMessage { ref msg, log_level: _ }, node_id } => {
947                                 assert_eq!(node_id, $recipient_node_id);
948                                 assert_eq!(msg.channel_id, $chan_id);
949                                 msg.data.clone()
950                         },
951                         _ => panic!("Unexpected event"),
952                 }
953         }}
954 }
955
956 /// Check that a channel's closing channel update has been broadcasted, and optionally
957 /// check whether an error message event has occurred.
958 #[macro_export]
959 macro_rules! check_closed_broadcast {
960         ($node: expr, $with_error_msg: expr) => {{
961                 use $crate::util::events::MessageSendEvent;
962                 use $crate::ln::msgs::ErrorAction;
963
964                 let msg_events = $node.node.get_and_clear_pending_msg_events();
965                 assert_eq!(msg_events.len(), if $with_error_msg { 2 } else { 1 });
966                 match msg_events[0] {
967                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
968                                 assert_eq!(msg.contents.flags & 2, 2);
969                         },
970                         _ => panic!("Unexpected event"),
971                 }
972                 if $with_error_msg {
973                         match msg_events[1] {
974                                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
975                                         // TODO: Check node_id
976                                         Some(msg.clone())
977                                 },
978                                 _ => panic!("Unexpected event"),
979                         }
980                 } else { None }
981         }}
982 }
983
984 /// Check that a channel's closing channel events has been issued
985 #[macro_export]
986 macro_rules! check_closed_event {
987         ($node: expr, $events: expr, $reason: expr) => {
988                 check_closed_event!($node, $events, $reason, false);
989         };
990         ($node: expr, $events: expr, $reason: expr, $is_check_discard_funding: expr) => {{
991                 use $crate::util::events::Event;
992
993                 let events = $node.node.get_and_clear_pending_events();
994                 assert_eq!(events.len(), $events);
995                 let expected_reason = $reason;
996                 let mut issues_discard_funding = false;
997                 for event in events {
998                         match event {
999                                 Event::ChannelClosed { ref reason, .. } => {
1000                                         assert_eq!(*reason, expected_reason);
1001                                 },
1002                                 Event::DiscardFunding { .. } => {
1003                                         issues_discard_funding = true;
1004                                 }
1005                                 _ => panic!("Unexpected event"),
1006                         }
1007                 }
1008                 assert_eq!($is_check_discard_funding, issues_discard_funding);
1009         }}
1010 }
1011
1012 pub fn close_channel<'a, 'b, 'c>(outbound_node: &Node<'a, 'b, 'c>, inbound_node: &Node<'a, 'b, 'c>, channel_id: &[u8; 32], funding_tx: Transaction, close_inbound_first: bool) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, Transaction) {
1013         let (node_a, broadcaster_a, struct_a) = if close_inbound_first { (&inbound_node.node, &inbound_node.tx_broadcaster, inbound_node) } else { (&outbound_node.node, &outbound_node.tx_broadcaster, outbound_node) };
1014         let (node_b, broadcaster_b, struct_b) = if close_inbound_first { (&outbound_node.node, &outbound_node.tx_broadcaster, outbound_node) } else { (&inbound_node.node, &inbound_node.tx_broadcaster, inbound_node) };
1015         let (tx_a, tx_b);
1016
1017         node_a.close_channel(channel_id).unwrap();
1018         node_b.handle_shutdown(&node_a.get_our_node_id(), &InitFeatures::known(), &get_event_msg!(struct_a, MessageSendEvent::SendShutdown, node_b.get_our_node_id()));
1019
1020         let events_1 = node_b.get_and_clear_pending_msg_events();
1021         assert!(events_1.len() >= 1);
1022         let shutdown_b = match events_1[0] {
1023                 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
1024                         assert_eq!(node_id, &node_a.get_our_node_id());
1025                         msg.clone()
1026                 },
1027                 _ => panic!("Unexpected event"),
1028         };
1029
1030         let closing_signed_b = if !close_inbound_first {
1031                 assert_eq!(events_1.len(), 1);
1032                 None
1033         } else {
1034                 Some(match events_1[1] {
1035                         MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
1036                                 assert_eq!(node_id, &node_a.get_our_node_id());
1037                                 msg.clone()
1038                         },
1039                         _ => panic!("Unexpected event"),
1040                 })
1041         };
1042
1043         node_a.handle_shutdown(&node_b.get_our_node_id(), &InitFeatures::known(), &shutdown_b);
1044         let (as_update, bs_update) = if close_inbound_first {
1045                 assert!(node_a.get_and_clear_pending_msg_events().is_empty());
1046                 node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap());
1047
1048                 node_b.handle_closing_signed(&node_a.get_our_node_id(), &get_event_msg!(struct_a, MessageSendEvent::SendClosingSigned, node_b.get_our_node_id()));
1049                 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
1050                 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
1051                 let (bs_update, closing_signed_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
1052
1053                 node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap());
1054                 let (as_update, none_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
1055                 assert!(none_a.is_none());
1056                 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
1057                 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
1058                 (as_update, bs_update)
1059         } else {
1060                 let closing_signed_a = get_event_msg!(struct_a, MessageSendEvent::SendClosingSigned, node_b.get_our_node_id());
1061
1062                 node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a);
1063                 node_a.handle_closing_signed(&node_b.get_our_node_id(), &get_event_msg!(struct_b, MessageSendEvent::SendClosingSigned, node_a.get_our_node_id()));
1064
1065                 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
1066                 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
1067                 let (as_update, closing_signed_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
1068
1069                 node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap());
1070                 let (bs_update, none_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
1071                 assert!(none_b.is_none());
1072                 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
1073                 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
1074                 (as_update, bs_update)
1075         };
1076         assert_eq!(tx_a, tx_b);
1077         check_spends!(tx_a, funding_tx);
1078
1079         (as_update, bs_update, tx_a)
1080 }
1081
1082 pub struct SendEvent {
1083         pub node_id: PublicKey,
1084         pub msgs: Vec<msgs::UpdateAddHTLC>,
1085         pub commitment_msg: msgs::CommitmentSigned,
1086 }
1087 impl SendEvent {
1088         pub fn from_commitment_update(node_id: PublicKey, updates: msgs::CommitmentUpdate) -> SendEvent {
1089                 assert!(updates.update_fulfill_htlcs.is_empty());
1090                 assert!(updates.update_fail_htlcs.is_empty());
1091                 assert!(updates.update_fail_malformed_htlcs.is_empty());
1092                 assert!(updates.update_fee.is_none());
1093                 SendEvent { node_id: node_id, msgs: updates.update_add_htlcs, commitment_msg: updates.commitment_signed }
1094         }
1095
1096         pub fn from_event(event: MessageSendEvent) -> SendEvent {
1097                 match event {
1098                         MessageSendEvent::UpdateHTLCs { node_id, updates } => SendEvent::from_commitment_update(node_id, updates),
1099                         _ => panic!("Unexpected event type!"),
1100                 }
1101         }
1102
1103         pub fn from_node<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>) -> SendEvent {
1104                 let mut events = node.node.get_and_clear_pending_msg_events();
1105                 assert_eq!(events.len(), 1);
1106                 SendEvent::from_event(events.pop().unwrap())
1107         }
1108 }
1109
1110 #[macro_export]
1111 /// Performs the "commitment signed dance" - the series of message exchanges which occur after a
1112 /// commitment update.
1113 macro_rules! commitment_signed_dance {
1114         ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */) => {
1115                 {
1116                         check_added_monitors!($node_a, 0);
1117                         assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
1118                         $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed);
1119                         check_added_monitors!($node_a, 1);
1120                         commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, false);
1121                 }
1122         };
1123         ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */, true /* return last RAA */) => {
1124                 {
1125                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!($node_a, $node_b.node.get_our_node_id());
1126                         check_added_monitors!($node_b, 0);
1127                         assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
1128                         $node_b.node.handle_revoke_and_ack(&$node_a.node.get_our_node_id(), &as_revoke_and_ack);
1129                         assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
1130                         check_added_monitors!($node_b, 1);
1131                         $node_b.node.handle_commitment_signed(&$node_a.node.get_our_node_id(), &as_commitment_signed);
1132                         let (bs_revoke_and_ack, extra_msg_option) = {
1133                                 let events = $node_b.node.get_and_clear_pending_msg_events();
1134                                 assert!(events.len() <= 2);
1135                                 (match events[0] {
1136                                         MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
1137                                                 assert_eq!(*node_id, $node_a.node.get_our_node_id());
1138                                                 (*msg).clone()
1139                                         },
1140                                         _ => panic!("Unexpected event"),
1141                                 }, events.get(1).map(|e| e.clone()))
1142                         };
1143                         check_added_monitors!($node_b, 1);
1144                         if $fail_backwards {
1145                                 assert!($node_a.node.get_and_clear_pending_events().is_empty());
1146                                 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
1147                         }
1148                         (extra_msg_option, bs_revoke_and_ack)
1149                 }
1150         };
1151         ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */, false /* return extra message */, true /* return last RAA */) => {
1152                 {
1153                         check_added_monitors!($node_a, 0);
1154                         assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
1155                         $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed);
1156                         check_added_monitors!($node_a, 1);
1157                         let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
1158                         assert!(extra_msg_option.is_none());
1159                         bs_revoke_and_ack
1160                 }
1161         };
1162         ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */) => {
1163                 {
1164                         let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
1165                         $node_a.node.handle_revoke_and_ack(&$node_b.node.get_our_node_id(), &bs_revoke_and_ack);
1166                         check_added_monitors!($node_a, 1);
1167                         extra_msg_option
1168                 }
1169         };
1170         ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, false /* no extra message */) => {
1171                 {
1172                         assert!(commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true).is_none());
1173                 }
1174         };
1175         ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr) => {
1176                 {
1177                         commitment_signed_dance!($node_a, $node_b, $commitment_signed, $fail_backwards, true);
1178                         if $fail_backwards {
1179                                 $crate::expect_pending_htlcs_forwardable!($node_a);
1180                                 check_added_monitors!($node_a, 1);
1181
1182                                 let channel_state = $node_a.node.channel_state.lock().unwrap();
1183                                 assert_eq!(channel_state.pending_msg_events.len(), 1);
1184                                 if let MessageSendEvent::UpdateHTLCs { ref node_id, .. } = channel_state.pending_msg_events[0] {
1185                                         assert_ne!(*node_id, $node_b.node.get_our_node_id());
1186                                 } else { panic!("Unexpected event"); }
1187                         } else {
1188                                 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
1189                         }
1190                 }
1191         }
1192 }
1193
1194 /// Get a payment preimage and hash.
1195 #[macro_export]
1196 macro_rules! get_payment_preimage_hash {
1197         ($dest_node: expr) => {
1198                 {
1199                         get_payment_preimage_hash!($dest_node, None)
1200                 }
1201         };
1202         ($dest_node: expr, $min_value_msat: expr) => {
1203                 {
1204                         use bitcoin::hashes::Hash as _;
1205                         let mut payment_count = $dest_node.network_payment_count.borrow_mut();
1206                         let payment_preimage = $crate::ln::PaymentPreimage([*payment_count; 32]);
1207                         *payment_count += 1;
1208                         let payment_hash = $crate::ln::PaymentHash(
1209                                 bitcoin::hashes::sha256::Hash::hash(&payment_preimage.0[..]).into_inner());
1210                         let payment_secret = $dest_node.node.create_inbound_payment_for_hash(payment_hash, $min_value_msat, 7200).unwrap();
1211                         (payment_preimage, payment_hash, payment_secret)
1212                 }
1213         }
1214 }
1215
1216 #[macro_export]
1217 macro_rules! get_route {
1218         ($send_node: expr, $payment_params: expr, $recv_value: expr, $cltv: expr) => {{
1219                 use $crate::chain::keysinterface::KeysInterface;
1220                 let scorer = $crate::util::test_utils::TestScorer::with_penalty(0);
1221                 let keys_manager = $crate::util::test_utils::TestKeysInterface::new(&[0u8; 32], bitcoin::network::constants::Network::Testnet);
1222                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
1223                 $crate::routing::router::get_route(
1224                         &$send_node.node.get_our_node_id(), &$payment_params, &$send_node.network_graph.read_only(),
1225                         Some(&$send_node.node.list_usable_channels().iter().collect::<Vec<_>>()),
1226                         $recv_value, $cltv, $send_node.logger, &scorer, &random_seed_bytes
1227                 )
1228         }}
1229 }
1230
1231 #[cfg(test)]
1232 #[macro_export]
1233 macro_rules! get_route_and_payment_hash {
1234         ($send_node: expr, $recv_node: expr, $recv_value: expr) => {{
1235                 let payment_params = $crate::routing::router::PaymentParameters::from_node_id($recv_node.node.get_our_node_id())
1236                         .with_features($crate::ln::features::InvoiceFeatures::known());
1237                 $crate::get_route_and_payment_hash!($send_node, $recv_node, payment_params, $recv_value, TEST_FINAL_CLTV)
1238         }};
1239         ($send_node: expr, $recv_node: expr, $payment_params: expr, $recv_value: expr, $cltv: expr) => {{
1240                 let (payment_preimage, payment_hash, payment_secret) = $crate::get_payment_preimage_hash!($recv_node, Some($recv_value));
1241                 let route = $crate::get_route!($send_node, $payment_params, $recv_value, $cltv);
1242                 (route.unwrap(), payment_hash, payment_preimage, payment_secret)
1243         }}
1244 }
1245
1246 #[macro_export]
1247 /// Clears (and ignores) a PendingHTLCsForwardable event
1248 macro_rules! expect_pending_htlcs_forwardable_ignore {
1249         ($node: expr) => {{
1250                 let events = $node.node.get_and_clear_pending_events();
1251                 assert_eq!(events.len(), 1);
1252                 match events[0] {
1253                         $crate::util::events::Event::PendingHTLCsForwardable { .. } => { },
1254                         _ => panic!("Unexpected event"),
1255                 };
1256         }}
1257 }
1258
1259 #[macro_export]
1260 /// Handles a PendingHTLCsForwardable event
1261 macro_rules! expect_pending_htlcs_forwardable {
1262         ($node: expr) => {{
1263                 $crate::expect_pending_htlcs_forwardable_ignore!($node);
1264                 $node.node.process_pending_htlc_forwards();
1265
1266                 // Ensure process_pending_htlc_forwards is idempotent.
1267                 $node.node.process_pending_htlc_forwards();
1268         }}
1269 }
1270
1271 #[cfg(test)]
1272 macro_rules! expect_pending_htlcs_forwardable_from_events {
1273         ($node: expr, $events: expr, $ignore: expr) => {{
1274                 assert_eq!($events.len(), 1);
1275                 match $events[0] {
1276                         Event::PendingHTLCsForwardable { .. } => { },
1277                         _ => panic!("Unexpected event"),
1278                 };
1279                 if $ignore {
1280                         $node.node.process_pending_htlc_forwards();
1281
1282                         // Ensure process_pending_htlc_forwards is idempotent.
1283                         $node.node.process_pending_htlc_forwards();
1284                 }
1285         }}
1286 }
1287
1288 #[macro_export]
1289 #[cfg(any(test, feature = "_bench_unstable", feature = "_test_utils"))]
1290 macro_rules! expect_payment_received {
1291         ($node: expr, $expected_payment_hash: expr, $expected_payment_secret: expr, $expected_recv_value: expr) => {
1292                 expect_payment_received!($node, $expected_payment_hash, $expected_payment_secret, $expected_recv_value, None)
1293         };
1294         ($node: expr, $expected_payment_hash: expr, $expected_payment_secret: expr, $expected_recv_value: expr, $expected_payment_preimage: expr) => {
1295                 let events = $node.node.get_and_clear_pending_events();
1296                 assert_eq!(events.len(), 1);
1297                 match events[0] {
1298                         $crate::util::events::Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1299                                 assert_eq!($expected_payment_hash, *payment_hash);
1300                                 assert_eq!($expected_recv_value, amt);
1301                                 match purpose {
1302                                         $crate::util::events::PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1303                                                 assert_eq!(&$expected_payment_preimage, payment_preimage);
1304                                                 assert_eq!($expected_payment_secret, *payment_secret);
1305                                         },
1306                                         _ => {},
1307                                 }
1308                         },
1309                         _ => panic!("Unexpected event"),
1310                 }
1311         }
1312 }
1313
1314 #[cfg(test)]
1315 #[macro_export]
1316 macro_rules! expect_payment_sent_without_paths {
1317         ($node: expr, $expected_payment_preimage: expr) => {
1318                 expect_payment_sent!($node, $expected_payment_preimage, None::<u64>, false);
1319         };
1320         ($node: expr, $expected_payment_preimage: expr, $expected_fee_msat_opt: expr) => {
1321                 expect_payment_sent!($node, $expected_payment_preimage, $expected_fee_msat_opt, false);
1322         }
1323 }
1324
1325 #[macro_export]
1326 macro_rules! expect_payment_sent {
1327         ($node: expr, $expected_payment_preimage: expr) => {
1328                 $crate::expect_payment_sent!($node, $expected_payment_preimage, None::<u64>, true);
1329         };
1330         ($node: expr, $expected_payment_preimage: expr, $expected_fee_msat_opt: expr) => {
1331                 $crate::expect_payment_sent!($node, $expected_payment_preimage, $expected_fee_msat_opt, true);
1332         };
1333         ($node: expr, $expected_payment_preimage: expr, $expected_fee_msat_opt: expr, $expect_paths: expr) => { {
1334                 use bitcoin::hashes::Hash as _;
1335                 let events = $node.node.get_and_clear_pending_events();
1336                 let expected_payment_hash = $crate::ln::PaymentHash(
1337                         bitcoin::hashes::sha256::Hash::hash(&$expected_payment_preimage.0).into_inner());
1338                 if $expect_paths {
1339                         assert!(events.len() > 1);
1340                 } else {
1341                         assert_eq!(events.len(), 1);
1342                 }
1343                 let expected_payment_id = match events[0] {
1344                         $crate::util::events::Event::PaymentSent { ref payment_id, ref payment_preimage, ref payment_hash, ref fee_paid_msat } => {
1345                                 assert_eq!($expected_payment_preimage, *payment_preimage);
1346                                 assert_eq!(expected_payment_hash, *payment_hash);
1347                                 assert!(fee_paid_msat.is_some());
1348                                 if $expected_fee_msat_opt.is_some() {
1349                                         assert_eq!(*fee_paid_msat, $expected_fee_msat_opt);
1350                                 }
1351                                 payment_id.unwrap()
1352                         },
1353                         _ => panic!("Unexpected event"),
1354                 };
1355                 if $expect_paths {
1356                         for i in 1..events.len() {
1357                                 match events[i] {
1358                                         $crate::util::events::Event::PaymentPathSuccessful { payment_id, payment_hash, .. } => {
1359                                                 assert_eq!(payment_id, expected_payment_id);
1360                                                 assert_eq!(payment_hash, Some(expected_payment_hash));
1361                                         },
1362                                         _ => panic!("Unexpected event"),
1363                                 }
1364                         }
1365                 }
1366         } }
1367 }
1368
1369 #[cfg(test)]
1370 #[macro_export]
1371 macro_rules! expect_payment_path_successful {
1372         ($node: expr) => {
1373                 let events = $node.node.get_and_clear_pending_events();
1374                 assert_eq!(events.len(), 1);
1375                 match events[0] {
1376                         $crate::util::events::Event::PaymentPathSuccessful { .. } => {},
1377                         _ => panic!("Unexpected event"),
1378                 }
1379         }
1380 }
1381
1382 macro_rules! expect_payment_forwarded {
1383         ($node: expr, $source_node: expr, $expected_fee: expr, $upstream_force_closed: expr) => {
1384                 let events = $node.node.get_and_clear_pending_events();
1385                 assert_eq!(events.len(), 1);
1386                 match events[0] {
1387                         Event::PaymentForwarded { fee_earned_msat, source_channel_id, claim_from_onchain_tx } => {
1388                                 assert_eq!(fee_earned_msat, $expected_fee);
1389                                 if fee_earned_msat.is_some() {
1390                                         // Is the event channel_id in one of the channels between the two nodes?
1391                                         assert!($node.node.list_channels().iter().any(|x| x.counterparty.node_id == $source_node.node.get_our_node_id() && x.channel_id == source_channel_id.unwrap()));
1392                                 }
1393                                 assert_eq!(claim_from_onchain_tx, $upstream_force_closed);
1394                         },
1395                         _ => panic!("Unexpected event"),
1396                 }
1397         }
1398 }
1399
1400 pub struct PaymentFailedConditions<'a> {
1401         pub(crate) expected_htlc_error_data: Option<(u16, &'a [u8])>,
1402         pub(crate) expected_blamed_scid: Option<u64>,
1403         pub(crate) expected_blamed_chan_closed: Option<bool>,
1404         pub(crate) expected_mpp_parts_remain: bool,
1405 }
1406
1407 impl<'a> PaymentFailedConditions<'a> {
1408         pub fn new() -> Self {
1409                 Self {
1410                         expected_htlc_error_data: None,
1411                         expected_blamed_scid: None,
1412                         expected_blamed_chan_closed: None,
1413                         expected_mpp_parts_remain: false,
1414                 }
1415         }
1416         pub fn mpp_parts_remain(mut self) -> Self {
1417                 self.expected_mpp_parts_remain = true;
1418                 self
1419         }
1420         pub fn blamed_scid(mut self, scid: u64) -> Self {
1421                 self.expected_blamed_scid = Some(scid);
1422                 self
1423         }
1424         pub fn blamed_chan_closed(mut self, closed: bool) -> Self {
1425                 self.expected_blamed_chan_closed = Some(closed);
1426                 self
1427         }
1428         pub fn expected_htlc_error_data(mut self, code: u16, data: &'a [u8]) -> Self {
1429                 self.expected_htlc_error_data = Some((code, data));
1430                 self
1431         }
1432 }
1433
1434 #[cfg(test)]
1435 macro_rules! expect_payment_failed_with_update {
1436         ($node: expr, $expected_payment_hash: expr, $rejected_by_dest: expr, $scid: expr, $chan_closed: expr) => {
1437                 expect_payment_failed_conditions!($node, $expected_payment_hash, $rejected_by_dest,
1438                         $crate::ln::functional_test_utils::PaymentFailedConditions::new().blamed_scid($scid).blamed_chan_closed($chan_closed));
1439         }
1440 }
1441
1442 #[cfg(test)]
1443 macro_rules! expect_payment_failed {
1444         ($node: expr, $expected_payment_hash: expr, $rejected_by_dest: expr $(, $expected_error_code: expr, $expected_error_data: expr)*) => {
1445                 #[allow(unused_mut)]
1446                 let mut conditions = $crate::ln::functional_test_utils::PaymentFailedConditions::new();
1447                 $(
1448                         conditions = conditions.expected_htlc_error_data($expected_error_code, &$expected_error_data);
1449                 )*
1450                 expect_payment_failed_conditions!($node, $expected_payment_hash, $rejected_by_dest, conditions);
1451         };
1452 }
1453
1454 #[cfg(test)]
1455 macro_rules! expect_payment_failed_conditions {
1456         ($node: expr, $expected_payment_hash: expr, $rejected_by_dest: expr, $conditions: expr) => {
1457                 let events = $node.node.get_and_clear_pending_events();
1458                 assert_eq!(events.len(), 1);
1459                 let expected_payment_id = match events[0] {
1460                         Event::PaymentPathFailed { ref payment_hash, rejected_by_dest, ref error_code, ref error_data, ref path, ref retry, ref payment_id, ref network_update, .. } => {
1461                                 assert_eq!(*payment_hash, $expected_payment_hash, "unexpected payment_hash");
1462                                 assert_eq!(rejected_by_dest, $rejected_by_dest, "unexpected rejected_by_dest value");
1463                                 assert!(retry.is_some(), "expected retry.is_some()");
1464                                 assert_eq!(retry.as_ref().unwrap().final_value_msat, path.last().unwrap().fee_msat, "Retry amount should match last hop in path");
1465                                 assert_eq!(retry.as_ref().unwrap().payment_params.payee_pubkey, path.last().unwrap().pubkey, "Retry payee node_id should match last hop in path");
1466
1467                                 assert!(error_code.is_some(), "expected error_code.is_some() = true");
1468                                 assert!(error_data.is_some(), "expected error_data.is_some() = true");
1469                                 if let Some((code, data)) = $conditions.expected_htlc_error_data {
1470                                         assert_eq!(error_code.unwrap(), code, "unexpected error code");
1471                                         assert_eq!(&error_data.as_ref().unwrap()[..], data, "unexpected error data");
1472                                 }
1473
1474                                 if let Some(chan_closed) = $conditions.expected_blamed_chan_closed {
1475                                         match network_update {
1476                                                 &Some($crate::routing::network_graph::NetworkUpdate::ChannelUpdateMessage { ref msg }) if !chan_closed => {
1477                                                         if let Some(scid) = $conditions.expected_blamed_scid {
1478                                                                 assert_eq!(msg.contents.short_channel_id, scid);
1479                                                         }
1480                                                         assert_eq!(msg.contents.flags & 2, 0);
1481                                                 },
1482                                                 &Some($crate::routing::network_graph::NetworkUpdate::ChannelClosed { short_channel_id, is_permanent }) if chan_closed => {
1483                                                         if let Some(scid) = $conditions.expected_blamed_scid {
1484                                                                 assert_eq!(short_channel_id, scid);
1485                                                         }
1486                                                         assert!(is_permanent);
1487                                                 },
1488                                                 Some(_) => panic!("Unexpected update type"),
1489                                                 None => panic!("Expected update"),
1490                                         }
1491                                 }
1492
1493                                 payment_id.unwrap()
1494                         },
1495                         _ => panic!("Unexpected event"),
1496                 };
1497                 if !$conditions.expected_mpp_parts_remain {
1498                         $node.node.abandon_payment(expected_payment_id);
1499                         let events = $node.node.get_and_clear_pending_events();
1500                         assert_eq!(events.len(), 1);
1501                         match events[0] {
1502                                 Event::PaymentFailed { ref payment_hash, ref payment_id } => {
1503                                         assert_eq!(*payment_hash, $expected_payment_hash, "unexpected second payment_hash");
1504                                         assert_eq!(*payment_id, expected_payment_id);
1505                                 }
1506                                 _ => panic!("Unexpected second event"),
1507                         }
1508                 }
1509         }
1510 }
1511
1512 pub fn send_along_route_with_secret<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, route: Route, expected_paths: &[&[&Node<'a, 'b, 'c>]], recv_value: u64, our_payment_hash: PaymentHash, our_payment_secret: PaymentSecret) -> PaymentId {
1513         let payment_id = origin_node.node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
1514         check_added_monitors!(origin_node, expected_paths.len());
1515         pass_along_route(origin_node, expected_paths, recv_value, our_payment_hash, our_payment_secret);
1516         payment_id
1517 }
1518
1519 pub fn pass_along_path<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_path: &[&Node<'a, 'b, 'c>], recv_value: u64, our_payment_hash: PaymentHash, our_payment_secret: Option<PaymentSecret>, ev: MessageSendEvent, payment_received_expected: bool, expected_preimage: Option<PaymentPreimage>) {
1520         let mut payment_event = SendEvent::from_event(ev);
1521         let mut prev_node = origin_node;
1522
1523         for (idx, &node) in expected_path.iter().enumerate() {
1524                 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
1525
1526                 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
1527                 check_added_monitors!(node, 0);
1528                 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
1529
1530                 expect_pending_htlcs_forwardable!(node);
1531
1532                 if idx == expected_path.len() - 1 {
1533                         let events_2 = node.node.get_and_clear_pending_events();
1534                         if payment_received_expected {
1535                                 assert_eq!(events_2.len(), 1);
1536                                 match events_2[0] {
1537                                         Event::PaymentReceived { ref payment_hash, ref purpose, amt} => {
1538                                                 assert_eq!(our_payment_hash, *payment_hash);
1539                                                 match &purpose {
1540                                                         PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1541                                                                 assert_eq!(expected_preimage, *payment_preimage);
1542                                                                 assert_eq!(our_payment_secret.unwrap(), *payment_secret);
1543                                                         },
1544                                                         PaymentPurpose::SpontaneousPayment(payment_preimage) => {
1545                                                                 assert_eq!(expected_preimage.unwrap(), *payment_preimage);
1546                                                                 assert!(our_payment_secret.is_none());
1547                                                         },
1548                                                 }
1549                                                 assert_eq!(amt, recv_value);
1550                                         },
1551                                         _ => panic!("Unexpected event"),
1552                                 }
1553                         } else {
1554                                 assert!(events_2.is_empty());
1555                         }
1556                 } else {
1557                         let mut events_2 = node.node.get_and_clear_pending_msg_events();
1558                         assert_eq!(events_2.len(), 1);
1559                         check_added_monitors!(node, 1);
1560                         payment_event = SendEvent::from_event(events_2.remove(0));
1561                         assert_eq!(payment_event.msgs.len(), 1);
1562                 }
1563
1564                 prev_node = node;
1565         }
1566 }
1567
1568 pub fn pass_along_route<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_route: &[&[&Node<'a, 'b, 'c>]], recv_value: u64, our_payment_hash: PaymentHash, our_payment_secret: PaymentSecret) {
1569         let mut events = origin_node.node.get_and_clear_pending_msg_events();
1570         assert_eq!(events.len(), expected_route.len());
1571         for (path_idx, (ev, expected_path)) in events.drain(..).zip(expected_route.iter()).enumerate() {
1572                 // Once we've gotten through all the HTLCs, the last one should result in a
1573                 // PaymentReceived (but each previous one should not!), .
1574                 let expect_payment = path_idx == expected_route.len() - 1;
1575                 pass_along_path(origin_node, expected_path, recv_value, our_payment_hash.clone(), Some(our_payment_secret), ev, expect_payment, None);
1576         }
1577 }
1578
1579 pub fn send_along_route<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, route: Route, expected_route: &[&Node<'a, 'b, 'c>], recv_value: u64) -> (PaymentPreimage, PaymentHash, PaymentSecret, PaymentId) {
1580         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(expected_route.last().unwrap());
1581         let payment_id = send_along_route_with_secret(origin_node, route, &[expected_route], recv_value, our_payment_hash, our_payment_secret);
1582         (our_payment_preimage, our_payment_hash, our_payment_secret, payment_id)
1583 }
1584
1585 pub fn do_claim_payment_along_route<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_paths: &[&[&Node<'a, 'b, 'c>]], skip_last: bool, our_payment_preimage: PaymentPreimage) -> u64 {
1586         for path in expected_paths.iter() {
1587                 assert_eq!(path.last().unwrap().node.get_our_node_id(), expected_paths[0].last().unwrap().node.get_our_node_id());
1588         }
1589         assert!(expected_paths[0].last().unwrap().node.claim_funds(our_payment_preimage));
1590         check_added_monitors!(expected_paths[0].last().unwrap(), expected_paths.len());
1591
1592         let mut expected_total_fee_msat = 0;
1593
1594         macro_rules! msgs_from_ev {
1595                 ($ev: expr) => {
1596                         match $ev {
1597                                 &MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
1598                                         assert!(update_add_htlcs.is_empty());
1599                                         assert_eq!(update_fulfill_htlcs.len(), 1);
1600                                         assert!(update_fail_htlcs.is_empty());
1601                                         assert!(update_fail_malformed_htlcs.is_empty());
1602                                         assert!(update_fee.is_none());
1603                                         ((update_fulfill_htlcs[0].clone(), commitment_signed.clone()), node_id.clone())
1604                                 },
1605                                 _ => panic!("Unexpected event"),
1606                         }
1607                 }
1608         }
1609         let mut per_path_msgs: Vec<((msgs::UpdateFulfillHTLC, msgs::CommitmentSigned), PublicKey)> = Vec::with_capacity(expected_paths.len());
1610         let events = expected_paths[0].last().unwrap().node.get_and_clear_pending_msg_events();
1611         assert_eq!(events.len(), expected_paths.len());
1612         for ev in events.iter() {
1613                 per_path_msgs.push(msgs_from_ev!(ev));
1614         }
1615
1616         for (expected_route, (path_msgs, next_hop)) in expected_paths.iter().zip(per_path_msgs.drain(..)) {
1617                 let mut next_msgs = Some(path_msgs);
1618                 let mut expected_next_node = next_hop;
1619
1620                 macro_rules! last_update_fulfill_dance {
1621                         ($node: expr, $prev_node: expr) => {
1622                                 {
1623                                         $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0);
1624                                         check_added_monitors!($node, 0);
1625                                         assert!($node.node.get_and_clear_pending_msg_events().is_empty());
1626                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
1627                                 }
1628                         }
1629                 }
1630                 macro_rules! mid_update_fulfill_dance {
1631                         ($node: expr, $prev_node: expr, $next_node: expr, $new_msgs: expr) => {
1632                                 {
1633                                         $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0);
1634                                         let fee = $node.node.channel_state.lock().unwrap().by_id.get(&next_msgs.as_ref().unwrap().0.channel_id).unwrap().config.forwarding_fee_base_msat;
1635                                         expect_payment_forwarded!($node, $next_node, Some(fee as u64), false);
1636                                         expected_total_fee_msat += fee as u64;
1637                                         check_added_monitors!($node, 1);
1638                                         let new_next_msgs = if $new_msgs {
1639                                                 let events = $node.node.get_and_clear_pending_msg_events();
1640                                                 assert_eq!(events.len(), 1);
1641                                                 let (res, nexthop) = msgs_from_ev!(&events[0]);
1642                                                 expected_next_node = nexthop;
1643                                                 Some(res)
1644                                         } else {
1645                                                 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
1646                                                 None
1647                                         };
1648                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
1649                                         next_msgs = new_next_msgs;
1650                                 }
1651                         }
1652                 }
1653
1654                 let mut prev_node = expected_route.last().unwrap();
1655                 for (idx, node) in expected_route.iter().rev().enumerate().skip(1) {
1656                         assert_eq!(expected_next_node, node.node.get_our_node_id());
1657                         let update_next_msgs = !skip_last || idx != expected_route.len() - 1;
1658                         if next_msgs.is_some() {
1659                                 // Since we are traversing in reverse, next_node is actually the previous node
1660                                 let next_node: &Node;
1661                                 if idx == expected_route.len() - 1 {
1662                                         next_node = origin_node;
1663                                 } else {
1664                                         next_node = expected_route[expected_route.len() - 1 - idx - 1];
1665                                 }
1666                                 mid_update_fulfill_dance!(node, prev_node, next_node, update_next_msgs);
1667                         } else {
1668                                 assert!(!update_next_msgs);
1669                                 assert!(node.node.get_and_clear_pending_msg_events().is_empty());
1670                         }
1671                         if !skip_last && idx == expected_route.len() - 1 {
1672                                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
1673                         }
1674
1675                         prev_node = node;
1676                 }
1677
1678                 if !skip_last {
1679                         last_update_fulfill_dance!(origin_node, expected_route.first().unwrap());
1680                 }
1681         }
1682
1683         // Ensure that claim_funds is idempotent.
1684         assert!(!expected_paths[0].last().unwrap().node.claim_funds(our_payment_preimage));
1685         assert!(expected_paths[0].last().unwrap().node.get_and_clear_pending_msg_events().is_empty());
1686         check_added_monitors!(expected_paths[0].last().unwrap(), 0);
1687
1688         expected_total_fee_msat
1689 }
1690 pub fn claim_payment_along_route<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_paths: &[&[&Node<'a, 'b, 'c>]], skip_last: bool, our_payment_preimage: PaymentPreimage) {
1691         let expected_total_fee_msat = do_claim_payment_along_route(origin_node, expected_paths, skip_last, our_payment_preimage);
1692         if !skip_last {
1693                 expect_payment_sent!(origin_node, our_payment_preimage, Some(expected_total_fee_msat));
1694         }
1695 }
1696
1697 pub fn claim_payment<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_route: &[&Node<'a, 'b, 'c>], our_payment_preimage: PaymentPreimage) {
1698         claim_payment_along_route(origin_node, &[expected_route], false, our_payment_preimage);
1699 }
1700
1701 pub const TEST_FINAL_CLTV: u32 = 70;
1702
1703 pub fn route_payment<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_route: &[&Node<'a, 'b, 'c>], recv_value: u64) -> (PaymentPreimage, PaymentHash, PaymentSecret) {
1704         let payment_params = PaymentParameters::from_node_id(expected_route.last().unwrap().node.get_our_node_id())
1705                 .with_features(InvoiceFeatures::known());
1706         let route = get_route!(origin_node, payment_params, recv_value, TEST_FINAL_CLTV).unwrap();
1707         assert_eq!(route.paths.len(), 1);
1708         assert_eq!(route.paths[0].len(), expected_route.len());
1709         for (node, hop) in expected_route.iter().zip(route.paths[0].iter()) {
1710                 assert_eq!(hop.pubkey, node.node.get_our_node_id());
1711         }
1712
1713         let res = send_along_route(origin_node, route, expected_route, recv_value);
1714         (res.0, res.1, res.2)
1715 }
1716
1717 pub fn route_over_limit<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_route: &[&Node<'a, 'b, 'c>], recv_value: u64)  {
1718         let payment_params = PaymentParameters::from_node_id(expected_route.last().unwrap().node.get_our_node_id())
1719                 .with_features(InvoiceFeatures::known());
1720         let network_graph = origin_node.network_graph.read_only();
1721         let scorer = test_utils::TestScorer::with_penalty(0);
1722         let seed = [0u8; 32];
1723         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
1724         let random_seed_bytes = keys_manager.get_secure_random_bytes();
1725         let route = get_route(
1726                 &origin_node.node.get_our_node_id(), &payment_params, &network_graph,
1727                 None, recv_value, TEST_FINAL_CLTV, origin_node.logger, &scorer, &random_seed_bytes).unwrap();
1728         assert_eq!(route.paths.len(), 1);
1729         assert_eq!(route.paths[0].len(), expected_route.len());
1730         for (node, hop) in expected_route.iter().zip(route.paths[0].iter()) {
1731                 assert_eq!(hop.pubkey, node.node.get_our_node_id());
1732         }
1733
1734         let (_, our_payment_hash, our_payment_preimage) = get_payment_preimage_hash!(expected_route.last().unwrap());
1735         unwrap_send_err!(origin_node.node.send_payment(&route, our_payment_hash, &Some(our_payment_preimage)), true, APIError::ChannelUnavailable { ref err },
1736                 assert!(err.contains("Cannot send value that would put us over the max HTLC value in flight our peer will accept")));
1737 }
1738
1739 pub fn send_payment<'a, 'b, 'c>(origin: &Node<'a, 'b, 'c>, expected_route: &[&Node<'a, 'b, 'c>], recv_value: u64)  {
1740         let our_payment_preimage = route_payment(&origin, expected_route, recv_value).0;
1741         claim_payment(&origin, expected_route, our_payment_preimage);
1742 }
1743
1744 pub fn fail_payment_along_route<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_paths_slice: &[&[&Node<'a, 'b, 'c>]], skip_last: bool, our_payment_hash: PaymentHash)  {
1745         let mut expected_paths: Vec<_> = expected_paths_slice.iter().collect();
1746         for path in expected_paths.iter() {
1747                 assert_eq!(path.last().unwrap().node.get_our_node_id(), expected_paths[0].last().unwrap().node.get_our_node_id());
1748         }
1749         assert!(expected_paths[0].last().unwrap().node.fail_htlc_backwards(&our_payment_hash));
1750         expect_pending_htlcs_forwardable!(expected_paths[0].last().unwrap());
1751         check_added_monitors!(expected_paths[0].last().unwrap(), expected_paths.len());
1752
1753         let mut per_path_msgs: Vec<((msgs::UpdateFailHTLC, msgs::CommitmentSigned), PublicKey)> = Vec::with_capacity(expected_paths.len());
1754         let events = expected_paths[0].last().unwrap().node.get_and_clear_pending_msg_events();
1755         assert_eq!(events.len(), expected_paths.len());
1756         for ev in events.iter() {
1757                 let (update_fail, commitment_signed, node_id) = match ev {
1758                         &MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
1759                                 assert!(update_add_htlcs.is_empty());
1760                                 assert!(update_fulfill_htlcs.is_empty());
1761                                 assert_eq!(update_fail_htlcs.len(), 1);
1762                                 assert!(update_fail_malformed_htlcs.is_empty());
1763                                 assert!(update_fee.is_none());
1764                                 (update_fail_htlcs[0].clone(), commitment_signed.clone(), node_id.clone())
1765                         },
1766                         _ => panic!("Unexpected event"),
1767                 };
1768                 per_path_msgs.push(((update_fail, commitment_signed), node_id));
1769         }
1770         per_path_msgs.sort_unstable_by(|(_, node_id_a), (_, node_id_b)| node_id_a.cmp(node_id_b));
1771         expected_paths.sort_unstable_by(|path_a, path_b| path_a[path_a.len() - 2].node.get_our_node_id().cmp(&path_b[path_b.len() - 2].node.get_our_node_id()));
1772
1773         for (i, (expected_route, (path_msgs, next_hop))) in expected_paths.iter().zip(per_path_msgs.drain(..)).enumerate() {
1774                 let mut next_msgs = Some(path_msgs);
1775                 let mut expected_next_node = next_hop;
1776                 let mut prev_node = expected_route.last().unwrap();
1777
1778                 for (idx, node) in expected_route.iter().rev().enumerate().skip(1) {
1779                         assert_eq!(expected_next_node, node.node.get_our_node_id());
1780                         let update_next_node = !skip_last || idx != expected_route.len() - 1;
1781                         if next_msgs.is_some() {
1782                                 node.node.handle_update_fail_htlc(&prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0);
1783                                 commitment_signed_dance!(node, prev_node, next_msgs.as_ref().unwrap().1, update_next_node);
1784                                 if !update_next_node {
1785                                         expect_pending_htlcs_forwardable!(node);
1786                                 }
1787                         }
1788                         let events = node.node.get_and_clear_pending_msg_events();
1789                         if update_next_node {
1790                                 assert_eq!(events.len(), 1);
1791                                 match events[0] {
1792                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
1793                                                 assert!(update_add_htlcs.is_empty());
1794                                                 assert!(update_fulfill_htlcs.is_empty());
1795                                                 assert_eq!(update_fail_htlcs.len(), 1);
1796                                                 assert!(update_fail_malformed_htlcs.is_empty());
1797                                                 assert!(update_fee.is_none());
1798                                                 expected_next_node = node_id.clone();
1799                                                 next_msgs = Some((update_fail_htlcs[0].clone(), commitment_signed.clone()));
1800                                         },
1801                                         _ => panic!("Unexpected event"),
1802                                 }
1803                         } else {
1804                                 assert!(events.is_empty());
1805                         }
1806                         if !skip_last && idx == expected_route.len() - 1 {
1807                                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
1808                         }
1809
1810                         prev_node = node;
1811                 }
1812
1813                 if !skip_last {
1814                         let prev_node = expected_route.first().unwrap();
1815                         origin_node.node.handle_update_fail_htlc(&prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0);
1816                         check_added_monitors!(origin_node, 0);
1817                         assert!(origin_node.node.get_and_clear_pending_msg_events().is_empty());
1818                         commitment_signed_dance!(origin_node, prev_node, next_msgs.as_ref().unwrap().1, false);
1819                         let events = origin_node.node.get_and_clear_pending_events();
1820                         assert_eq!(events.len(), 1);
1821                         let expected_payment_id = match events[0] {
1822                                 Event::PaymentPathFailed { payment_hash, rejected_by_dest, all_paths_failed, ref path, ref payment_id, .. } => {
1823                                         assert_eq!(payment_hash, our_payment_hash);
1824                                         assert!(rejected_by_dest);
1825                                         assert_eq!(all_paths_failed, i == expected_paths.len() - 1);
1826                                         for (idx, hop) in expected_route.iter().enumerate() {
1827                                                 assert_eq!(hop.node.get_our_node_id(), path[idx].pubkey);
1828                                         }
1829                                         payment_id.unwrap()
1830                                 },
1831                                 _ => panic!("Unexpected event"),
1832                         };
1833                         if i == expected_paths.len() - 1 {
1834                                 origin_node.node.abandon_payment(expected_payment_id);
1835                                 let events = origin_node.node.get_and_clear_pending_events();
1836                                 assert_eq!(events.len(), 1);
1837                                 match events[0] {
1838                                         Event::PaymentFailed { ref payment_hash, ref payment_id } => {
1839                                                 assert_eq!(*payment_hash, our_payment_hash, "unexpected second payment_hash");
1840                                                 assert_eq!(*payment_id, expected_payment_id);
1841                                         }
1842                                         _ => panic!("Unexpected second event"),
1843                                 }
1844                         }
1845                 }
1846         }
1847
1848         // Ensure that fail_htlc_backwards is idempotent.
1849         assert!(!expected_paths[0].last().unwrap().node.fail_htlc_backwards(&our_payment_hash));
1850         assert!(expected_paths[0].last().unwrap().node.get_and_clear_pending_events().is_empty());
1851         assert!(expected_paths[0].last().unwrap().node.get_and_clear_pending_msg_events().is_empty());
1852         check_added_monitors!(expected_paths[0].last().unwrap(), 0);
1853 }
1854
1855 pub fn fail_payment<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_path: &[&Node<'a, 'b, 'c>], our_payment_hash: PaymentHash)  {
1856         fail_payment_along_route(origin_node, &[&expected_path[..]], false, our_payment_hash);
1857 }
1858
1859 pub fn create_chanmon_cfgs(node_count: usize) -> Vec<TestChanMonCfg> {
1860         let mut chan_mon_cfgs = Vec::new();
1861         for i in 0..node_count {
1862                 let tx_broadcaster = test_utils::TestBroadcaster {
1863                         txn_broadcasted: Mutex::new(Vec::new()),
1864                         blocks: Arc::new(Mutex::new(vec![(genesis_block(Network::Testnet), 0)])),
1865                 };
1866                 let fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
1867                 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
1868                 let logger = test_utils::TestLogger::with_id(format!("node {}", i));
1869                 let persister = test_utils::TestPersister::new();
1870                 let seed = [i as u8; 32];
1871                 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
1872                 let network_graph = NetworkGraph::new(chain_source.genesis_hash);
1873
1874                 chan_mon_cfgs.push(TestChanMonCfg{ tx_broadcaster, fee_estimator, chain_source, logger, persister, keys_manager, network_graph });
1875         }
1876
1877         chan_mon_cfgs
1878 }
1879
1880 pub fn create_node_cfgs<'a>(node_count: usize, chanmon_cfgs: &'a Vec<TestChanMonCfg>) -> Vec<NodeCfg<'a>> {
1881         let mut nodes = Vec::new();
1882
1883         for i in 0..node_count {
1884                 let chain_monitor = test_utils::TestChainMonitor::new(Some(&chanmon_cfgs[i].chain_source), &chanmon_cfgs[i].tx_broadcaster, &chanmon_cfgs[i].logger, &chanmon_cfgs[i].fee_estimator, &chanmon_cfgs[i].persister, &chanmon_cfgs[i].keys_manager);
1885                 let seed = [i as u8; 32];
1886                 nodes.push(NodeCfg {
1887                         chain_source: &chanmon_cfgs[i].chain_source,
1888                         logger: &chanmon_cfgs[i].logger,
1889                         tx_broadcaster: &chanmon_cfgs[i].tx_broadcaster,
1890                         fee_estimator: &chanmon_cfgs[i].fee_estimator,
1891                         chain_monitor,
1892                         keys_manager: &chanmon_cfgs[i].keys_manager,
1893                         node_seed: seed,
1894                         features: InitFeatures::known(),
1895                         network_graph: &chanmon_cfgs[i].network_graph,
1896                 });
1897         }
1898
1899         nodes
1900 }
1901
1902 pub fn test_default_channel_config() -> UserConfig {
1903         let mut default_config = UserConfig::default();
1904         // Set cltv_expiry_delta slightly lower to keep the final CLTV values inside one byte in our
1905         // tests so that our script-length checks don't fail (see ACCEPTED_HTLC_SCRIPT_WEIGHT).
1906         default_config.channel_options.cltv_expiry_delta = MIN_CLTV_EXPIRY_DELTA;
1907         default_config.channel_options.announced_channel = true;
1908         default_config.peer_channel_config_limits.force_announced_channel_preference = false;
1909         // When most of our tests were written, the default HTLC minimum was fixed at 1000.
1910         // It now defaults to 1, so we simply set it to the expected value here.
1911         default_config.own_channel_config.our_htlc_minimum_msat = 1000;
1912         // When most of our tests were written, we didn't have the notion of a `max_dust_htlc_exposure_msat`,
1913         // It now defaults to 5_000_000 msat; to avoid interfering with tests we bump it to 50_000_000 msat.
1914         default_config.channel_options.max_dust_htlc_exposure_msat = 50_000_000;
1915         default_config
1916 }
1917
1918 pub fn create_node_chanmgrs<'a, 'b>(node_count: usize, cfgs: &'a Vec<NodeCfg<'b>>, node_config: &[Option<UserConfig>]) -> Vec<ChannelManager<EnforcingSigner, &'a TestChainMonitor<'b>, &'b test_utils::TestBroadcaster, &'a test_utils::TestKeysInterface, &'b test_utils::TestFeeEstimator, &'b test_utils::TestLogger>> {
1919         let mut chanmgrs = Vec::new();
1920         for i in 0..node_count {
1921                 let network = Network::Testnet;
1922                 let params = ChainParameters {
1923                         network,
1924                         best_block: BestBlock::from_genesis(network),
1925                 };
1926                 let node = ChannelManager::new(cfgs[i].fee_estimator, &cfgs[i].chain_monitor, cfgs[i].tx_broadcaster, cfgs[i].logger, cfgs[i].keys_manager,
1927                         if node_config[i].is_some() { node_config[i].clone().unwrap() } else { test_default_channel_config() }, params);
1928                 chanmgrs.push(node);
1929         }
1930
1931         chanmgrs
1932 }
1933
1934 pub fn create_network<'a, 'b: 'a, 'c: 'b>(node_count: usize, cfgs: &'b Vec<NodeCfg<'c>>, chan_mgrs: &'a Vec<ChannelManager<EnforcingSigner, &'b TestChainMonitor<'c>, &'c test_utils::TestBroadcaster, &'b test_utils::TestKeysInterface, &'c test_utils::TestFeeEstimator, &'c test_utils::TestLogger>>) -> Vec<Node<'a, 'b, 'c>> {
1935         let mut nodes = Vec::new();
1936         let chan_count = Rc::new(RefCell::new(0));
1937         let payment_count = Rc::new(RefCell::new(0));
1938         let connect_style = Rc::new(RefCell::new(ConnectStyle::random_style()));
1939
1940         for i in 0..node_count {
1941                 let net_graph_msg_handler = NetGraphMsgHandler::new(cfgs[i].network_graph, None, cfgs[i].logger);
1942                 nodes.push(Node{
1943                         chain_source: cfgs[i].chain_source, tx_broadcaster: cfgs[i].tx_broadcaster,
1944                         chain_monitor: &cfgs[i].chain_monitor, keys_manager: &cfgs[i].keys_manager,
1945                         node: &chan_mgrs[i], network_graph: &cfgs[i].network_graph, net_graph_msg_handler,
1946                         node_seed: cfgs[i].node_seed, network_chan_count: chan_count.clone(),
1947                         network_payment_count: payment_count.clone(), logger: cfgs[i].logger,
1948                         blocks: Arc::clone(&cfgs[i].tx_broadcaster.blocks),
1949                         connect_style: Rc::clone(&connect_style),
1950                 })
1951         }
1952
1953         for i in 0..node_count {
1954                 for j in (i+1)..node_count {
1955                         nodes[i].node.peer_connected(&nodes[j].node.get_our_node_id(), &msgs::Init { features: cfgs[j].features.clone(), remote_network_address: None });
1956                         nodes[j].node.peer_connected(&nodes[i].node.get_our_node_id(), &msgs::Init { features: cfgs[i].features.clone(), remote_network_address: None });
1957                 }
1958         }
1959
1960         nodes
1961 }
1962
1963 // Note that the following only works for CLTV values up to 128
1964 pub const ACCEPTED_HTLC_SCRIPT_WEIGHT: usize = 137; //Here we have a diff due to HTLC CLTV expiry being < 2^15 in test
1965 pub const OFFERED_HTLC_SCRIPT_WEIGHT: usize = 133;
1966
1967 #[derive(PartialEq)]
1968 pub enum HTLCType { NONE, TIMEOUT, SUCCESS }
1969 /// Tests that the given node has broadcast transactions for the given Channel
1970 ///
1971 /// First checks that the latest holder commitment tx has been broadcast, unless an explicit
1972 /// commitment_tx is provided, which may be used to test that a remote commitment tx was
1973 /// broadcast and the revoked outputs were claimed.
1974 ///
1975 /// Next tests that there is (or is not) a transaction that spends the commitment transaction
1976 /// that appears to be the type of HTLC transaction specified in has_htlc_tx.
1977 ///
1978 /// All broadcast transactions must be accounted for in one of the above three types of we'll
1979 /// also fail.
1980 pub fn test_txn_broadcast<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, chan: &(msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction), commitment_tx: Option<Transaction>, has_htlc_tx: HTLCType) -> Vec<Transaction>  {
1981         let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
1982         assert!(node_txn.len() >= if commitment_tx.is_some() { 0 } else { 1 } + if has_htlc_tx == HTLCType::NONE { 0 } else { 1 });
1983
1984         let mut res = Vec::with_capacity(2);
1985         node_txn.retain(|tx| {
1986                 if tx.input.len() == 1 && tx.input[0].previous_output.txid == chan.3.txid() {
1987                         check_spends!(tx, chan.3);
1988                         if commitment_tx.is_none() {
1989                                 res.push(tx.clone());
1990                         }
1991                         false
1992                 } else { true }
1993         });
1994         if let Some(explicit_tx) = commitment_tx {
1995                 res.push(explicit_tx.clone());
1996         }
1997
1998         assert_eq!(res.len(), 1);
1999
2000         if has_htlc_tx != HTLCType::NONE {
2001                 node_txn.retain(|tx| {
2002                         if tx.input.len() == 1 && tx.input[0].previous_output.txid == res[0].txid() {
2003                                 check_spends!(tx, res[0]);
2004                                 if has_htlc_tx == HTLCType::TIMEOUT {
2005                                         assert!(tx.lock_time != 0);
2006                                 } else {
2007                                         assert!(tx.lock_time == 0);
2008                                 }
2009                                 res.push(tx.clone());
2010                                 false
2011                         } else { true }
2012                 });
2013                 assert!(res.len() == 2 || res.len() == 3);
2014                 if res.len() == 3 {
2015                         assert_eq!(res[1], res[2]);
2016                 }
2017         }
2018
2019         assert!(node_txn.is_empty());
2020         res
2021 }
2022
2023 /// Tests that the given node has broadcast a claim transaction against the provided revoked
2024 /// HTLC transaction.
2025 pub fn test_revoked_htlc_claim_txn_broadcast<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, revoked_tx: Transaction, commitment_revoked_tx: Transaction)  {
2026         let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2027         // We may issue multiple claiming transaction on revoked outputs due to block rescan
2028         // for revoked htlc outputs
2029         if node_txn.len() != 1 && node_txn.len() != 2 && node_txn.len() != 3 { assert!(false); }
2030         node_txn.retain(|tx| {
2031                 if tx.input.len() == 1 && tx.input[0].previous_output.txid == revoked_tx.txid() {
2032                         check_spends!(tx, revoked_tx);
2033                         false
2034                 } else { true }
2035         });
2036         node_txn.retain(|tx| {
2037                 check_spends!(tx, commitment_revoked_tx);
2038                 false
2039         });
2040         assert!(node_txn.is_empty());
2041 }
2042
2043 pub fn check_preimage_claim<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, prev_txn: &Vec<Transaction>) -> Vec<Transaction>  {
2044         let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2045
2046         assert!(node_txn.len() >= 1);
2047         assert_eq!(node_txn[0].input.len(), 1);
2048         let mut found_prev = false;
2049
2050         for tx in prev_txn {
2051                 if node_txn[0].input[0].previous_output.txid == tx.txid() {
2052                         check_spends!(node_txn[0], tx);
2053                         let mut iter = node_txn[0].input[0].witness.iter();
2054                         iter.next().expect("expected 3 witness items");
2055                         iter.next().expect("expected 3 witness items");
2056                         assert!(iter.next().expect("expected 3 witness items").len() > 106); // must spend an htlc output
2057                         assert_eq!(tx.input.len(), 1); // must spend a commitment tx
2058
2059                         found_prev = true;
2060                         break;
2061                 }
2062         }
2063         assert!(found_prev);
2064
2065         let mut res = Vec::new();
2066         mem::swap(&mut *node_txn, &mut res);
2067         res
2068 }
2069
2070 pub fn handle_announce_close_broadcast_events<'a, 'b, 'c>(nodes: &Vec<Node<'a, 'b, 'c>>, a: usize, b: usize, needs_err_handle: bool, expected_error: &str)  {
2071         let events_1 = nodes[a].node.get_and_clear_pending_msg_events();
2072         assert_eq!(events_1.len(), 2);
2073         let as_update = match events_1[0] {
2074                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2075                         msg.clone()
2076                 },
2077                 _ => panic!("Unexpected event"),
2078         };
2079         match events_1[1] {
2080                 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
2081                         assert_eq!(node_id, nodes[b].node.get_our_node_id());
2082                         assert_eq!(msg.data, expected_error);
2083                         if needs_err_handle {
2084                                 nodes[b].node.handle_error(&nodes[a].node.get_our_node_id(), msg);
2085                         }
2086                 },
2087                 _ => panic!("Unexpected event"),
2088         }
2089
2090         let events_2 = nodes[b].node.get_and_clear_pending_msg_events();
2091         assert_eq!(events_2.len(), if needs_err_handle { 1 } else { 2 });
2092         let bs_update = match events_2[0] {
2093                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2094                         msg.clone()
2095                 },
2096                 _ => panic!("Unexpected event"),
2097         };
2098         if !needs_err_handle {
2099                 match events_2[1] {
2100                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
2101                                 assert_eq!(node_id, nodes[a].node.get_our_node_id());
2102                                 assert_eq!(msg.data, expected_error);
2103                         },
2104                         _ => panic!("Unexpected event"),
2105                 }
2106         }
2107
2108         for node in nodes {
2109                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
2110                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
2111         }
2112 }
2113
2114 pub fn get_announce_close_broadcast_events<'a, 'b, 'c>(nodes: &Vec<Node<'a, 'b, 'c>>, a: usize, b: usize)  {
2115         handle_announce_close_broadcast_events(nodes, a, b, false, "Channel closed because commitment or closing transaction was confirmed on chain.");
2116 }
2117
2118 #[cfg(test)]
2119 macro_rules! get_channel_value_stat {
2120         ($node: expr, $channel_id: expr) => {{
2121                 let chan_lock = $node.node.channel_state.lock().unwrap();
2122                 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
2123                 chan.get_value_stat()
2124         }}
2125 }
2126
2127 macro_rules! get_chan_reestablish_msgs {
2128         ($src_node: expr, $dst_node: expr) => {
2129                 {
2130                         let mut res = Vec::with_capacity(1);
2131                         for msg in $src_node.node.get_and_clear_pending_msg_events() {
2132                                 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
2133                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2134                                         res.push(msg.clone());
2135                                 } else {
2136                                         panic!("Unexpected event")
2137                                 }
2138                         }
2139                         res
2140                 }
2141         }
2142 }
2143
2144 macro_rules! handle_chan_reestablish_msgs {
2145         ($src_node: expr, $dst_node: expr) => {
2146                 {
2147                         let msg_events = $src_node.node.get_and_clear_pending_msg_events();
2148                         let mut idx = 0;
2149                         let funding_locked = if let Some(&MessageSendEvent::SendFundingLocked { ref node_id, ref msg }) = msg_events.get(0) {
2150                                 idx += 1;
2151                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2152                                 Some(msg.clone())
2153                         } else {
2154                                 None
2155                         };
2156
2157                         if let Some(&MessageSendEvent::SendAnnouncementSignatures { ref node_id, msg: _ }) = msg_events.get(idx) {
2158                                 idx += 1;
2159                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2160                         }
2161
2162                         let mut revoke_and_ack = None;
2163                         let mut commitment_update = None;
2164                         let order = if let Some(ev) = msg_events.get(idx) {
2165                                 match ev {
2166                                         &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
2167                                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2168                                                 revoke_and_ack = Some(msg.clone());
2169                                                 idx += 1;
2170                                                 RAACommitmentOrder::RevokeAndACKFirst
2171                                         },
2172                                         &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
2173                                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2174                                                 commitment_update = Some(updates.clone());
2175                                                 idx += 1;
2176                                                 RAACommitmentOrder::CommitmentFirst
2177                                         },
2178                                         _ => RAACommitmentOrder::CommitmentFirst,
2179                                 }
2180                         } else {
2181                                 RAACommitmentOrder::CommitmentFirst
2182                         };
2183
2184                         if let Some(ev) = msg_events.get(idx) {
2185                                 match ev {
2186                                         &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
2187                                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2188                                                 assert!(revoke_and_ack.is_none());
2189                                                 revoke_and_ack = Some(msg.clone());
2190                                                 idx += 1;
2191                                         },
2192                                         &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
2193                                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2194                                                 assert!(commitment_update.is_none());
2195                                                 commitment_update = Some(updates.clone());
2196                                                 idx += 1;
2197                                         },
2198                                         _ => {},
2199                                 }
2200                         }
2201
2202                         if let Some(&MessageSendEvent::SendChannelUpdate { ref node_id, ref msg }) = msg_events.get(idx) {
2203                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
2204                                 idx += 1;
2205                                 assert_eq!(msg.contents.flags & 2, 0); // "disabled" flag must not be set as we just reconnected.
2206                         }
2207
2208                         assert_eq!(msg_events.len(), idx);
2209
2210                         (funding_locked, revoke_and_ack, commitment_update, order)
2211                 }
2212         }
2213 }
2214
2215 /// pending_htlc_adds includes both the holding cell and in-flight update_add_htlcs, whereas
2216 /// for claims/fails they are separated out.
2217 pub fn reconnect_nodes<'a, 'b, 'c>(node_a: &Node<'a, 'b, 'c>, node_b: &Node<'a, 'b, 'c>, send_funding_locked: (bool, bool), pending_htlc_adds: (i64, i64), pending_htlc_claims: (usize, usize), pending_htlc_fails: (usize, usize), pending_cell_htlc_claims: (usize, usize), pending_cell_htlc_fails: (usize, usize), pending_raa: (bool, bool))  {
2218         node_a.node.peer_connected(&node_b.node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
2219         let reestablish_1 = get_chan_reestablish_msgs!(node_a, node_b);
2220         node_b.node.peer_connected(&node_a.node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
2221         let reestablish_2 = get_chan_reestablish_msgs!(node_b, node_a);
2222
2223         if send_funding_locked.0 {
2224                 // If a expects a funding_locked, it better not think it has received a revoke_and_ack
2225                 // from b
2226                 for reestablish in reestablish_1.iter() {
2227                         assert_eq!(reestablish.next_remote_commitment_number, 0);
2228                 }
2229         }
2230         if send_funding_locked.1 {
2231                 // If b expects a funding_locked, it better not think it has received a revoke_and_ack
2232                 // from a
2233                 for reestablish in reestablish_2.iter() {
2234                         assert_eq!(reestablish.next_remote_commitment_number, 0);
2235                 }
2236         }
2237         if send_funding_locked.0 || send_funding_locked.1 {
2238                 // If we expect any funding_locked's, both sides better have set
2239                 // next_holder_commitment_number to 1
2240                 for reestablish in reestablish_1.iter() {
2241                         assert_eq!(reestablish.next_local_commitment_number, 1);
2242                 }
2243                 for reestablish in reestablish_2.iter() {
2244                         assert_eq!(reestablish.next_local_commitment_number, 1);
2245                 }
2246         }
2247
2248         let mut resp_1 = Vec::new();
2249         for msg in reestablish_1 {
2250                 node_b.node.handle_channel_reestablish(&node_a.node.get_our_node_id(), &msg);
2251                 resp_1.push(handle_chan_reestablish_msgs!(node_b, node_a));
2252         }
2253         if pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
2254                 check_added_monitors!(node_b, 1);
2255         } else {
2256                 check_added_monitors!(node_b, 0);
2257         }
2258
2259         let mut resp_2 = Vec::new();
2260         for msg in reestablish_2 {
2261                 node_a.node.handle_channel_reestablish(&node_b.node.get_our_node_id(), &msg);
2262                 resp_2.push(handle_chan_reestablish_msgs!(node_a, node_b));
2263         }
2264         if pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
2265                 check_added_monitors!(node_a, 1);
2266         } else {
2267                 check_added_monitors!(node_a, 0);
2268         }
2269
2270         // We don't yet support both needing updates, as that would require a different commitment dance:
2271         assert!((pending_htlc_adds.0 == 0 && pending_htlc_claims.0 == 0 && pending_htlc_fails.0 == 0 &&
2272                          pending_cell_htlc_claims.0 == 0 && pending_cell_htlc_fails.0 == 0) ||
2273                         (pending_htlc_adds.1 == 0 && pending_htlc_claims.1 == 0 && pending_htlc_fails.1 == 0 &&
2274                          pending_cell_htlc_claims.1 == 0 && pending_cell_htlc_fails.1 == 0));
2275
2276         for chan_msgs in resp_1.drain(..) {
2277                 if send_funding_locked.0 {
2278                         node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), &chan_msgs.0.unwrap());
2279                         let announcement_event = node_a.node.get_and_clear_pending_msg_events();
2280                         if !announcement_event.is_empty() {
2281                                 assert_eq!(announcement_event.len(), 1);
2282                                 if let MessageSendEvent::SendChannelUpdate { .. } = announcement_event[0] {
2283                                         //TODO: Test announcement_sigs re-sending
2284                                 } else { panic!("Unexpected event! {:?}", announcement_event[0]); }
2285                         }
2286                 } else {
2287                         assert!(chan_msgs.0.is_none());
2288                 }
2289                 if pending_raa.0 {
2290                         assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
2291                         node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap());
2292                         assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
2293                         check_added_monitors!(node_a, 1);
2294                 } else {
2295                         assert!(chan_msgs.1.is_none());
2296                 }
2297                 if pending_htlc_adds.0 != 0 || pending_htlc_claims.0 != 0 || pending_htlc_fails.0 != 0 || pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
2298                         let commitment_update = chan_msgs.2.unwrap();
2299                         if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
2300                                 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.0 as usize);
2301                         } else {
2302                                 assert!(commitment_update.update_add_htlcs.is_empty());
2303                         }
2304                         assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
2305                         assert_eq!(commitment_update.update_fail_htlcs.len(), pending_htlc_fails.0 + pending_cell_htlc_fails.0);
2306                         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
2307                         for update_add in commitment_update.update_add_htlcs {
2308                                 node_a.node.handle_update_add_htlc(&node_b.node.get_our_node_id(), &update_add);
2309                         }
2310                         for update_fulfill in commitment_update.update_fulfill_htlcs {
2311                                 node_a.node.handle_update_fulfill_htlc(&node_b.node.get_our_node_id(), &update_fulfill);
2312                         }
2313                         for update_fail in commitment_update.update_fail_htlcs {
2314                                 node_a.node.handle_update_fail_htlc(&node_b.node.get_our_node_id(), &update_fail);
2315                         }
2316
2317                         if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
2318                                 commitment_signed_dance!(node_a, node_b, commitment_update.commitment_signed, false);
2319                         } else {
2320                                 node_a.node.handle_commitment_signed(&node_b.node.get_our_node_id(), &commitment_update.commitment_signed);
2321                                 check_added_monitors!(node_a, 1);
2322                                 let as_revoke_and_ack = get_event_msg!(node_a, MessageSendEvent::SendRevokeAndACK, node_b.node.get_our_node_id());
2323                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
2324                                 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &as_revoke_and_ack);
2325                                 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
2326                                 check_added_monitors!(node_b, 1);
2327                         }
2328                 } else {
2329                         assert!(chan_msgs.2.is_none());
2330                 }
2331         }
2332
2333         for chan_msgs in resp_2.drain(..) {
2334                 if send_funding_locked.1 {
2335                         node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &chan_msgs.0.unwrap());
2336                         let announcement_event = node_b.node.get_and_clear_pending_msg_events();
2337                         if !announcement_event.is_empty() {
2338                                 assert_eq!(announcement_event.len(), 1);
2339                                 match announcement_event[0] {
2340                                         MessageSendEvent::SendChannelUpdate { .. } => {},
2341                                         MessageSendEvent::SendAnnouncementSignatures { .. } => {},
2342                                         _ => panic!("Unexpected event {:?}!", announcement_event[0]),
2343                                 }
2344                         }
2345                 } else {
2346                         assert!(chan_msgs.0.is_none());
2347                 }
2348                 if pending_raa.1 {
2349                         assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
2350                         node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap());
2351                         assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
2352                         check_added_monitors!(node_b, 1);
2353                 } else {
2354                         assert!(chan_msgs.1.is_none());
2355                 }
2356                 if pending_htlc_adds.1 != 0 || pending_htlc_claims.1 != 0 || pending_htlc_fails.1 != 0 || pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
2357                         let commitment_update = chan_msgs.2.unwrap();
2358                         if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
2359                                 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.1 as usize);
2360                         }
2361                         assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.1 + pending_cell_htlc_claims.1);
2362                         assert_eq!(commitment_update.update_fail_htlcs.len(), pending_htlc_fails.1 + pending_cell_htlc_fails.1);
2363                         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
2364                         for update_add in commitment_update.update_add_htlcs {
2365                                 node_b.node.handle_update_add_htlc(&node_a.node.get_our_node_id(), &update_add);
2366                         }
2367                         for update_fulfill in commitment_update.update_fulfill_htlcs {
2368                                 node_b.node.handle_update_fulfill_htlc(&node_a.node.get_our_node_id(), &update_fulfill);
2369                         }
2370                         for update_fail in commitment_update.update_fail_htlcs {
2371                                 node_b.node.handle_update_fail_htlc(&node_a.node.get_our_node_id(), &update_fail);
2372                         }
2373
2374                         if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
2375                                 commitment_signed_dance!(node_b, node_a, commitment_update.commitment_signed, false);
2376                         } else {
2377                                 node_b.node.handle_commitment_signed(&node_a.node.get_our_node_id(), &commitment_update.commitment_signed);
2378                                 check_added_monitors!(node_b, 1);
2379                                 let bs_revoke_and_ack = get_event_msg!(node_b, MessageSendEvent::SendRevokeAndACK, node_a.node.get_our_node_id());
2380                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
2381                                 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &bs_revoke_and_ack);
2382                                 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
2383                                 check_added_monitors!(node_a, 1);
2384                         }
2385                 } else {
2386                         assert!(chan_msgs.2.is_none());
2387                 }
2388         }
2389 }