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