Correctly handle sending announcement sigs on public 0conf channels
[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::scid_utils;
25 use util::test_utils;
26 use util::test_utils::{panicking, TestChainMonitor};
27 use util::events::{Event, MessageSendEvent, MessageSendEventsProvider, PaymentPurpose};
28 use util::errors::APIError;
29 use util::config::UserConfig;
30 use util::ser::{ReadableArgs, Writeable, Readable};
31
32 use bitcoin::blockdata::block::{Block, BlockHeader};
33 use bitcoin::blockdata::constants::genesis_block;
34 use bitcoin::blockdata::transaction::{Transaction, TxOut};
35 use bitcoin::network::constants::Network;
36
37 use bitcoin::hash_types::BlockHash;
38
39 use bitcoin::secp256k1::PublicKey;
40
41 use io;
42 use prelude::*;
43 use core::cell::RefCell;
44 use alloc::rc::Rc;
45 use sync::{Arc, Mutex};
46 use core::mem;
47
48 pub const CHAN_CONFIRM_DEPTH: u32 = 10;
49
50 /// Mine the given transaction in the next block and then mine CHAN_CONFIRM_DEPTH - 1 blocks on
51 /// top, giving the given transaction CHAN_CONFIRM_DEPTH confirmations.
52 ///
53 /// Returns the SCID a channel confirmed in the given transaction will have, assuming the funding
54 /// output is the 1st output in the transaction.
55 pub fn confirm_transaction<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, tx: &Transaction) -> u64 {
56         let scid = confirm_transaction_at(node, tx, node.best_block_info().1 + 1);
57         connect_blocks(node, CHAN_CONFIRM_DEPTH - 1);
58         scid
59 }
60 /// Mine a signle block containing the given transaction
61 pub fn mine_transaction<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, tx: &Transaction) {
62         let height = node.best_block_info().1 + 1;
63         confirm_transaction_at(node, tx, height);
64 }
65 /// Mine the given transaction at the given height, mining blocks as required to build to that
66 /// height
67 ///
68 /// Returns the SCID a channel confirmed in the given transaction will have, assuming the funding
69 /// output is the 1st output in the transaction.
70 pub fn confirm_transaction_at<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, tx: &Transaction, conf_height: u32) -> u64 {
71         let first_connect_height = node.best_block_info().1 + 1;
72         assert!(first_connect_height <= conf_height);
73         if conf_height > first_connect_height {
74                 connect_blocks(node, conf_height - first_connect_height);
75         }
76         let mut block = Block {
77                 header: BlockHeader { version: 0x20000000, prev_blockhash: node.best_block_hash(), merkle_root: Default::default(), time: conf_height, bits: 42, nonce: 42 },
78                 txdata: Vec::new(),
79         };
80         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
81                 block.txdata.push(Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() });
82         }
83         block.txdata.push(tx.clone());
84         connect_block(node, &block);
85         scid_utils::scid_from_parts(conf_height as u64, block.txdata.len() as u64 - 1, 0).unwrap()
86 }
87
88 /// The possible ways we may notify a ChannelManager of a new block
89 #[derive(Clone, Copy, PartialEq)]
90 pub enum ConnectStyle {
91         /// Calls best_block_updated first, detecting transactions in the block only after receiving the
92         /// header and height information.
93         BestBlockFirst,
94         /// The same as BestBlockFirst, however when we have multiple blocks to connect, we only
95         /// make a single best_block_updated call.
96         BestBlockFirstSkippingBlocks,
97         /// Calls transactions_confirmed first, detecting transactions in the block before updating the
98         /// header and height information.
99         TransactionsFirst,
100         /// The same as TransactionsFirst, however when we have multiple blocks to connect, we only
101         /// make a single best_block_updated call.
102         TransactionsFirstSkippingBlocks,
103         /// Provides the full block via the chain::Listen interface. In the current code this is
104         /// equivalent to TransactionsFirst with some additional assertions.
105         FullBlockViaListen,
106 }
107
108 pub fn connect_blocks<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, depth: u32) -> BlockHash {
109         let skip_intermediaries = match *node.connect_style.borrow() {
110                 ConnectStyle::BestBlockFirstSkippingBlocks|ConnectStyle::TransactionsFirstSkippingBlocks => true,
111                 _ => false,
112         };
113
114         let height = node.best_block_info().1 + 1;
115         let mut block = Block {
116                 header: BlockHeader { version: 0x2000000, prev_blockhash: node.best_block_hash(), merkle_root: Default::default(), time: height, bits: 42, nonce: 42 },
117                 txdata: vec![],
118         };
119         assert!(depth >= 1);
120         for i in 1..depth {
121                 do_connect_block(node, &block, skip_intermediaries);
122                 block = Block {
123                         header: BlockHeader { version: 0x20000000, prev_blockhash: block.header.block_hash(), merkle_root: Default::default(), time: height + i, bits: 42, nonce: 42 },
124                         txdata: vec![],
125                 };
126         }
127         connect_block(node, &block);
128         block.header.block_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, 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 => {
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 => {
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.header, 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_header = node.blocks.lock().unwrap().pop().unwrap();
177                 assert!(orig_header.1 > 0); // Cannot disconnect genesis
178                 let prev_header = 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_header.0, orig_header.1);
183                                 Listen::block_disconnected(node.node, &orig_header.0, orig_header.1);
184                         },
185                         ConnectStyle::BestBlockFirstSkippingBlocks|ConnectStyle::TransactionsFirstSkippingBlocks => {
186                                 if i == count - 1 {
187                                         node.chain_monitor.chain_monitor.best_block_updated(&prev_header.0, prev_header.1);
188                                         node.node.best_block_updated(&prev_header.0, prev_header.1);
189                                 }
190                         },
191                         _ => {
192                                 node.chain_monitor.chain_monitor.best_block_updated(&prev_header.0, prev_header.1);
193                                 node.node.best_block_updated(&prev_header.0, prev_header.1);
194                         },
195                 }
196                 call_claimable_balances(node);
197         }
198 }
199
200 pub fn disconnect_all_blocks<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>) {
201         let count = node.blocks.lock().unwrap().len() as u32 - 1;
202         disconnect_blocks(node, count);
203 }
204
205 pub struct TestChanMonCfg {
206         pub tx_broadcaster: test_utils::TestBroadcaster,
207         pub fee_estimator: test_utils::TestFeeEstimator,
208         pub chain_source: test_utils::TestChainSource,
209         pub persister: test_utils::TestPersister,
210         pub logger: test_utils::TestLogger,
211         pub keys_manager: test_utils::TestKeysInterface,
212         pub network_graph: NetworkGraph,
213 }
214
215 pub struct NodeCfg<'a> {
216         pub chain_source: &'a test_utils::TestChainSource,
217         pub tx_broadcaster: &'a test_utils::TestBroadcaster,
218         pub fee_estimator: &'a test_utils::TestFeeEstimator,
219         pub chain_monitor: test_utils::TestChainMonitor<'a>,
220         pub keys_manager: &'a test_utils::TestKeysInterface,
221         pub logger: &'a test_utils::TestLogger,
222         pub network_graph: &'a NetworkGraph,
223         pub node_seed: [u8; 32],
224         pub features: InitFeatures,
225 }
226
227 pub struct Node<'a, 'b: 'a, 'c: 'b> {
228         pub chain_source: &'c test_utils::TestChainSource,
229         pub tx_broadcaster: &'c test_utils::TestBroadcaster,
230         pub chain_monitor: &'b test_utils::TestChainMonitor<'c>,
231         pub keys_manager: &'b test_utils::TestKeysInterface,
232         pub node: &'a ChannelManager<EnforcingSigner, &'b TestChainMonitor<'c>, &'c test_utils::TestBroadcaster, &'b test_utils::TestKeysInterface, &'c test_utils::TestFeeEstimator, &'c test_utils::TestLogger>,
233         pub network_graph: &'c NetworkGraph,
234         pub net_graph_msg_handler: NetGraphMsgHandler<&'c NetworkGraph, &'c test_utils::TestChainSource, &'c test_utils::TestLogger>,
235         pub node_seed: [u8; 32],
236         pub network_payment_count: Rc<RefCell<u8>>,
237         pub network_chan_count: Rc<RefCell<u32>>,
238         pub logger: &'c test_utils::TestLogger,
239         pub blocks: Arc<Mutex<Vec<(BlockHeader, u32)>>>,
240         pub connect_style: Rc<RefCell<ConnectStyle>>,
241 }
242 impl<'a, 'b, 'c> Node<'a, 'b, 'c> {
243         pub fn best_block_hash(&self) -> BlockHash {
244                 self.blocks.lock().unwrap().last().unwrap().0.block_hash()
245         }
246         pub fn best_block_info(&self) -> (BlockHash, u32) {
247                 self.blocks.lock().unwrap().last().map(|(a, b)| (a.block_hash(), *b)).unwrap()
248         }
249         pub fn get_block_header(&self, height: u32) -> BlockHeader {
250                 self.blocks.lock().unwrap()[height as usize].0
251         }
252 }
253
254 impl<'a, 'b, 'c> Drop for Node<'a, 'b, 'c> {
255         fn drop(&mut self) {
256                 if !panicking() {
257                         // Check that we processed all pending events
258                         assert!(self.node.get_and_clear_pending_msg_events().is_empty());
259                         assert!(self.node.get_and_clear_pending_events().is_empty());
260                         assert!(self.chain_monitor.added_monitors.lock().unwrap().is_empty());
261
262                         // Check that if we serialize the Router, we can deserialize it again.
263                         {
264                                 let mut w = test_utils::TestVecWriter(Vec::new());
265                                 self.network_graph.write(&mut w).unwrap();
266                                 let network_graph_deser = <NetworkGraph>::read(&mut io::Cursor::new(&w.0)).unwrap();
267                                 assert!(network_graph_deser == *self.network_graph);
268                                 let net_graph_msg_handler = NetGraphMsgHandler::new(
269                                         &network_graph_deser, Some(self.chain_source), self.logger
270                                 );
271                                 let mut chan_progress = 0;
272                                 loop {
273                                         let orig_announcements = self.net_graph_msg_handler.get_next_channel_announcements(chan_progress, 255);
274                                         let deserialized_announcements = net_graph_msg_handler.get_next_channel_announcements(chan_progress, 255);
275                                         assert!(orig_announcements == deserialized_announcements);
276                                         chan_progress = match orig_announcements.last() {
277                                                 Some(announcement) => announcement.0.contents.short_channel_id + 1,
278                                                 None => break,
279                                         };
280                                 }
281                                 let mut node_progress = None;
282                                 loop {
283                                         let orig_announcements = self.net_graph_msg_handler.get_next_node_announcements(node_progress.as_ref(), 255);
284                                         let deserialized_announcements = net_graph_msg_handler.get_next_node_announcements(node_progress.as_ref(), 255);
285                                         assert!(orig_announcements == deserialized_announcements);
286                                         node_progress = match orig_announcements.last() {
287                                                 Some(announcement) => Some(announcement.contents.node_id),
288                                                 None => break,
289                                         };
290                                 }
291                         }
292
293                         // Check that if we serialize and then deserialize all our channel monitors we get the
294                         // same set of outputs to watch for on chain as we have now. Note that if we write
295                         // tests that fully close channels and remove the monitors at some point this may break.
296                         let feeest = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
297                         let mut deserialized_monitors = Vec::new();
298                         {
299                                 for outpoint in self.chain_monitor.chain_monitor.list_monitors() {
300                                         let mut w = test_utils::TestVecWriter(Vec::new());
301                                         self.chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut w).unwrap();
302                                         let (_, deserialized_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
303                                                 &mut io::Cursor::new(&w.0), self.keys_manager).unwrap();
304                                         deserialized_monitors.push(deserialized_monitor);
305                                 }
306                         }
307
308                         // Before using all the new monitors to check the watch outpoints, use the full set of
309                         // them to ensure we can write and reload our ChannelManager.
310                         {
311                                 let mut channel_monitors = HashMap::new();
312                                 for monitor in deserialized_monitors.iter_mut() {
313                                         channel_monitors.insert(monitor.get_funding_txo().0, monitor);
314                                 }
315
316                                 let mut w = test_utils::TestVecWriter(Vec::new());
317                                 self.node.write(&mut w).unwrap();
318                                 <(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 {
319                                         default_config: *self.node.get_current_default_configuration(),
320                                         keys_manager: self.keys_manager,
321                                         fee_estimator: &test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
322                                         chain_monitor: self.chain_monitor,
323                                         tx_broadcaster: &test_utils::TestBroadcaster {
324                                                 txn_broadcasted: Mutex::new(self.tx_broadcaster.txn_broadcasted.lock().unwrap().clone()),
325                                                 blocks: Arc::new(Mutex::new(self.tx_broadcaster.blocks.lock().unwrap().clone())),
326                                         },
327                                         logger: &self.logger,
328                                         channel_monitors,
329                                 }).unwrap();
330                         }
331
332                         let persister = test_utils::TestPersister::new();
333                         let broadcaster = test_utils::TestBroadcaster {
334                                 txn_broadcasted: Mutex::new(self.tx_broadcaster.txn_broadcasted.lock().unwrap().clone()),
335                                 blocks: Arc::new(Mutex::new(self.tx_broadcaster.blocks.lock().unwrap().clone())),
336                         };
337                         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
338                         let chain_monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &broadcaster, &self.logger, &feeest, &persister, &self.keys_manager);
339                         for deserialized_monitor in deserialized_monitors.drain(..) {
340                                 if let Err(_) = chain_monitor.watch_channel(deserialized_monitor.get_funding_txo().0, deserialized_monitor) {
341                                         panic!();
342                                 }
343                         }
344                         assert_eq!(*chain_source.watched_txn.lock().unwrap(), *self.chain_source.watched_txn.lock().unwrap());
345                         assert_eq!(*chain_source.watched_outputs.lock().unwrap(), *self.chain_source.watched_outputs.lock().unwrap());
346                 }
347         }
348 }
349
350 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) {
351         create_chan_between_nodes_with_value(node_a, node_b, 100000, 10001, a_flags, b_flags)
352 }
353
354 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) {
355         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);
356         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(node_a, node_b, &funding_locked);
357         (announcement, as_update, bs_update, channel_id, tx)
358 }
359
360 #[macro_export]
361 /// Gets an RAA and CS which were sent in response to a commitment update
362 macro_rules! get_revoke_commit_msgs {
363         ($node: expr, $node_id: expr) => {
364                 {
365                         use $crate::util::events::MessageSendEvent;
366                         let events = $node.node.get_and_clear_pending_msg_events();
367                         assert_eq!(events.len(), 2);
368                         (match events[0] {
369                                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
370                                         assert_eq!(*node_id, $node_id);
371                                         (*msg).clone()
372                                 },
373                                 _ => panic!("Unexpected event"),
374                         }, match events[1] {
375                                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
376                                         assert_eq!(*node_id, $node_id);
377                                         assert!(updates.update_add_htlcs.is_empty());
378                                         assert!(updates.update_fulfill_htlcs.is_empty());
379                                         assert!(updates.update_fail_htlcs.is_empty());
380                                         assert!(updates.update_fail_malformed_htlcs.is_empty());
381                                         assert!(updates.update_fee.is_none());
382                                         updates.commitment_signed.clone()
383                                 },
384                                 _ => panic!("Unexpected event"),
385                         })
386                 }
387         }
388 }
389
390 /// Get an specific event message from the pending events queue.
391 #[macro_export]
392 macro_rules! get_event_msg {
393         ($node: expr, $event_type: path, $node_id: expr) => {
394                 {
395                         let events = $node.node.get_and_clear_pending_msg_events();
396                         assert_eq!(events.len(), 1);
397                         match events[0] {
398                                 $event_type { ref node_id, ref msg } => {
399                                         assert_eq!(*node_id, $node_id);
400                                         (*msg).clone()
401                                 },
402                                 _ => panic!("Unexpected event"),
403                         }
404                 }
405         }
406 }
407
408 /// Get an error message from the pending events queue.
409 #[macro_export]
410 macro_rules! get_err_msg {
411         ($node: expr, $node_id: expr) => {
412                 {
413                         let events = $node.node.get_and_clear_pending_msg_events();
414                         assert_eq!(events.len(), 1);
415                         match events[0] {
416                                 $crate::util::events::MessageSendEvent::HandleError {
417                                         action: $crate::ln::msgs::ErrorAction::SendErrorMessage { ref msg }, ref node_id
418                                 } => {
419                                         assert_eq!(*node_id, $node_id);
420                                         (*msg).clone()
421                                 },
422                                 _ => panic!("Unexpected event"),
423                         }
424                 }
425         }
426 }
427
428 /// Get a specific event from the pending events queue.
429 #[macro_export]
430 macro_rules! get_event {
431         ($node: expr, $event_type: path) => {
432                 {
433                         let mut events = $node.node.get_and_clear_pending_events();
434                         assert_eq!(events.len(), 1);
435                         let ev = events.pop().unwrap();
436                         match ev {
437                                 $event_type { .. } => {
438                                         ev
439                                 },
440                                 _ => panic!("Unexpected event"),
441                         }
442                 }
443         }
444 }
445
446 #[macro_export]
447 /// Gets an UpdateHTLCs MessageSendEvent
448 macro_rules! get_htlc_update_msgs {
449         ($node: expr, $node_id: expr) => {
450                 {
451                         let events = $node.node.get_and_clear_pending_msg_events();
452                         assert_eq!(events.len(), 1);
453                         match events[0] {
454                                 $crate::util::events::MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
455                                         assert_eq!(*node_id, $node_id);
456                                         (*updates).clone()
457                                 },
458                                 _ => panic!("Unexpected event"),
459                         }
460                 }
461         }
462 }
463
464 #[cfg(test)]
465 macro_rules! get_channel_ref {
466         ($node: expr, $lock: ident, $channel_id: expr) => {
467                 {
468                         $lock = $node.node.channel_state.lock().unwrap();
469                         $lock.by_id.get_mut(&$channel_id).unwrap()
470                 }
471         }
472 }
473
474 #[cfg(test)]
475 macro_rules! get_feerate {
476         ($node: expr, $channel_id: expr) => {
477                 {
478                         let mut lock;
479                         let chan = get_channel_ref!($node, lock, $channel_id);
480                         chan.get_feerate()
481                 }
482         }
483 }
484
485 #[cfg(test)]
486 macro_rules! get_opt_anchors {
487         ($node: expr, $channel_id: expr) => {
488                 {
489                         let mut lock;
490                         let chan = get_channel_ref!($node, lock, $channel_id);
491                         chan.opt_anchors()
492                 }
493         }
494 }
495
496 /// Returns a channel monitor given a channel id, making some naive assumptions
497 #[macro_export]
498 macro_rules! get_monitor {
499         ($node: expr, $channel_id: expr) => {
500                 {
501                         use bitcoin::hashes::Hash;
502                         let mut monitor = None;
503                         // Assume funding vout is either 0 or 1 blindly
504                         for index in 0..2 {
505                                 if let Ok(mon) = $node.chain_monitor.chain_monitor.get_monitor(
506                                         $crate::chain::transaction::OutPoint {
507                                                 txid: bitcoin::Txid::from_slice(&$channel_id[..]).unwrap(), index
508                                         })
509                                 {
510                                         monitor = Some(mon);
511                                         break;
512                                 }
513                         }
514                         monitor.unwrap()
515                 }
516         }
517 }
518
519 /// Returns any local commitment transactions for the channel.
520 #[macro_export]
521 macro_rules! get_local_commitment_txn {
522         ($node: expr, $channel_id: expr) => {
523                 {
524                         $crate::get_monitor!($node, $channel_id).unsafe_get_latest_holder_commitment_txn(&$node.logger)
525                 }
526         }
527 }
528
529 /// Check the error from attempting a payment.
530 #[macro_export]
531 macro_rules! unwrap_send_err {
532         ($res: expr, $all_failed: expr, $type: pat, $check: expr) => {
533                 match &$res {
534                         &Err(PaymentSendFailure::AllFailedRetrySafe(ref fails)) if $all_failed => {
535                                 assert_eq!(fails.len(), 1);
536                                 match fails[0] {
537                                         $type => { $check },
538                                         _ => panic!(),
539                                 }
540                         },
541                         &Err(PaymentSendFailure::PartialFailure { ref results, .. }) if !$all_failed => {
542                                 assert_eq!(results.len(), 1);
543                                 match results[0] {
544                                         Err($type) => { $check },
545                                         _ => panic!(),
546                                 }
547                         },
548                         _ => panic!(),
549                 }
550         }
551 }
552
553 /// Check whether N channel monitor(s) have been added.
554 #[macro_export]
555 macro_rules! check_added_monitors {
556         ($node: expr, $count: expr) => {
557                 {
558                         let mut added_monitors = $node.chain_monitor.added_monitors.lock().unwrap();
559                         assert_eq!(added_monitors.len(), $count);
560                         added_monitors.clear();
561                 }
562         }
563 }
564
565 pub fn create_funding_transaction<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, expected_counterparty_node_id: &PublicKey, expected_chan_value: u64, expected_user_chan_id: u64) -> ([u8; 32], Transaction, OutPoint) {
566         let chan_id = *node.network_chan_count.borrow();
567
568         let events = node.node.get_and_clear_pending_events();
569         assert_eq!(events.len(), 1);
570         match events[0] {
571                 Event::FundingGenerationReady { ref temporary_channel_id, ref counterparty_node_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
572                         assert_eq!(counterparty_node_id, expected_counterparty_node_id);
573                         assert_eq!(*channel_value_satoshis, expected_chan_value);
574                         assert_eq!(user_channel_id, expected_user_chan_id);
575
576                         let tx = Transaction { version: chan_id as i32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
577                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
578                         }]};
579                         let funding_outpoint = OutPoint { txid: tx.txid(), index: 0 };
580                         (*temporary_channel_id, tx, funding_outpoint)
581                 },
582                 _ => panic!("Unexpected event"),
583         }
584 }
585 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 {
586         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(node_a, &node_b.node.get_our_node_id(), channel_value, 42);
587         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
588
589         assert!(node_a.node.funding_transaction_generated(&temporary_channel_id, &node_b.node.get_our_node_id(), tx.clone()).is_ok());
590         check_added_monitors!(node_a, 0);
591
592         let funding_created_msg = get_event_msg!(node_a, MessageSendEvent::SendFundingCreated, node_b.node.get_our_node_id());
593         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
594         node_b.node.handle_funding_created(&node_a.node.get_our_node_id(), &funding_created_msg);
595         {
596                 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
597                 assert_eq!(added_monitors.len(), 1);
598                 assert_eq!(added_monitors[0].0, funding_output);
599                 added_monitors.clear();
600         }
601
602         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()));
603         {
604                 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
605                 assert_eq!(added_monitors.len(), 1);
606                 assert_eq!(added_monitors[0].0, funding_output);
607                 added_monitors.clear();
608         }
609
610         let events_4 = node_a.node.get_and_clear_pending_events();
611         assert_eq!(events_4.len(), 0);
612
613         assert_eq!(node_a.tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
614         assert_eq!(node_a.tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
615         node_a.tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
616
617         // Ensure that funding_transaction_generated is idempotent.
618         assert!(node_a.node.funding_transaction_generated(&temporary_channel_id, &node_b.node.get_our_node_id(), tx.clone()).is_err());
619         assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
620         check_added_monitors!(node_a, 0);
621
622         tx
623 }
624
625 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 {
626         let create_chan_id = node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
627         let open_channel_msg = get_event_msg!(node_a, MessageSendEvent::SendOpenChannel, node_b.node.get_our_node_id());
628         assert_eq!(open_channel_msg.temporary_channel_id, create_chan_id);
629         node_b.node.handle_open_channel(&node_a.node.get_our_node_id(), a_flags, &open_channel_msg);
630         let accept_channel_msg = get_event_msg!(node_b, MessageSendEvent::SendAcceptChannel, node_a.node.get_our_node_id());
631         assert_eq!(accept_channel_msg.temporary_channel_id, create_chan_id);
632         node_a.node.handle_accept_channel(&node_b.node.get_our_node_id(), b_flags, &accept_channel_msg);
633
634         sign_funding_transaction(node_a, node_b, channel_value, create_chan_id)
635 }
636
637 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) {
638         confirm_transaction_at(node_conf, tx, conf_height);
639         connect_blocks(node_conf, CHAN_CONFIRM_DEPTH - 1);
640         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()));
641 }
642
643 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]) {
644         let channel_id;
645         let events_6 = node_conf.node.get_and_clear_pending_msg_events();
646         assert_eq!(events_6.len(), 3);
647         let announcement_sigs_idx = if let MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } = events_6[1] {
648                 assert_eq!(*node_id, node_recv.node.get_our_node_id());
649                 2
650         } else if let MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } = events_6[2] {
651                 assert_eq!(*node_id, node_recv.node.get_our_node_id());
652                 1
653         } else { panic!("Unexpected event: {:?}", events_6[1]); };
654         ((match events_6[0] {
655                 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
656                         channel_id = msg.channel_id.clone();
657                         assert_eq!(*node_id, node_recv.node.get_our_node_id());
658                         msg.clone()
659                 },
660                 _ => panic!("Unexpected event"),
661         }, match events_6[announcement_sigs_idx] {
662                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
663                         assert_eq!(*node_id, node_recv.node.get_our_node_id());
664                         msg.clone()
665                 },
666                 _ => panic!("Unexpected event"),
667         }), channel_id)
668 }
669
670 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]) {
671         let conf_height = core::cmp::max(node_a.best_block_info().1 + 1, node_b.best_block_info().1 + 1);
672         create_chan_between_nodes_with_value_confirm_first(node_a, node_b, tx, conf_height);
673         confirm_transaction_at(node_a, tx, conf_height);
674         connect_blocks(node_a, CHAN_CONFIRM_DEPTH - 1);
675         create_chan_between_nodes_with_value_confirm_second(node_b, node_a)
676 }
677
678 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) {
679         let tx = create_chan_between_nodes_with_value_init(node_a, node_b, channel_value, push_msat, a_flags, b_flags);
680         let (msgs, chan_id) = create_chan_between_nodes_with_value_confirm(node_a, node_b, &tx);
681         (msgs, chan_id, tx)
682 }
683
684 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) {
685         node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &as_funding_msgs.0);
686         let bs_announcement_sigs = get_event_msg!(node_b, MessageSendEvent::SendAnnouncementSignatures, node_a.node.get_our_node_id());
687         node_b.node.handle_announcement_signatures(&node_a.node.get_our_node_id(), &as_funding_msgs.1);
688
689         let events_7 = node_b.node.get_and_clear_pending_msg_events();
690         assert_eq!(events_7.len(), 1);
691         let (announcement, bs_update) = match events_7[0] {
692                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
693                         (msg, update_msg)
694                 },
695                 _ => panic!("Unexpected event"),
696         };
697
698         node_a.node.handle_announcement_signatures(&node_b.node.get_our_node_id(), &bs_announcement_sigs);
699         let events_8 = node_a.node.get_and_clear_pending_msg_events();
700         assert_eq!(events_8.len(), 1);
701         let as_update = match events_8[0] {
702                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
703                         assert!(*announcement == *msg);
704                         assert_eq!(update_msg.contents.short_channel_id, announcement.contents.short_channel_id);
705                         assert_eq!(update_msg.contents.short_channel_id, bs_update.contents.short_channel_id);
706                         update_msg
707                 },
708                 _ => panic!("Unexpected event"),
709         };
710
711         *node_a.network_chan_count.borrow_mut() += 1;
712
713         ((*announcement).clone(), (*as_update).clone(), (*bs_update).clone())
714 }
715
716 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) {
717         create_announced_chan_between_nodes_with_value(nodes, a, b, 100000, 10001, a_flags, b_flags)
718 }
719
720 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) {
721         let chan_announcement = create_chan_between_nodes_with_value(&nodes[a], &nodes[b], channel_value, push_msat, a_flags, b_flags);
722         update_nodes_with_chan_announce(nodes, a, b, &chan_announcement.0, &chan_announcement.1, &chan_announcement.2);
723         (chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
724 }
725
726 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) {
727         let mut no_announce_cfg = test_default_channel_config();
728         no_announce_cfg.channel_options.announced_channel = false;
729         nodes[a].node.create_channel(nodes[b].node.get_our_node_id(), channel_value, push_msat, 42, Some(no_announce_cfg)).unwrap();
730         let open_channel = get_event_msg!(nodes[a], MessageSendEvent::SendOpenChannel, nodes[b].node.get_our_node_id());
731         nodes[b].node.handle_open_channel(&nodes[a].node.get_our_node_id(), a_flags, &open_channel);
732         let accept_channel = get_event_msg!(nodes[b], MessageSendEvent::SendAcceptChannel, nodes[a].node.get_our_node_id());
733         nodes[a].node.handle_accept_channel(&nodes[b].node.get_our_node_id(), b_flags, &accept_channel);
734
735         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[a], &nodes[b].node.get_our_node_id(), channel_value, 42);
736         nodes[a].node.funding_transaction_generated(&temporary_channel_id, &nodes[b].node.get_our_node_id(), tx.clone()).unwrap();
737         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()));
738         check_added_monitors!(nodes[b], 1);
739
740         let cs_funding_signed = get_event_msg!(nodes[b], MessageSendEvent::SendFundingSigned, nodes[a].node.get_our_node_id());
741         nodes[a].node.handle_funding_signed(&nodes[b].node.get_our_node_id(), &cs_funding_signed);
742         check_added_monitors!(nodes[a], 1);
743
744         let conf_height = core::cmp::max(nodes[a].best_block_info().1 + 1, nodes[b].best_block_info().1 + 1);
745         confirm_transaction_at(&nodes[a], &tx, conf_height);
746         connect_blocks(&nodes[a], CHAN_CONFIRM_DEPTH - 1);
747         confirm_transaction_at(&nodes[b], &tx, conf_height);
748         connect_blocks(&nodes[b], CHAN_CONFIRM_DEPTH - 1);
749         let as_funding_locked = get_event_msg!(nodes[a], MessageSendEvent::SendFundingLocked, nodes[b].node.get_our_node_id());
750         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()));
751         let as_update = get_event_msg!(nodes[a], MessageSendEvent::SendChannelUpdate, nodes[b].node.get_our_node_id());
752         nodes[b].node.handle_funding_locked(&nodes[a].node.get_our_node_id(), &as_funding_locked);
753         let bs_update = get_event_msg!(nodes[b], MessageSendEvent::SendChannelUpdate, nodes[a].node.get_our_node_id());
754
755         nodes[a].node.handle_channel_update(&nodes[b].node.get_our_node_id(), &bs_update);
756         nodes[b].node.handle_channel_update(&nodes[a].node.get_our_node_id(), &as_update);
757
758         let mut found_a = false;
759         for chan in nodes[a].node.list_usable_channels() {
760                 if chan.channel_id == as_funding_locked.channel_id {
761                         assert!(!found_a);
762                         found_a = true;
763                         assert!(!chan.is_public);
764                 }
765         }
766         assert!(found_a);
767
768         let mut found_b = false;
769         for chan in nodes[b].node.list_usable_channels() {
770                 if chan.channel_id == as_funding_locked.channel_id {
771                         assert!(!found_b);
772                         found_b = true;
773                         assert!(!chan.is_public);
774                 }
775         }
776         assert!(found_b);
777
778         (as_funding_locked, tx)
779 }
780
781 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) {
782         nodes[a].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
783         let a_events = nodes[a].node.get_and_clear_pending_msg_events();
784         assert!(a_events.len() >= 2);
785
786         // ann should be re-generated by broadcast_node_announcement - check that we have it.
787         let mut found_ann_1 = false;
788         for event in a_events.iter() {
789                 match event {
790                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
791                                 if msg == ann { found_ann_1 = true; }
792                         },
793                         MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
794                         _ => panic!("Unexpected event {:?}", event),
795                 }
796         }
797         assert!(found_ann_1);
798
799         let a_node_announcement = match a_events.last().unwrap() {
800                 MessageSendEvent::BroadcastNodeAnnouncement { ref msg } => {
801                         (*msg).clone()
802                 },
803                 _ => panic!("Unexpected event"),
804         };
805
806         nodes[b].node.broadcast_node_announcement([1, 1, 1], [1; 32], Vec::new());
807         let b_events = nodes[b].node.get_and_clear_pending_msg_events();
808         assert!(b_events.len() >= 2);
809
810         // ann should be re-generated by broadcast_node_announcement - check that we have it.
811         let mut found_ann_2 = false;
812         for event in b_events.iter() {
813                 match event {
814                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
815                                 if msg == ann { found_ann_2 = true; }
816                         },
817                         MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
818                         _ => panic!("Unexpected event"),
819                 }
820         }
821         assert!(found_ann_2);
822
823         let b_node_announcement = match b_events.last().unwrap() {
824                 MessageSendEvent::BroadcastNodeAnnouncement { ref msg } => {
825                         (*msg).clone()
826                 },
827                 _ => panic!("Unexpected event"),
828         };
829
830         for node in nodes {
831                 assert!(node.net_graph_msg_handler.handle_channel_announcement(ann).unwrap());
832                 node.net_graph_msg_handler.handle_channel_update(upd_1).unwrap();
833                 node.net_graph_msg_handler.handle_channel_update(upd_2).unwrap();
834                 node.net_graph_msg_handler.handle_node_announcement(&a_node_announcement).unwrap();
835                 node.net_graph_msg_handler.handle_node_announcement(&b_node_announcement).unwrap();
836
837                 // Note that channel_updates are also delivered to ChannelManagers to ensure we have
838                 // forwarding info for local channels even if its not accepted in the network graph.
839                 node.node.handle_channel_update(&nodes[a].node.get_our_node_id(), &upd_1);
840                 node.node.handle_channel_update(&nodes[b].node.get_our_node_id(), &upd_2);
841         }
842 }
843
844 #[macro_export]
845 macro_rules! check_spends {
846         ($tx: expr, $($spends_txn: expr),*) => {
847                 {
848                         $(
849                         for outp in $spends_txn.output.iter() {
850                                 assert!(outp.value >= outp.script_pubkey.dust_value().as_sat(), "Input tx output didn't meet dust limit");
851                         }
852                         )*
853                         for outp in $tx.output.iter() {
854                                 assert!(outp.value >= outp.script_pubkey.dust_value().as_sat(), "Spending tx output didn't meet dust limit");
855                         }
856                         let get_output = |out_point: &bitcoin::blockdata::transaction::OutPoint| {
857                                 $(
858                                         if out_point.txid == $spends_txn.txid() {
859                                                 return $spends_txn.output.get(out_point.vout as usize).cloned()
860                                         }
861                                 )*
862                                 None
863                         };
864                         let mut total_value_in = 0;
865                         for input in $tx.input.iter() {
866                                 total_value_in += get_output(&input.previous_output).unwrap().value;
867                         }
868                         let mut total_value_out = 0;
869                         for output in $tx.output.iter() {
870                                 total_value_out += output.value;
871                         }
872                         let min_fee = ($tx.weight() as u64 + 3) / 4; // One sat per vbyte (ie per weight/4, rounded up)
873                         // Input amount - output amount = fee, so check that out + min_fee is smaller than input
874                         assert!(total_value_out + min_fee <= total_value_in);
875                         $tx.verify(get_output).unwrap();
876                 }
877         }
878 }
879
880 macro_rules! get_closing_signed_broadcast {
881         ($node: expr, $dest_pubkey: expr) => {
882                 {
883                         let events = $node.get_and_clear_pending_msg_events();
884                         assert!(events.len() == 1 || events.len() == 2);
885                         (match events[events.len() - 1] {
886                                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
887                                         assert_eq!(msg.contents.flags & 2, 2);
888                                         msg.clone()
889                                 },
890                                 _ => panic!("Unexpected event"),
891                         }, if events.len() == 2 {
892                                 match events[0] {
893                                         MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
894                                                 assert_eq!(*node_id, $dest_pubkey);
895                                                 Some(msg.clone())
896                                         },
897                                         _ => panic!("Unexpected event"),
898                                 }
899                         } else { None })
900                 }
901         }
902 }
903
904 #[cfg(test)]
905 macro_rules! check_warn_msg {
906         ($node: expr, $recipient_node_id: expr, $chan_id: expr) => {{
907                 let msg_events = $node.node.get_and_clear_pending_msg_events();
908                 assert_eq!(msg_events.len(), 1);
909                 match msg_events[0] {
910                         MessageSendEvent::HandleError { action: ErrorAction::SendWarningMessage { ref msg, log_level: _ }, node_id } => {
911                                 assert_eq!(node_id, $recipient_node_id);
912                                 assert_eq!(msg.channel_id, $chan_id);
913                                 msg.data.clone()
914                         },
915                         _ => panic!("Unexpected event"),
916                 }
917         }}
918 }
919
920 /// Check that a channel's closing channel update has been broadcasted, and optionally
921 /// check whether an error message event has occurred.
922 #[macro_export]
923 macro_rules! check_closed_broadcast {
924         ($node: expr, $with_error_msg: expr) => {{
925                 use $crate::util::events::MessageSendEvent;
926                 use $crate::ln::msgs::ErrorAction;
927
928                 let msg_events = $node.node.get_and_clear_pending_msg_events();
929                 assert_eq!(msg_events.len(), if $with_error_msg { 2 } else { 1 });
930                 match msg_events[0] {
931                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
932                                 assert_eq!(msg.contents.flags & 2, 2);
933                         },
934                         _ => panic!("Unexpected event"),
935                 }
936                 if $with_error_msg {
937                         match msg_events[1] {
938                                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
939                                         // TODO: Check node_id
940                                         Some(msg.clone())
941                                 },
942                                 _ => panic!("Unexpected event"),
943                         }
944                 } else { None }
945         }}
946 }
947
948 /// Check that a channel's closing channel events has been issued
949 #[macro_export]
950 macro_rules! check_closed_event {
951         ($node: expr, $events: expr, $reason: expr) => {
952                 check_closed_event!($node, $events, $reason, false);
953         };
954         ($node: expr, $events: expr, $reason: expr, $is_check_discard_funding: expr) => {{
955                 use $crate::util::events::Event;
956
957                 let events = $node.node.get_and_clear_pending_events();
958                 assert_eq!(events.len(), $events);
959                 let expected_reason = $reason;
960                 let mut issues_discard_funding = false;
961                 for event in events {
962                         match event {
963                                 Event::ChannelClosed { ref reason, .. } => {
964                                         assert_eq!(*reason, expected_reason);
965                                 },
966                                 Event::DiscardFunding { .. } => {
967                                         issues_discard_funding = true;
968                                 }
969                                 _ => panic!("Unexpected event"),
970                         }
971                 }
972                 assert_eq!($is_check_discard_funding, issues_discard_funding);
973         }}
974 }
975
976 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) {
977         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) };
978         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) };
979         let (tx_a, tx_b);
980
981         node_a.close_channel(channel_id, &node_b.get_our_node_id()).unwrap();
982         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()));
983
984         let events_1 = node_b.get_and_clear_pending_msg_events();
985         assert!(events_1.len() >= 1);
986         let shutdown_b = match events_1[0] {
987                 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
988                         assert_eq!(node_id, &node_a.get_our_node_id());
989                         msg.clone()
990                 },
991                 _ => panic!("Unexpected event"),
992         };
993
994         let closing_signed_b = if !close_inbound_first {
995                 assert_eq!(events_1.len(), 1);
996                 None
997         } else {
998                 Some(match events_1[1] {
999                         MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
1000                                 assert_eq!(node_id, &node_a.get_our_node_id());
1001                                 msg.clone()
1002                         },
1003                         _ => panic!("Unexpected event"),
1004                 })
1005         };
1006
1007         node_a.handle_shutdown(&node_b.get_our_node_id(), &InitFeatures::known(), &shutdown_b);
1008         let (as_update, bs_update) = if close_inbound_first {
1009                 assert!(node_a.get_and_clear_pending_msg_events().is_empty());
1010                 node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap());
1011
1012                 node_b.handle_closing_signed(&node_a.get_our_node_id(), &get_event_msg!(struct_a, MessageSendEvent::SendClosingSigned, node_b.get_our_node_id()));
1013                 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
1014                 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
1015                 let (bs_update, closing_signed_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
1016
1017                 node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap());
1018                 let (as_update, none_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
1019                 assert!(none_a.is_none());
1020                 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
1021                 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
1022                 (as_update, bs_update)
1023         } else {
1024                 let closing_signed_a = get_event_msg!(struct_a, MessageSendEvent::SendClosingSigned, node_b.get_our_node_id());
1025
1026                 node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a);
1027                 node_a.handle_closing_signed(&node_b.get_our_node_id(), &get_event_msg!(struct_b, MessageSendEvent::SendClosingSigned, node_a.get_our_node_id()));
1028
1029                 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
1030                 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
1031                 let (as_update, closing_signed_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
1032
1033                 node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap());
1034                 let (bs_update, none_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
1035                 assert!(none_b.is_none());
1036                 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
1037                 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
1038                 (as_update, bs_update)
1039         };
1040         assert_eq!(tx_a, tx_b);
1041         check_spends!(tx_a, funding_tx);
1042
1043         (as_update, bs_update, tx_a)
1044 }
1045
1046 pub struct SendEvent {
1047         pub node_id: PublicKey,
1048         pub msgs: Vec<msgs::UpdateAddHTLC>,
1049         pub commitment_msg: msgs::CommitmentSigned,
1050 }
1051 impl SendEvent {
1052         pub fn from_commitment_update(node_id: PublicKey, updates: msgs::CommitmentUpdate) -> SendEvent {
1053                 assert!(updates.update_fulfill_htlcs.is_empty());
1054                 assert!(updates.update_fail_htlcs.is_empty());
1055                 assert!(updates.update_fail_malformed_htlcs.is_empty());
1056                 assert!(updates.update_fee.is_none());
1057                 SendEvent { node_id: node_id, msgs: updates.update_add_htlcs, commitment_msg: updates.commitment_signed }
1058         }
1059
1060         pub fn from_event(event: MessageSendEvent) -> SendEvent {
1061                 match event {
1062                         MessageSendEvent::UpdateHTLCs { node_id, updates } => SendEvent::from_commitment_update(node_id, updates),
1063                         _ => panic!("Unexpected event type!"),
1064                 }
1065         }
1066
1067         pub fn from_node<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>) -> SendEvent {
1068                 let mut events = node.node.get_and_clear_pending_msg_events();
1069                 assert_eq!(events.len(), 1);
1070                 SendEvent::from_event(events.pop().unwrap())
1071         }
1072 }
1073
1074 #[macro_export]
1075 /// Performs the "commitment signed dance" - the series of message exchanges which occur after a
1076 /// commitment update.
1077 macro_rules! commitment_signed_dance {
1078         ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */) => {
1079                 {
1080                         check_added_monitors!($node_a, 0);
1081                         assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
1082                         $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed);
1083                         check_added_monitors!($node_a, 1);
1084                         commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, false);
1085                 }
1086         };
1087         ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */, true /* return last RAA */) => {
1088                 {
1089                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!($node_a, $node_b.node.get_our_node_id());
1090                         check_added_monitors!($node_b, 0);
1091                         assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
1092                         $node_b.node.handle_revoke_and_ack(&$node_a.node.get_our_node_id(), &as_revoke_and_ack);
1093                         assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
1094                         check_added_monitors!($node_b, 1);
1095                         $node_b.node.handle_commitment_signed(&$node_a.node.get_our_node_id(), &as_commitment_signed);
1096                         let (bs_revoke_and_ack, extra_msg_option) = {
1097                                 let events = $node_b.node.get_and_clear_pending_msg_events();
1098                                 assert!(events.len() <= 2);
1099                                 (match events[0] {
1100                                         MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
1101                                                 assert_eq!(*node_id, $node_a.node.get_our_node_id());
1102                                                 (*msg).clone()
1103                                         },
1104                                         _ => panic!("Unexpected event"),
1105                                 }, events.get(1).map(|e| e.clone()))
1106                         };
1107                         check_added_monitors!($node_b, 1);
1108                         if $fail_backwards {
1109                                 assert!($node_a.node.get_and_clear_pending_events().is_empty());
1110                                 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
1111                         }
1112                         (extra_msg_option, bs_revoke_and_ack)
1113                 }
1114         };
1115         ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */, false /* return extra message */, true /* return last RAA */) => {
1116                 {
1117                         check_added_monitors!($node_a, 0);
1118                         assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
1119                         $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed);
1120                         check_added_monitors!($node_a, 1);
1121                         let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
1122                         assert!(extra_msg_option.is_none());
1123                         bs_revoke_and_ack
1124                 }
1125         };
1126         ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */) => {
1127                 {
1128                         let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
1129                         $node_a.node.handle_revoke_and_ack(&$node_b.node.get_our_node_id(), &bs_revoke_and_ack);
1130                         check_added_monitors!($node_a, 1);
1131                         extra_msg_option
1132                 }
1133         };
1134         ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, false /* no extra message */) => {
1135                 {
1136                         assert!(commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true).is_none());
1137                 }
1138         };
1139         ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr) => {
1140                 {
1141                         commitment_signed_dance!($node_a, $node_b, $commitment_signed, $fail_backwards, true);
1142                         if $fail_backwards {
1143                                 $crate::expect_pending_htlcs_forwardable!($node_a);
1144                                 check_added_monitors!($node_a, 1);
1145
1146                                 let channel_state = $node_a.node.channel_state.lock().unwrap();
1147                                 assert_eq!(channel_state.pending_msg_events.len(), 1);
1148                                 if let MessageSendEvent::UpdateHTLCs { ref node_id, .. } = channel_state.pending_msg_events[0] {
1149                                         assert_ne!(*node_id, $node_b.node.get_our_node_id());
1150                                 } else { panic!("Unexpected event"); }
1151                         } else {
1152                                 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
1153                         }
1154                 }
1155         }
1156 }
1157
1158 /// Get a payment preimage and hash.
1159 #[macro_export]
1160 macro_rules! get_payment_preimage_hash {
1161         ($dest_node: expr) => {
1162                 {
1163                         get_payment_preimage_hash!($dest_node, None)
1164                 }
1165         };
1166         ($dest_node: expr, $min_value_msat: expr) => {
1167                 {
1168                         use bitcoin::hashes::Hash as _;
1169                         let mut payment_count = $dest_node.network_payment_count.borrow_mut();
1170                         let payment_preimage = $crate::ln::PaymentPreimage([*payment_count; 32]);
1171                         *payment_count += 1;
1172                         let payment_hash = $crate::ln::PaymentHash(
1173                                 bitcoin::hashes::sha256::Hash::hash(&payment_preimage.0[..]).into_inner());
1174                         let payment_secret = $dest_node.node.create_inbound_payment_for_hash(payment_hash, $min_value_msat, 7200).unwrap();
1175                         (payment_preimage, payment_hash, payment_secret)
1176                 }
1177         }
1178 }
1179
1180 #[macro_export]
1181 macro_rules! get_route {
1182         ($send_node: expr, $payment_params: expr, $recv_value: expr, $cltv: expr) => {{
1183                 use $crate::chain::keysinterface::KeysInterface;
1184                 let scorer = $crate::util::test_utils::TestScorer::with_penalty(0);
1185                 let keys_manager = $crate::util::test_utils::TestKeysInterface::new(&[0u8; 32], bitcoin::network::constants::Network::Testnet);
1186                 let random_seed_bytes = keys_manager.get_secure_random_bytes();
1187                 $crate::routing::router::get_route(
1188                         &$send_node.node.get_our_node_id(), &$payment_params, &$send_node.network_graph.read_only(),
1189                         Some(&$send_node.node.list_usable_channels().iter().collect::<Vec<_>>()),
1190                         $recv_value, $cltv, $send_node.logger, &scorer, &random_seed_bytes
1191                 )
1192         }}
1193 }
1194
1195 #[cfg(test)]
1196 #[macro_export]
1197 macro_rules! get_route_and_payment_hash {
1198         ($send_node: expr, $recv_node: expr, $recv_value: expr) => {{
1199                 let payment_params = $crate::routing::router::PaymentParameters::from_node_id($recv_node.node.get_our_node_id())
1200                         .with_features($crate::ln::features::InvoiceFeatures::known());
1201                 $crate::get_route_and_payment_hash!($send_node, $recv_node, payment_params, $recv_value, TEST_FINAL_CLTV)
1202         }};
1203         ($send_node: expr, $recv_node: expr, $payment_params: expr, $recv_value: expr, $cltv: expr) => {{
1204                 let (payment_preimage, payment_hash, payment_secret) = $crate::get_payment_preimage_hash!($recv_node, Some($recv_value));
1205                 let route = $crate::get_route!($send_node, $payment_params, $recv_value, $cltv);
1206                 (route.unwrap(), payment_hash, payment_preimage, payment_secret)
1207         }}
1208 }
1209
1210 #[macro_export]
1211 /// Clears (and ignores) a PendingHTLCsForwardable event
1212 macro_rules! expect_pending_htlcs_forwardable_ignore {
1213         ($node: expr) => {{
1214                 let events = $node.node.get_and_clear_pending_events();
1215                 assert_eq!(events.len(), 1);
1216                 match events[0] {
1217                         $crate::util::events::Event::PendingHTLCsForwardable { .. } => { },
1218                         _ => panic!("Unexpected event"),
1219                 };
1220         }}
1221 }
1222
1223 #[macro_export]
1224 /// Handles a PendingHTLCsForwardable event
1225 macro_rules! expect_pending_htlcs_forwardable {
1226         ($node: expr) => {{
1227                 $crate::expect_pending_htlcs_forwardable_ignore!($node);
1228                 $node.node.process_pending_htlc_forwards();
1229
1230                 // Ensure process_pending_htlc_forwards is idempotent.
1231                 $node.node.process_pending_htlc_forwards();
1232         }}
1233 }
1234
1235 #[cfg(test)]
1236 macro_rules! expect_pending_htlcs_forwardable_from_events {
1237         ($node: expr, $events: expr, $ignore: expr) => {{
1238                 assert_eq!($events.len(), 1);
1239                 match $events[0] {
1240                         Event::PendingHTLCsForwardable { .. } => { },
1241                         _ => panic!("Unexpected event"),
1242                 };
1243                 if $ignore {
1244                         $node.node.process_pending_htlc_forwards();
1245
1246                         // Ensure process_pending_htlc_forwards is idempotent.
1247                         $node.node.process_pending_htlc_forwards();
1248                 }
1249         }}
1250 }
1251
1252 #[macro_export]
1253 #[cfg(any(test, feature = "_bench_unstable", feature = "_test_utils"))]
1254 macro_rules! expect_payment_received {
1255         ($node: expr, $expected_payment_hash: expr, $expected_payment_secret: expr, $expected_recv_value: expr) => {
1256                 expect_payment_received!($node, $expected_payment_hash, $expected_payment_secret, $expected_recv_value, None)
1257         };
1258         ($node: expr, $expected_payment_hash: expr, $expected_payment_secret: expr, $expected_recv_value: expr, $expected_payment_preimage: expr) => {
1259                 let events = $node.node.get_and_clear_pending_events();
1260                 assert_eq!(events.len(), 1);
1261                 match events[0] {
1262                         $crate::util::events::Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1263                                 assert_eq!($expected_payment_hash, *payment_hash);
1264                                 assert_eq!($expected_recv_value, amt);
1265                                 match purpose {
1266                                         $crate::util::events::PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1267                                                 assert_eq!(&$expected_payment_preimage, payment_preimage);
1268                                                 assert_eq!($expected_payment_secret, *payment_secret);
1269                                         },
1270                                         _ => {},
1271                                 }
1272                         },
1273                         _ => panic!("Unexpected event"),
1274                 }
1275         }
1276 }
1277
1278 #[cfg(test)]
1279 #[macro_export]
1280 macro_rules! expect_payment_sent_without_paths {
1281         ($node: expr, $expected_payment_preimage: expr) => {
1282                 expect_payment_sent!($node, $expected_payment_preimage, None::<u64>, false);
1283         };
1284         ($node: expr, $expected_payment_preimage: expr, $expected_fee_msat_opt: expr) => {
1285                 expect_payment_sent!($node, $expected_payment_preimage, $expected_fee_msat_opt, false);
1286         }
1287 }
1288
1289 #[macro_export]
1290 macro_rules! expect_payment_sent {
1291         ($node: expr, $expected_payment_preimage: expr) => {
1292                 $crate::expect_payment_sent!($node, $expected_payment_preimage, None::<u64>, true);
1293         };
1294         ($node: expr, $expected_payment_preimage: expr, $expected_fee_msat_opt: expr) => {
1295                 $crate::expect_payment_sent!($node, $expected_payment_preimage, $expected_fee_msat_opt, true);
1296         };
1297         ($node: expr, $expected_payment_preimage: expr, $expected_fee_msat_opt: expr, $expect_paths: expr) => { {
1298                 use bitcoin::hashes::Hash as _;
1299                 let events = $node.node.get_and_clear_pending_events();
1300                 let expected_payment_hash = $crate::ln::PaymentHash(
1301                         bitcoin::hashes::sha256::Hash::hash(&$expected_payment_preimage.0).into_inner());
1302                 if $expect_paths {
1303                         assert!(events.len() > 1);
1304                 } else {
1305                         assert_eq!(events.len(), 1);
1306                 }
1307                 let expected_payment_id = match events[0] {
1308                         $crate::util::events::Event::PaymentSent { ref payment_id, ref payment_preimage, ref payment_hash, ref fee_paid_msat } => {
1309                                 assert_eq!($expected_payment_preimage, *payment_preimage);
1310                                 assert_eq!(expected_payment_hash, *payment_hash);
1311                                 assert!(fee_paid_msat.is_some());
1312                                 if $expected_fee_msat_opt.is_some() {
1313                                         assert_eq!(*fee_paid_msat, $expected_fee_msat_opt);
1314                                 }
1315                                 payment_id.unwrap()
1316                         },
1317                         _ => panic!("Unexpected event"),
1318                 };
1319                 if $expect_paths {
1320                         for i in 1..events.len() {
1321                                 match events[i] {
1322                                         $crate::util::events::Event::PaymentPathSuccessful { payment_id, payment_hash, .. } => {
1323                                                 assert_eq!(payment_id, expected_payment_id);
1324                                                 assert_eq!(payment_hash, Some(expected_payment_hash));
1325                                         },
1326                                         _ => panic!("Unexpected event"),
1327                                 }
1328                         }
1329                 }
1330         } }
1331 }
1332
1333 #[cfg(test)]
1334 #[macro_export]
1335 macro_rules! expect_payment_path_successful {
1336         ($node: expr) => {
1337                 let events = $node.node.get_and_clear_pending_events();
1338                 assert_eq!(events.len(), 1);
1339                 match events[0] {
1340                         $crate::util::events::Event::PaymentPathSuccessful { .. } => {},
1341                         _ => panic!("Unexpected event"),
1342                 }
1343         }
1344 }
1345
1346 macro_rules! expect_payment_forwarded {
1347         ($node: expr, $prev_node: expr, $next_node: expr, $expected_fee: expr, $upstream_force_closed: expr, $downstream_force_closed: expr) => {
1348                 let events = $node.node.get_and_clear_pending_events();
1349                 assert_eq!(events.len(), 1);
1350                 match events[0] {
1351                         Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
1352                                 assert_eq!(fee_earned_msat, $expected_fee);
1353                                 if fee_earned_msat.is_some() {
1354                                         // Is the event prev_channel_id in one of the channels between the two nodes?
1355                                         assert!($node.node.list_channels().iter().any(|x| x.counterparty.node_id == $prev_node.node.get_our_node_id() && x.channel_id == prev_channel_id.unwrap()));
1356                                 }
1357                                 // We check for force closures since a force closed channel is removed from the
1358                                 // node's channel list
1359                                 if !$downstream_force_closed {
1360                                         assert!($node.node.list_channels().iter().any(|x| x.counterparty.node_id == $next_node.node.get_our_node_id() && x.channel_id == next_channel_id.unwrap()));
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, $prev_node, Some(fee as u64), false, 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).header, 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 }