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