Use alloc for no_std builds
[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::{Confirm, Listen, Watch};
14 use chain::channelmonitor::ChannelMonitor;
15 use chain::transaction::OutPoint;
16 use ln::{PaymentPreimage, PaymentHash, PaymentSecret};
17 use ln::channelmanager::{BestBlock, ChainParameters, ChannelManager, ChannelManagerReadArgs, RAACommitmentOrder, PaymentSendFailure};
18 use routing::router::{Route, get_route};
19 use routing::network_graph::{NetGraphMsgHandler, NetworkGraph};
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::TestChainMonitor;
26 use util::events::{Event, MessageSendEvent, MessageSendEventsProvider};
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::hashes::sha256::Hash as Sha256;
37 use bitcoin::hashes::Hash;
38 use bitcoin::hash_types::BlockHash;
39
40 use bitcoin::secp256k1::key::PublicKey;
41
42 use prelude::*;
43 use core::cell::RefCell;
44 use std::rc::Rc;
45 use std::sync::Mutex;
46 use core::mem;
47 use std::collections::HashMap;
48
49 pub const CHAN_CONFIRM_DEPTH: u32 = 10;
50
51 /// Mine the given transaction in the next block and then mine CHAN_CONFIRM_DEPTH - 1 blocks on
52 /// top, giving the given transaction CHAN_CONFIRM_DEPTH confirmations.
53 pub fn confirm_transaction<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, tx: &Transaction) {
54         confirm_transaction_at(node, tx, node.best_block_info().1 + 1);
55         connect_blocks(node, CHAN_CONFIRM_DEPTH - 1);
56 }
57 /// Mine a signle block containing the given transaction
58 pub fn mine_transaction<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, tx: &Transaction) {
59         let height = node.best_block_info().1 + 1;
60         confirm_transaction_at(node, tx, height);
61 }
62 /// Mine the given transaction at the given height, mining blocks as required to build to that
63 /// height
64 pub fn confirm_transaction_at<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, tx: &Transaction, conf_height: u32) {
65         let first_connect_height = node.best_block_info().1 + 1;
66         assert!(first_connect_height <= conf_height);
67         if conf_height > first_connect_height {
68                 connect_blocks(node, conf_height - first_connect_height);
69         }
70         let mut block = Block {
71                 header: BlockHeader { version: 0x20000000, prev_blockhash: node.best_block_hash(), merkle_root: Default::default(), time: conf_height, bits: 42, nonce: 42 },
72                 txdata: Vec::new(),
73         };
74         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
75                 block.txdata.push(Transaction { version: 0, lock_time: 0, input: Vec::new(), output: Vec::new() });
76         }
77         block.txdata.push(tx.clone());
78         connect_block(node, &block);
79 }
80
81 /// The possible ways we may notify a ChannelManager of a new block
82 #[derive(Clone, Copy, PartialEq)]
83 pub enum ConnectStyle {
84         /// Calls best_block_updated first, detecting transactions in the block only after receiving the
85         /// header and height information.
86         BestBlockFirst,
87         /// The same as BestBlockFirst, however when we have multiple blocks to connect, we only
88         /// make a single best_block_updated call.
89         BestBlockFirstSkippingBlocks,
90         /// Calls transactions_confirmed first, detecting transactions in the block before updating the
91         /// header and height information.
92         TransactionsFirst,
93         /// The same as TransactionsFirst, however when we have multiple blocks to connect, we only
94         /// make a single best_block_updated call.
95         TransactionsFirstSkippingBlocks,
96         /// Provides the full block via the chain::Listen interface. In the current code this is
97         /// equivalent to TransactionsFirst with some additional assertions.
98         FullBlockViaListen,
99 }
100
101 pub fn connect_blocks<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, depth: u32) -> BlockHash {
102         let skip_intermediaries = match *node.connect_style.borrow() {
103                 ConnectStyle::BestBlockFirstSkippingBlocks|ConnectStyle::TransactionsFirstSkippingBlocks => true,
104                 _ => false,
105         };
106
107         let height = node.best_block_info().1 + 1;
108         let mut block = Block {
109                 header: BlockHeader { version: 0x2000000, prev_blockhash: node.best_block_hash(), merkle_root: Default::default(), time: height, bits: 42, nonce: 42 },
110                 txdata: vec![],
111         };
112         assert!(depth >= 1);
113         for i in 1..depth {
114                 do_connect_block(node, &block, skip_intermediaries);
115                 block = Block {
116                         header: BlockHeader { version: 0x20000000, prev_blockhash: block.header.block_hash(), merkle_root: Default::default(), time: height + i, bits: 42, nonce: 42 },
117                         txdata: vec![],
118                 };
119         }
120         connect_block(node, &block);
121         block.header.block_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, false);
126 }
127
128 fn do_connect_block<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, block: &Block, skip_intermediaries: bool) {
129         let height = node.best_block_info().1 + 1;
130         if !skip_intermediaries {
131                 let txdata: Vec<_> = block.txdata.iter().enumerate().collect();
132                 match *node.connect_style.borrow() {
133                         ConnectStyle::BestBlockFirst|ConnectStyle::BestBlockFirstSkippingBlocks => {
134                                 node.chain_monitor.chain_monitor.best_block_updated(&block.header, height);
135                                 node.chain_monitor.chain_monitor.transactions_confirmed(&block.header, &txdata, height);
136                                 node.node.best_block_updated(&block.header, height);
137                                 node.node.transactions_confirmed(&block.header, &txdata, height);
138                         },
139                         ConnectStyle::TransactionsFirst|ConnectStyle::TransactionsFirstSkippingBlocks => {
140                                 node.chain_monitor.chain_monitor.transactions_confirmed(&block.header, &txdata, height);
141                                 node.chain_monitor.chain_monitor.best_block_updated(&block.header, height);
142                                 node.node.transactions_confirmed(&block.header, &txdata, height);
143                                 node.node.best_block_updated(&block.header, height);
144                         },
145                         ConnectStyle::FullBlockViaListen => {
146                                 node.chain_monitor.chain_monitor.block_connected(&block, height);
147                                 node.node.block_connected(&block, height);
148                         }
149                 }
150         }
151         node.node.test_process_background_events();
152         node.blocks.borrow_mut().push((block.header, height));
153 }
154
155 pub fn disconnect_blocks<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, count: u32) {
156         for i in 0..count {
157                 let orig_header = node.blocks.borrow_mut().pop().unwrap();
158                 assert!(orig_header.1 > 0); // Cannot disconnect genesis
159                 let prev_header = node.blocks.borrow().last().unwrap().clone();
160
161                 match *node.connect_style.borrow() {
162                         ConnectStyle::FullBlockViaListen => {
163                                 node.chain_monitor.chain_monitor.block_disconnected(&orig_header.0, orig_header.1);
164                                 Listen::block_disconnected(node.node, &orig_header.0, orig_header.1);
165                         },
166                         ConnectStyle::BestBlockFirstSkippingBlocks|ConnectStyle::TransactionsFirstSkippingBlocks => {
167                                 if i == count - 1 {
168                                         node.chain_monitor.chain_monitor.best_block_updated(&prev_header.0, prev_header.1);
169                                         node.node.best_block_updated(&prev_header.0, prev_header.1);
170                                 }
171                         },
172                         _ => {
173                                 node.chain_monitor.chain_monitor.best_block_updated(&prev_header.0, prev_header.1);
174                                 node.node.best_block_updated(&prev_header.0, prev_header.1);
175                         },
176                 }
177         }
178 }
179
180 pub fn disconnect_all_blocks<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>) {
181         let count = node.blocks.borrow_mut().len() as u32 - 1;
182         disconnect_blocks(node, count);
183 }
184
185 pub struct TestChanMonCfg {
186         pub tx_broadcaster: test_utils::TestBroadcaster,
187         pub fee_estimator: test_utils::TestFeeEstimator,
188         pub chain_source: test_utils::TestChainSource,
189         pub persister: test_utils::TestPersister,
190         pub logger: test_utils::TestLogger,
191         pub keys_manager: test_utils::TestKeysInterface,
192 }
193
194 pub struct NodeCfg<'a> {
195         pub chain_source: &'a test_utils::TestChainSource,
196         pub tx_broadcaster: &'a test_utils::TestBroadcaster,
197         pub fee_estimator: &'a test_utils::TestFeeEstimator,
198         pub chain_monitor: test_utils::TestChainMonitor<'a>,
199         pub keys_manager: &'a test_utils::TestKeysInterface,
200         pub logger: &'a test_utils::TestLogger,
201         pub node_seed: [u8; 32],
202 }
203
204 pub struct Node<'a, 'b: 'a, 'c: 'b> {
205         pub chain_source: &'c test_utils::TestChainSource,
206         pub tx_broadcaster: &'c test_utils::TestBroadcaster,
207         pub chain_monitor: &'b test_utils::TestChainMonitor<'c>,
208         pub keys_manager: &'b test_utils::TestKeysInterface,
209         pub node: &'a ChannelManager<EnforcingSigner, &'b TestChainMonitor<'c>, &'c test_utils::TestBroadcaster, &'b test_utils::TestKeysInterface, &'c test_utils::TestFeeEstimator, &'c test_utils::TestLogger>,
210         pub net_graph_msg_handler: NetGraphMsgHandler<&'c test_utils::TestChainSource, &'c test_utils::TestLogger>,
211         pub node_seed: [u8; 32],
212         pub network_payment_count: Rc<RefCell<u8>>,
213         pub network_chan_count: Rc<RefCell<u32>>,
214         pub logger: &'c test_utils::TestLogger,
215         pub blocks: RefCell<Vec<(BlockHeader, u32)>>,
216         pub connect_style: Rc<RefCell<ConnectStyle>>,
217 }
218 impl<'a, 'b, 'c> Node<'a, 'b, 'c> {
219         pub fn best_block_hash(&self) -> BlockHash {
220                 self.blocks.borrow_mut().last().unwrap().0.block_hash()
221         }
222         pub fn best_block_info(&self) -> (BlockHash, u32) {
223                 self.blocks.borrow_mut().last().map(|(a, b)| (a.block_hash(), *b)).unwrap()
224         }
225 }
226
227 impl<'a, 'b, 'c> Drop for Node<'a, 'b, 'c> {
228         fn drop(&mut self) {
229                 if !::std::thread::panicking() {
230                         // Check that we processed all pending events
231                         assert!(self.node.get_and_clear_pending_msg_events().is_empty());
232                         assert!(self.node.get_and_clear_pending_events().is_empty());
233                         assert!(self.chain_monitor.added_monitors.lock().unwrap().is_empty());
234
235                         // Check that if we serialize the Router, we can deserialize it again.
236                         {
237                                 let mut w = test_utils::TestVecWriter(Vec::new());
238                                 let network_graph_ser = self.net_graph_msg_handler.network_graph.read().unwrap();
239                                 network_graph_ser.write(&mut w).unwrap();
240                                 let network_graph_deser = <NetworkGraph>::read(&mut ::std::io::Cursor::new(&w.0)).unwrap();
241                                 assert!(network_graph_deser == *self.net_graph_msg_handler.network_graph.read().unwrap());
242                                 let net_graph_msg_handler = NetGraphMsgHandler::from_net_graph(
243                                         Some(self.chain_source), self.logger, network_graph_deser
244                                 );
245                                 let mut chan_progress = 0;
246                                 loop {
247                                         let orig_announcements = self.net_graph_msg_handler.get_next_channel_announcements(chan_progress, 255);
248                                         let deserialized_announcements = net_graph_msg_handler.get_next_channel_announcements(chan_progress, 255);
249                                         assert!(orig_announcements == deserialized_announcements);
250                                         chan_progress = match orig_announcements.last() {
251                                                 Some(announcement) => announcement.0.contents.short_channel_id + 1,
252                                                 None => break,
253                                         };
254                                 }
255                                 let mut node_progress = None;
256                                 loop {
257                                         let orig_announcements = self.net_graph_msg_handler.get_next_node_announcements(node_progress.as_ref(), 255);
258                                         let deserialized_announcements = net_graph_msg_handler.get_next_node_announcements(node_progress.as_ref(), 255);
259                                         assert!(orig_announcements == deserialized_announcements);
260                                         node_progress = match orig_announcements.last() {
261                                                 Some(announcement) => Some(announcement.contents.node_id),
262                                                 None => break,
263                                         };
264                                 }
265                         }
266
267                         // Check that if we serialize and then deserialize all our channel monitors we get the
268                         // same set of outputs to watch for on chain as we have now. Note that if we write
269                         // tests that fully close channels and remove the monitors at some point this may break.
270                         let feeest = test_utils::TestFeeEstimator { sat_per_kw: 253 };
271                         let mut deserialized_monitors = Vec::new();
272                         {
273                                 let old_monitors = self.chain_monitor.chain_monitor.monitors.read().unwrap();
274                                 for (_, old_monitor) in old_monitors.iter() {
275                                         let mut w = test_utils::TestVecWriter(Vec::new());
276                                         old_monitor.write(&mut w).unwrap();
277                                         let (_, deserialized_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
278                                                 &mut ::std::io::Cursor::new(&w.0), self.keys_manager).unwrap();
279                                         deserialized_monitors.push(deserialized_monitor);
280                                 }
281                         }
282
283                         // Before using all the new monitors to check the watch outpoints, use the full set of
284                         // them to ensure we can write and reload our ChannelManager.
285                         {
286                                 let mut channel_monitors = HashMap::new();
287                                 for monitor in deserialized_monitors.iter_mut() {
288                                         channel_monitors.insert(monitor.get_funding_txo().0, monitor);
289                                 }
290
291                                 let mut w = test_utils::TestVecWriter(Vec::new());
292                                 self.node.write(&mut w).unwrap();
293                                 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut ::std::io::Cursor::new(w.0), ChannelManagerReadArgs {
294                                         default_config: *self.node.get_current_default_configuration(),
295                                         keys_manager: self.keys_manager,
296                                         fee_estimator: &test_utils::TestFeeEstimator { sat_per_kw: 253 },
297                                         chain_monitor: self.chain_monitor,
298                                         tx_broadcaster: &test_utils::TestBroadcaster {
299                                                 txn_broadcasted: Mutex::new(self.tx_broadcaster.txn_broadcasted.lock().unwrap().clone())
300                                         },
301                                         logger: &test_utils::TestLogger::new(),
302                                         channel_monitors,
303                                 }).unwrap();
304                         }
305
306                         let persister = test_utils::TestPersister::new();
307                         let broadcaster = test_utils::TestBroadcaster {
308                                 txn_broadcasted: Mutex::new(self.tx_broadcaster.txn_broadcasted.lock().unwrap().clone())
309                         };
310                         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
311                         let chain_monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &broadcaster, &self.logger, &feeest, &persister, &self.keys_manager);
312                         for deserialized_monitor in deserialized_monitors.drain(..) {
313                                 if let Err(_) = chain_monitor.watch_channel(deserialized_monitor.get_funding_txo().0, deserialized_monitor) {
314                                         panic!();
315                                 }
316                         }
317                         assert_eq!(*chain_source.watched_txn.lock().unwrap(), *self.chain_source.watched_txn.lock().unwrap());
318                         assert_eq!(*chain_source.watched_outputs.lock().unwrap(), *self.chain_source.watched_outputs.lock().unwrap());
319                 }
320         }
321 }
322
323 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) {
324         create_chan_between_nodes_with_value(node_a, node_b, 100000, 10001, a_flags, b_flags)
325 }
326
327 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) {
328         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);
329         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(node_a, node_b, &funding_locked);
330         (announcement, as_update, bs_update, channel_id, tx)
331 }
332
333 macro_rules! get_revoke_commit_msgs {
334         ($node: expr, $node_id: expr) => {
335                 {
336                         let events = $node.node.get_and_clear_pending_msg_events();
337                         assert_eq!(events.len(), 2);
338                         (match events[0] {
339                                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
340                                         assert_eq!(*node_id, $node_id);
341                                         (*msg).clone()
342                                 },
343                                 _ => panic!("Unexpected event"),
344                         }, match events[1] {
345                                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
346                                         assert_eq!(*node_id, $node_id);
347                                         assert!(updates.update_add_htlcs.is_empty());
348                                         assert!(updates.update_fulfill_htlcs.is_empty());
349                                         assert!(updates.update_fail_htlcs.is_empty());
350                                         assert!(updates.update_fail_malformed_htlcs.is_empty());
351                                         assert!(updates.update_fee.is_none());
352                                         updates.commitment_signed.clone()
353                                 },
354                                 _ => panic!("Unexpected event"),
355                         })
356                 }
357         }
358 }
359
360 /// Get an specific event message from the pending events queue.
361 #[macro_export]
362 macro_rules! get_event_msg {
363         ($node: expr, $event_type: path, $node_id: expr) => {
364                 {
365                         let events = $node.node.get_and_clear_pending_msg_events();
366                         assert_eq!(events.len(), 1);
367                         match events[0] {
368                                 $event_type { ref node_id, ref msg } => {
369                                         assert_eq!(*node_id, $node_id);
370                                         (*msg).clone()
371                                 },
372                                 _ => panic!("Unexpected event"),
373                         }
374                 }
375         }
376 }
377
378 /// Get a specific event from the pending events queue.
379 #[macro_export]
380 macro_rules! get_event {
381         ($node: expr, $event_type: path) => {
382                 {
383                         let mut events = $node.node.get_and_clear_pending_events();
384                         assert_eq!(events.len(), 1);
385                         let ev = events.pop().unwrap();
386                         match ev {
387                                 $event_type { .. } => {
388                                         ev
389                                 },
390                                 _ => panic!("Unexpected event"),
391                         }
392                 }
393         }
394 }
395
396 #[cfg(test)]
397 macro_rules! get_htlc_update_msgs {
398         ($node: expr, $node_id: expr) => {
399                 {
400                         let events = $node.node.get_and_clear_pending_msg_events();
401                         assert_eq!(events.len(), 1);
402                         match events[0] {
403                                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
404                                         assert_eq!(*node_id, $node_id);
405                                         (*updates).clone()
406                                 },
407                                 _ => panic!("Unexpected event"),
408                         }
409                 }
410         }
411 }
412
413 #[cfg(test)]
414 macro_rules! get_feerate {
415         ($node: expr, $channel_id: expr) => {
416                 {
417                         let chan_lock = $node.node.channel_state.lock().unwrap();
418                         let chan = chan_lock.by_id.get(&$channel_id).unwrap();
419                         chan.get_feerate()
420                 }
421         }
422 }
423
424 /// Returns any local commitment transactions for the channel.
425 #[macro_export]
426 macro_rules! get_local_commitment_txn {
427         ($node: expr, $channel_id: expr) => {
428                 {
429                         let monitors = $node.chain_monitor.chain_monitor.monitors.read().unwrap();
430                         let mut commitment_txn = None;
431                         for (funding_txo, monitor) in monitors.iter() {
432                                 if funding_txo.to_channel_id() == $channel_id {
433                                         commitment_txn = Some(monitor.unsafe_get_latest_holder_commitment_txn(&$node.logger));
434                                         break;
435                                 }
436                         }
437                         commitment_txn.unwrap()
438                 }
439         }
440 }
441
442 /// Check the error from attempting a payment.
443 #[macro_export]
444 macro_rules! unwrap_send_err {
445         ($res: expr, $all_failed: expr, $type: pat, $check: expr) => {
446                 match &$res {
447                         &Err(PaymentSendFailure::AllFailedRetrySafe(ref fails)) if $all_failed => {
448                                 assert_eq!(fails.len(), 1);
449                                 match fails[0] {
450                                         $type => { $check },
451                                         _ => panic!(),
452                                 }
453                         },
454                         &Err(PaymentSendFailure::PartialFailure(ref fails)) if !$all_failed => {
455                                 assert_eq!(fails.len(), 1);
456                                 match fails[0] {
457                                         Err($type) => { $check },
458                                         _ => panic!(),
459                                 }
460                         },
461                         _ => panic!(),
462                 }
463         }
464 }
465
466 /// Check whether N channel monitor(s) have been added.
467 #[macro_export]
468 macro_rules! check_added_monitors {
469         ($node: expr, $count: expr) => {
470                 {
471                         let mut added_monitors = $node.chain_monitor.added_monitors.lock().unwrap();
472                         assert_eq!(added_monitors.len(), $count);
473                         added_monitors.clear();
474                 }
475         }
476 }
477
478 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) {
479         let chan_id = *node.network_chan_count.borrow();
480
481         let events = node.node.get_and_clear_pending_events();
482         assert_eq!(events.len(), 1);
483         match events[0] {
484                 Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
485                         assert_eq!(*channel_value_satoshis, expected_chan_value);
486                         assert_eq!(user_channel_id, expected_user_chan_id);
487
488                         let tx = Transaction { version: chan_id as i32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
489                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
490                         }]};
491                         let funding_outpoint = OutPoint { txid: tx.txid(), index: 0 };
492                         (*temporary_channel_id, tx, funding_outpoint)
493                 },
494                 _ => panic!("Unexpected event"),
495         }
496 }
497
498 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 {
499         node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
500         node_b.node.handle_open_channel(&node_a.node.get_our_node_id(), a_flags, &get_event_msg!(node_a, MessageSendEvent::SendOpenChannel, node_b.node.get_our_node_id()));
501         node_a.node.handle_accept_channel(&node_b.node.get_our_node_id(), b_flags, &get_event_msg!(node_b, MessageSendEvent::SendAcceptChannel, node_a.node.get_our_node_id()));
502
503         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(node_a, channel_value, 42);
504
505         node_a.node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
506         check_added_monitors!(node_a, 0);
507
508         node_b.node.handle_funding_created(&node_a.node.get_our_node_id(), &get_event_msg!(node_a, MessageSendEvent::SendFundingCreated, node_b.node.get_our_node_id()));
509         {
510                 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
511                 assert_eq!(added_monitors.len(), 1);
512                 assert_eq!(added_monitors[0].0, funding_output);
513                 added_monitors.clear();
514         }
515
516         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()));
517         {
518                 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
519                 assert_eq!(added_monitors.len(), 1);
520                 assert_eq!(added_monitors[0].0, funding_output);
521                 added_monitors.clear();
522         }
523
524         let events_4 = node_a.node.get_and_clear_pending_events();
525         assert_eq!(events_4.len(), 0);
526
527         assert_eq!(node_a.tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
528         assert_eq!(node_a.tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
529         node_a.tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
530
531         tx
532 }
533
534 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) {
535         confirm_transaction_at(node_conf, tx, conf_height);
536         connect_blocks(node_conf, CHAN_CONFIRM_DEPTH - 1);
537         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()));
538 }
539
540 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]) {
541         let channel_id;
542         let events_6 = node_conf.node.get_and_clear_pending_msg_events();
543         assert_eq!(events_6.len(), 2);
544         ((match events_6[0] {
545                 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
546                         channel_id = msg.channel_id.clone();
547                         assert_eq!(*node_id, node_recv.node.get_our_node_id());
548                         msg.clone()
549                 },
550                 _ => panic!("Unexpected event"),
551         }, match events_6[1] {
552                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
553                         assert_eq!(*node_id, node_recv.node.get_our_node_id());
554                         msg.clone()
555                 },
556                 _ => panic!("Unexpected event"),
557         }), channel_id)
558 }
559
560 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]) {
561         let conf_height = core::cmp::max(node_a.best_block_info().1 + 1, node_b.best_block_info().1 + 1);
562         create_chan_between_nodes_with_value_confirm_first(node_a, node_b, tx, conf_height);
563         confirm_transaction_at(node_a, tx, conf_height);
564         connect_blocks(node_a, CHAN_CONFIRM_DEPTH - 1);
565         create_chan_between_nodes_with_value_confirm_second(node_b, node_a)
566 }
567
568 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) {
569         let tx = create_chan_between_nodes_with_value_init(node_a, node_b, channel_value, push_msat, a_flags, b_flags);
570         let (msgs, chan_id) = create_chan_between_nodes_with_value_confirm(node_a, node_b, &tx);
571         (msgs, chan_id, tx)
572 }
573
574 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) {
575         node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &as_funding_msgs.0);
576         let bs_announcement_sigs = get_event_msg!(node_b, MessageSendEvent::SendAnnouncementSignatures, node_a.node.get_our_node_id());
577         node_b.node.handle_announcement_signatures(&node_a.node.get_our_node_id(), &as_funding_msgs.1);
578
579         let events_7 = node_b.node.get_and_clear_pending_msg_events();
580         assert_eq!(events_7.len(), 1);
581         let (announcement, bs_update) = match events_7[0] {
582                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
583                         (msg, update_msg)
584                 },
585                 _ => panic!("Unexpected event"),
586         };
587
588         node_a.node.handle_announcement_signatures(&node_b.node.get_our_node_id(), &bs_announcement_sigs);
589         let events_8 = node_a.node.get_and_clear_pending_msg_events();
590         assert_eq!(events_8.len(), 1);
591         let as_update = match events_8[0] {
592                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
593                         assert!(*announcement == *msg);
594                         assert_eq!(update_msg.contents.short_channel_id, announcement.contents.short_channel_id);
595                         assert_eq!(update_msg.contents.short_channel_id, bs_update.contents.short_channel_id);
596                         update_msg
597                 },
598                 _ => panic!("Unexpected event"),
599         };
600
601         *node_a.network_chan_count.borrow_mut() += 1;
602
603         ((*announcement).clone(), (*as_update).clone(), (*bs_update).clone())
604 }
605
606 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) {
607         create_announced_chan_between_nodes_with_value(nodes, a, b, 100000, 10001, a_flags, b_flags)
608 }
609
610 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) {
611         let chan_announcement = create_chan_between_nodes_with_value(&nodes[a], &nodes[b], channel_value, push_msat, a_flags, b_flags);
612         update_nodes_with_chan_announce(nodes, a, b, &chan_announcement.0, &chan_announcement.1, &chan_announcement.2);
613         (chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
614 }
615
616 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) {
617         nodes[a].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
618         let a_events = nodes[a].node.get_and_clear_pending_msg_events();
619         assert!(a_events.len() >= 2);
620
621         // ann should be re-generated by broadcast_node_announcement - check that we have it.
622         let mut found_ann_1 = false;
623         for event in a_events.iter() {
624                 match event {
625                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
626                                 if msg == ann { found_ann_1 = true; }
627                         },
628                         MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
629                         _ => panic!("Unexpected event {:?}", event),
630                 }
631         }
632         assert!(found_ann_1);
633
634         let a_node_announcement = match a_events.last().unwrap() {
635                 MessageSendEvent::BroadcastNodeAnnouncement { ref msg } => {
636                         (*msg).clone()
637                 },
638                 _ => panic!("Unexpected event"),
639         };
640
641         nodes[b].node.broadcast_node_announcement([1, 1, 1], [1; 32], Vec::new());
642         let b_events = nodes[b].node.get_and_clear_pending_msg_events();
643         assert!(b_events.len() >= 2);
644
645         // ann should be re-generated by broadcast_node_announcement - check that we have it.
646         let mut found_ann_2 = false;
647         for event in b_events.iter() {
648                 match event {
649                         MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
650                                 if msg == ann { found_ann_2 = true; }
651                         },
652                         MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
653                         _ => panic!("Unexpected event"),
654                 }
655         }
656         assert!(found_ann_2);
657
658         let b_node_announcement = match b_events.last().unwrap() {
659                 MessageSendEvent::BroadcastNodeAnnouncement { ref msg } => {
660                         (*msg).clone()
661                 },
662                 _ => panic!("Unexpected event"),
663         };
664
665         for node in nodes {
666                 assert!(node.net_graph_msg_handler.handle_channel_announcement(ann).unwrap());
667                 node.net_graph_msg_handler.handle_channel_update(upd_1).unwrap();
668                 node.net_graph_msg_handler.handle_channel_update(upd_2).unwrap();
669                 node.net_graph_msg_handler.handle_node_announcement(&a_node_announcement).unwrap();
670                 node.net_graph_msg_handler.handle_node_announcement(&b_node_announcement).unwrap();
671         }
672 }
673
674 macro_rules! check_spends {
675         ($tx: expr, $($spends_txn: expr),*) => {
676                 {
677                         let get_output = |out_point: &bitcoin::blockdata::transaction::OutPoint| {
678                                 $(
679                                         if out_point.txid == $spends_txn.txid() {
680                                                 return $spends_txn.output.get(out_point.vout as usize).cloned()
681                                         }
682                                 )*
683                                 None
684                         };
685                         let mut total_value_in = 0;
686                         for input in $tx.input.iter() {
687                                 total_value_in += get_output(&input.previous_output).unwrap().value;
688                         }
689                         let mut total_value_out = 0;
690                         for output in $tx.output.iter() {
691                                 total_value_out += output.value;
692                         }
693                         let min_fee = ($tx.get_weight() as u64 + 3) / 4; // One sat per vbyte (ie per weight/4, rounded up)
694                         // Input amount - output amount = fee, so check that out + min_fee is smaller than input
695                         assert!(total_value_out + min_fee <= total_value_in);
696                         $tx.verify(get_output).unwrap();
697                 }
698         }
699 }
700
701 macro_rules! get_closing_signed_broadcast {
702         ($node: expr, $dest_pubkey: expr) => {
703                 {
704                         let events = $node.get_and_clear_pending_msg_events();
705                         assert!(events.len() == 1 || events.len() == 2);
706                         (match events[events.len() - 1] {
707                                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
708                                         assert_eq!(msg.contents.flags & 2, 2);
709                                         msg.clone()
710                                 },
711                                 _ => panic!("Unexpected event"),
712                         }, if events.len() == 2 {
713                                 match events[0] {
714                                         MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
715                                                 assert_eq!(*node_id, $dest_pubkey);
716                                                 Some(msg.clone())
717                                         },
718                                         _ => panic!("Unexpected event"),
719                                 }
720                         } else { None })
721                 }
722         }
723 }
724
725 /// Check that a channel's closing channel update has been broadcasted, and optionally
726 /// check whether an error message event has occurred.
727 #[macro_export]
728 macro_rules! check_closed_broadcast {
729         ($node: expr, $with_error_msg: expr) => {{
730                 let events = $node.node.get_and_clear_pending_msg_events();
731                 assert_eq!(events.len(), if $with_error_msg { 2 } else { 1 });
732                 match events[0] {
733                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
734                                 assert_eq!(msg.contents.flags & 2, 2);
735                         },
736                         _ => panic!("Unexpected event"),
737                 }
738                 if $with_error_msg {
739                         match events[1] {
740                                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
741                                         // TODO: Check node_id
742                                         Some(msg.clone())
743                                 },
744                                 _ => panic!("Unexpected event"),
745                         }
746                 } else { None }
747         }}
748 }
749
750 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) {
751         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) };
752         let (node_b, broadcaster_b) = if close_inbound_first { (&outbound_node.node, &outbound_node.tx_broadcaster) } else { (&inbound_node.node, &inbound_node.tx_broadcaster) };
753         let (tx_a, tx_b);
754
755         node_a.close_channel(channel_id).unwrap();
756         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()));
757
758         let events_1 = node_b.get_and_clear_pending_msg_events();
759         assert!(events_1.len() >= 1);
760         let shutdown_b = match events_1[0] {
761                 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
762                         assert_eq!(node_id, &node_a.get_our_node_id());
763                         msg.clone()
764                 },
765                 _ => panic!("Unexpected event"),
766         };
767
768         let closing_signed_b = if !close_inbound_first {
769                 assert_eq!(events_1.len(), 1);
770                 None
771         } else {
772                 Some(match events_1[1] {
773                         MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
774                                 assert_eq!(node_id, &node_a.get_our_node_id());
775                                 msg.clone()
776                         },
777                         _ => panic!("Unexpected event"),
778                 })
779         };
780
781         node_a.handle_shutdown(&node_b.get_our_node_id(), &InitFeatures::known(), &shutdown_b);
782         let (as_update, bs_update) = if close_inbound_first {
783                 assert!(node_a.get_and_clear_pending_msg_events().is_empty());
784                 node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap());
785                 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
786                 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
787                 let (as_update, closing_signed_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
788
789                 node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap());
790                 let (bs_update, none_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
791                 assert!(none_b.is_none());
792                 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
793                 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
794                 (as_update, bs_update)
795         } else {
796                 let closing_signed_a = get_event_msg!(struct_a, MessageSendEvent::SendClosingSigned, node_b.get_our_node_id());
797
798                 node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a);
799                 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
800                 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
801                 let (bs_update, closing_signed_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
802
803                 node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap());
804                 let (as_update, none_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
805                 assert!(none_a.is_none());
806                 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
807                 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
808                 (as_update, bs_update)
809         };
810         assert_eq!(tx_a, tx_b);
811         check_spends!(tx_a, funding_tx);
812
813         (as_update, bs_update, tx_a)
814 }
815
816 pub struct SendEvent {
817         pub node_id: PublicKey,
818         pub msgs: Vec<msgs::UpdateAddHTLC>,
819         pub commitment_msg: msgs::CommitmentSigned,
820 }
821 impl SendEvent {
822         pub fn from_commitment_update(node_id: PublicKey, updates: msgs::CommitmentUpdate) -> SendEvent {
823                 assert!(updates.update_fulfill_htlcs.is_empty());
824                 assert!(updates.update_fail_htlcs.is_empty());
825                 assert!(updates.update_fail_malformed_htlcs.is_empty());
826                 assert!(updates.update_fee.is_none());
827                 SendEvent { node_id: node_id, msgs: updates.update_add_htlcs, commitment_msg: updates.commitment_signed }
828         }
829
830         pub fn from_event(event: MessageSendEvent) -> SendEvent {
831                 match event {
832                         MessageSendEvent::UpdateHTLCs { node_id, updates } => SendEvent::from_commitment_update(node_id, updates),
833                         _ => panic!("Unexpected event type!"),
834                 }
835         }
836
837         pub fn from_node<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>) -> SendEvent {
838                 let mut events = node.node.get_and_clear_pending_msg_events();
839                 assert_eq!(events.len(), 1);
840                 SendEvent::from_event(events.pop().unwrap())
841         }
842 }
843
844 macro_rules! commitment_signed_dance {
845         ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */) => {
846                 {
847                         check_added_monitors!($node_a, 0);
848                         assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
849                         $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed);
850                         check_added_monitors!($node_a, 1);
851                         commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, false);
852                 }
853         };
854         ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */, true /* return last RAA */) => {
855                 {
856                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!($node_a, $node_b.node.get_our_node_id());
857                         check_added_monitors!($node_b, 0);
858                         assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
859                         $node_b.node.handle_revoke_and_ack(&$node_a.node.get_our_node_id(), &as_revoke_and_ack);
860                         assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
861                         check_added_monitors!($node_b, 1);
862                         $node_b.node.handle_commitment_signed(&$node_a.node.get_our_node_id(), &as_commitment_signed);
863                         let (bs_revoke_and_ack, extra_msg_option) = {
864                                 let events = $node_b.node.get_and_clear_pending_msg_events();
865                                 assert!(events.len() <= 2);
866                                 (match events[0] {
867                                         MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
868                                                 assert_eq!(*node_id, $node_a.node.get_our_node_id());
869                                                 (*msg).clone()
870                                         },
871                                         _ => panic!("Unexpected event"),
872                                 }, events.get(1).map(|e| e.clone()))
873                         };
874                         check_added_monitors!($node_b, 1);
875                         if $fail_backwards {
876                                 assert!($node_a.node.get_and_clear_pending_events().is_empty());
877                                 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
878                         }
879                         (extra_msg_option, bs_revoke_and_ack)
880                 }
881         };
882         ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */, false /* return extra message */, true /* return last RAA */) => {
883                 {
884                         check_added_monitors!($node_a, 0);
885                         assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
886                         $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed);
887                         check_added_monitors!($node_a, 1);
888                         let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
889                         assert!(extra_msg_option.is_none());
890                         bs_revoke_and_ack
891                 }
892         };
893         ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */) => {
894                 {
895                         let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
896                         $node_a.node.handle_revoke_and_ack(&$node_b.node.get_our_node_id(), &bs_revoke_and_ack);
897                         check_added_monitors!($node_a, 1);
898                         extra_msg_option
899                 }
900         };
901         ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, false /* no extra message */) => {
902                 {
903                         assert!(commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true).is_none());
904                 }
905         };
906         ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr) => {
907                 {
908                         commitment_signed_dance!($node_a, $node_b, $commitment_signed, $fail_backwards, true);
909                         if $fail_backwards {
910                                 expect_pending_htlcs_forwardable!($node_a);
911                                 check_added_monitors!($node_a, 1);
912
913                                 let channel_state = $node_a.node.channel_state.lock().unwrap();
914                                 assert_eq!(channel_state.pending_msg_events.len(), 1);
915                                 if let MessageSendEvent::UpdateHTLCs { ref node_id, .. } = channel_state.pending_msg_events[0] {
916                                         assert_ne!(*node_id, $node_b.node.get_our_node_id());
917                                 } else { panic!("Unexpected event"); }
918                         } else {
919                                 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
920                         }
921                 }
922         }
923 }
924
925 /// Get a payment preimage and hash.
926 #[macro_export]
927 macro_rules! get_payment_preimage_hash {
928         ($dest_node: expr) => {
929                 {
930                         let payment_preimage = PaymentPreimage([*$dest_node.network_payment_count.borrow(); 32]);
931                         *$dest_node.network_payment_count.borrow_mut() += 1;
932                         let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner());
933                         let payment_secret = $dest_node.node.create_inbound_payment_for_hash(payment_hash, None, 7200, 0).unwrap();
934                         (payment_preimage, payment_hash, payment_secret)
935                 }
936         }
937 }
938
939 #[cfg(test)]
940 macro_rules! get_route_and_payment_hash {
941         ($send_node: expr, $recv_node: expr, $recv_value: expr) => {{
942                 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!($recv_node);
943                 let net_graph_msg_handler = &$send_node.net_graph_msg_handler;
944                 let route = get_route(&$send_node.node.get_our_node_id(),
945                         &net_graph_msg_handler.network_graph.read().unwrap(),
946                         &$recv_node.node.get_our_node_id(), None, None, &Vec::new(), $recv_value, TEST_FINAL_CLTV, $send_node.logger).unwrap();
947                 (route, payment_hash, payment_preimage, payment_secret)
948         }}
949 }
950
951 macro_rules! expect_pending_htlcs_forwardable_ignore {
952         ($node: expr) => {{
953                 let events = $node.node.get_and_clear_pending_events();
954                 assert_eq!(events.len(), 1);
955                 match events[0] {
956                         Event::PendingHTLCsForwardable { .. } => { },
957                         _ => panic!("Unexpected event"),
958                 };
959         }}
960 }
961
962 macro_rules! expect_pending_htlcs_forwardable {
963         ($node: expr) => {{
964                 expect_pending_htlcs_forwardable_ignore!($node);
965                 $node.node.process_pending_htlc_forwards();
966         }}
967 }
968
969 #[cfg(any(test, feature = "unstable"))]
970 macro_rules! expect_payment_received {
971         ($node: expr, $expected_payment_hash: expr, $expected_payment_secret: expr, $expected_recv_value: expr) => {
972                 let events = $node.node.get_and_clear_pending_events();
973                 assert_eq!(events.len(), 1);
974                 match events[0] {
975                         Event::PaymentReceived { ref payment_hash, ref payment_preimage, ref payment_secret, amt, user_payment_id: _ } => {
976                                 assert_eq!($expected_payment_hash, *payment_hash);
977                                 assert!(payment_preimage.is_none());
978                                 assert_eq!($expected_payment_secret, *payment_secret);
979                                 assert_eq!($expected_recv_value, amt);
980                         },
981                         _ => panic!("Unexpected event"),
982                 }
983         }
984 }
985
986 macro_rules! expect_payment_sent {
987         ($node: expr, $expected_payment_preimage: expr) => {
988                 let events = $node.node.get_and_clear_pending_events();
989                 assert_eq!(events.len(), 1);
990                 match events[0] {
991                         Event::PaymentSent { ref payment_preimage } => {
992                                 assert_eq!($expected_payment_preimage, *payment_preimage);
993                         },
994                         _ => panic!("Unexpected event"),
995                 }
996         }
997 }
998
999 #[cfg(test)]
1000 macro_rules! expect_payment_failed {
1001         ($node: expr, $expected_payment_hash: expr, $rejected_by_dest: expr $(, $expected_error_code: expr, $expected_error_data: expr)*) => {
1002                 let events = $node.node.get_and_clear_pending_events();
1003                 assert_eq!(events.len(), 1);
1004                 match events[0] {
1005                         Event::PaymentFailed { ref payment_hash, rejected_by_dest, ref error_code, ref error_data } => {
1006                                 assert_eq!(*payment_hash, $expected_payment_hash, "unexpected payment_hash");
1007                                 assert_eq!(rejected_by_dest, $rejected_by_dest, "unexpected rejected_by_dest value");
1008                                 assert!(error_code.is_some(), "expected error_code.is_some() = true");
1009                                 assert!(error_data.is_some(), "expected error_data.is_some() = true");
1010                                 $(
1011                                         assert_eq!(error_code.unwrap(), $expected_error_code, "unexpected error code");
1012                                         assert_eq!(&error_data.as_ref().unwrap()[..], $expected_error_data, "unexpected error data");
1013                                 )*
1014                         },
1015                         _ => panic!("Unexpected event"),
1016                 }
1017         }
1018 }
1019
1020 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) {
1021         origin_node.node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
1022         check_added_monitors!(origin_node, expected_paths.len());
1023         pass_along_route(origin_node, expected_paths, recv_value, our_payment_hash, our_payment_secret);
1024 }
1025
1026 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: PaymentSecret, ev: MessageSendEvent, payment_received_expected: bool) {
1027         let mut payment_event = SendEvent::from_event(ev);
1028         let mut prev_node = origin_node;
1029
1030         for (idx, &node) in expected_path.iter().enumerate() {
1031                 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
1032
1033                 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
1034                 check_added_monitors!(node, 0);
1035                 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
1036
1037                 expect_pending_htlcs_forwardable!(node);
1038
1039                 if idx == expected_path.len() - 1 {
1040                         let events_2 = node.node.get_and_clear_pending_events();
1041                         if payment_received_expected {
1042                                 assert_eq!(events_2.len(), 1);
1043                                 match events_2[0] {
1044                                         Event::PaymentReceived { ref payment_hash, ref payment_preimage, ref payment_secret, amt, user_payment_id: _ } => {
1045                                                 assert_eq!(our_payment_hash, *payment_hash);
1046                                                 assert!(payment_preimage.is_none());
1047                                                 assert_eq!(our_payment_secret, *payment_secret);
1048                                                 assert_eq!(amt, recv_value);
1049                                         },
1050                                         _ => panic!("Unexpected event"),
1051                                 }
1052                         } else {
1053                                 assert!(events_2.is_empty());
1054                         }
1055                 } else {
1056                         let mut events_2 = node.node.get_and_clear_pending_msg_events();
1057                         assert_eq!(events_2.len(), 1);
1058                         check_added_monitors!(node, 1);
1059                         payment_event = SendEvent::from_event(events_2.remove(0));
1060                         assert_eq!(payment_event.msgs.len(), 1);
1061                 }
1062
1063                 prev_node = node;
1064         }
1065 }
1066
1067 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) {
1068         let mut events = origin_node.node.get_and_clear_pending_msg_events();
1069         assert_eq!(events.len(), expected_route.len());
1070         for (path_idx, (ev, expected_path)) in events.drain(..).zip(expected_route.iter()).enumerate() {
1071                 // Once we've gotten through all the HTLCs, the last one should result in a
1072                 // PaymentReceived (but each previous one should not!), .
1073                 let expect_payment = path_idx == expected_route.len() - 1;
1074                 pass_along_path(origin_node, expected_path, recv_value, our_payment_hash.clone(), our_payment_secret, ev, expect_payment);
1075         }
1076 }
1077
1078 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) {
1079         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(expected_route.last().unwrap());
1080         send_along_route_with_secret(origin_node, route, &[expected_route], recv_value, our_payment_hash, our_payment_secret);
1081         (our_payment_preimage, our_payment_hash, our_payment_secret)
1082 }
1083
1084 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) {
1085         for path in expected_paths.iter() {
1086                 assert_eq!(path.last().unwrap().node.get_our_node_id(), expected_paths[0].last().unwrap().node.get_our_node_id());
1087         }
1088         assert!(expected_paths[0].last().unwrap().node.claim_funds(our_payment_preimage));
1089         check_added_monitors!(expected_paths[0].last().unwrap(), expected_paths.len());
1090
1091         macro_rules! msgs_from_ev {
1092                 ($ev: expr) => {
1093                         match $ev {
1094                                 &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 } } => {
1095                                         assert!(update_add_htlcs.is_empty());
1096                                         assert_eq!(update_fulfill_htlcs.len(), 1);
1097                                         assert!(update_fail_htlcs.is_empty());
1098                                         assert!(update_fail_malformed_htlcs.is_empty());
1099                                         assert!(update_fee.is_none());
1100                                         ((update_fulfill_htlcs[0].clone(), commitment_signed.clone()), node_id.clone())
1101                                 },
1102                                 _ => panic!("Unexpected event"),
1103                         }
1104                 }
1105         }
1106         let mut per_path_msgs: Vec<((msgs::UpdateFulfillHTLC, msgs::CommitmentSigned), PublicKey)> = Vec::with_capacity(expected_paths.len());
1107         let events = expected_paths[0].last().unwrap().node.get_and_clear_pending_msg_events();
1108         assert_eq!(events.len(), expected_paths.len());
1109         for ev in events.iter() {
1110                 per_path_msgs.push(msgs_from_ev!(ev));
1111         }
1112
1113         for (expected_route, (path_msgs, next_hop)) in expected_paths.iter().zip(per_path_msgs.drain(..)) {
1114                 let mut next_msgs = Some(path_msgs);
1115                 let mut expected_next_node = next_hop;
1116
1117                 macro_rules! last_update_fulfill_dance {
1118                         ($node: expr, $prev_node: expr) => {
1119                                 {
1120                                         $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0);
1121                                         check_added_monitors!($node, 0);
1122                                         assert!($node.node.get_and_clear_pending_msg_events().is_empty());
1123                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
1124                                 }
1125                         }
1126                 }
1127                 macro_rules! mid_update_fulfill_dance {
1128                         ($node: expr, $prev_node: expr, $new_msgs: expr) => {
1129                                 {
1130                                         $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0);
1131                                         check_added_monitors!($node, 1);
1132                                         let new_next_msgs = if $new_msgs {
1133                                                 let events = $node.node.get_and_clear_pending_msg_events();
1134                                                 assert_eq!(events.len(), 1);
1135                                                 let (res, nexthop) = msgs_from_ev!(&events[0]);
1136                                                 expected_next_node = nexthop;
1137                                                 Some(res)
1138                                         } else {
1139                                                 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
1140                                                 None
1141                                         };
1142                                         commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
1143                                         next_msgs = new_next_msgs;
1144                                 }
1145                         }
1146                 }
1147
1148                 let mut prev_node = expected_route.last().unwrap();
1149                 for (idx, node) in expected_route.iter().rev().enumerate().skip(1) {
1150                         assert_eq!(expected_next_node, node.node.get_our_node_id());
1151                         let update_next_msgs = !skip_last || idx != expected_route.len() - 1;
1152                         if next_msgs.is_some() {
1153                                 mid_update_fulfill_dance!(node, prev_node, update_next_msgs);
1154                         } else {
1155                                 assert!(!update_next_msgs);
1156                                 assert!(node.node.get_and_clear_pending_msg_events().is_empty());
1157                         }
1158                         if !skip_last && idx == expected_route.len() - 1 {
1159                                 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
1160                         }
1161
1162                         prev_node = node;
1163                 }
1164
1165                 if !skip_last {
1166                         last_update_fulfill_dance!(origin_node, expected_route.first().unwrap());
1167                         expect_payment_sent!(origin_node, our_payment_preimage);
1168                 }
1169         }
1170 }
1171
1172 pub fn claim_payment<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_route: &[&Node<'a, 'b, 'c>], our_payment_preimage: PaymentPreimage) {
1173         claim_payment_along_route(origin_node, &[expected_route], false, our_payment_preimage);
1174 }
1175
1176 pub const TEST_FINAL_CLTV: u32 = 70;
1177
1178 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) {
1179         let net_graph_msg_handler = &origin_node.net_graph_msg_handler;
1180         let logger = test_utils::TestLogger::new();
1181         let route = get_route(&origin_node.node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &expected_route.last().unwrap().node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), recv_value, TEST_FINAL_CLTV, &logger).unwrap();
1182         assert_eq!(route.paths.len(), 1);
1183         assert_eq!(route.paths[0].len(), expected_route.len());
1184         for (node, hop) in expected_route.iter().zip(route.paths[0].iter()) {
1185                 assert_eq!(hop.pubkey, node.node.get_our_node_id());
1186         }
1187
1188         send_along_route(origin_node, route, expected_route, recv_value)
1189 }
1190
1191 pub fn route_over_limit<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_route: &[&Node<'a, 'b, 'c>], recv_value: u64)  {
1192         let logger = test_utils::TestLogger::new();
1193         let net_graph_msg_handler = &origin_node.net_graph_msg_handler;
1194         let route = get_route(&origin_node.node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &expected_route.last().unwrap().node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), recv_value, TEST_FINAL_CLTV, &logger).unwrap();
1195         assert_eq!(route.paths.len(), 1);
1196         assert_eq!(route.paths[0].len(), expected_route.len());
1197         for (node, hop) in expected_route.iter().zip(route.paths[0].iter()) {
1198                 assert_eq!(hop.pubkey, node.node.get_our_node_id());
1199         }
1200
1201         let (_, our_payment_hash, our_payment_preimage) = get_payment_preimage_hash!(expected_route.last().unwrap());
1202         unwrap_send_err!(origin_node.node.send_payment(&route, our_payment_hash, &Some(our_payment_preimage)), true, APIError::ChannelUnavailable { ref err },
1203                 assert!(err.contains("Cannot send value that would put us over the max HTLC value in flight our peer will accept")));
1204 }
1205
1206 pub fn send_payment<'a, 'b, 'c>(origin: &Node<'a, 'b, 'c>, expected_route: &[&Node<'a, 'b, 'c>], recv_value: u64)  {
1207         let our_payment_preimage = route_payment(&origin, expected_route, recv_value).0;
1208         claim_payment(&origin, expected_route, our_payment_preimage);
1209 }
1210
1211 pub fn fail_payment_along_route<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_route: &[&Node<'a, 'b, 'c>], skip_last: bool, our_payment_hash: PaymentHash)  {
1212         assert!(expected_route.last().unwrap().node.fail_htlc_backwards(&our_payment_hash));
1213         expect_pending_htlcs_forwardable!(expected_route.last().unwrap());
1214         check_added_monitors!(expected_route.last().unwrap(), 1);
1215
1216         let mut next_msgs: Option<(msgs::UpdateFailHTLC, msgs::CommitmentSigned)> = None;
1217         macro_rules! update_fail_dance {
1218                 ($node: expr, $prev_node: expr, $last_node: expr) => {
1219                         {
1220                                 $node.node.handle_update_fail_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0);
1221                                 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, !$last_node);
1222                                 if skip_last && $last_node {
1223                                         expect_pending_htlcs_forwardable!($node);
1224                                 }
1225                         }
1226                 }
1227         }
1228
1229         let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
1230         let mut prev_node = expected_route.last().unwrap();
1231         for (idx, node) in expected_route.iter().rev().enumerate() {
1232                 assert_eq!(expected_next_node, node.node.get_our_node_id());
1233                 if next_msgs.is_some() {
1234                         // We may be the "last node" for the purpose of the commitment dance if we're
1235                         // skipping the last node (implying it is disconnected) and we're the
1236                         // second-to-last node!
1237                         update_fail_dance!(node, prev_node, skip_last && idx == expected_route.len() - 1);
1238                 }
1239
1240                 let events = node.node.get_and_clear_pending_msg_events();
1241                 if !skip_last || idx != expected_route.len() - 1 {
1242                         assert_eq!(events.len(), 1);
1243                         match events[0] {
1244                                 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 } } => {
1245                                         assert!(update_add_htlcs.is_empty());
1246                                         assert!(update_fulfill_htlcs.is_empty());
1247                                         assert_eq!(update_fail_htlcs.len(), 1);
1248                                         assert!(update_fail_malformed_htlcs.is_empty());
1249                                         assert!(update_fee.is_none());
1250                                         expected_next_node = node_id.clone();
1251                                         next_msgs = Some((update_fail_htlcs[0].clone(), commitment_signed.clone()));
1252                                 },
1253                                 _ => panic!("Unexpected event"),
1254                         }
1255                 } else {
1256                         assert!(events.is_empty());
1257                 }
1258                 if !skip_last && idx == expected_route.len() - 1 {
1259                         assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
1260                 }
1261
1262                 prev_node = node;
1263         }
1264
1265         if !skip_last {
1266                 update_fail_dance!(origin_node, expected_route.first().unwrap(), true);
1267
1268                 let events = origin_node.node.get_and_clear_pending_events();
1269                 assert_eq!(events.len(), 1);
1270                 match events[0] {
1271                         Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
1272                                 assert_eq!(payment_hash, our_payment_hash);
1273                                 assert!(rejected_by_dest);
1274                         },
1275                         _ => panic!("Unexpected event"),
1276                 }
1277         }
1278 }
1279
1280 pub fn fail_payment<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_route: &[&Node<'a, 'b, 'c>], our_payment_hash: PaymentHash)  {
1281         fail_payment_along_route(origin_node, expected_route, false, our_payment_hash);
1282 }
1283
1284 pub fn create_chanmon_cfgs(node_count: usize) -> Vec<TestChanMonCfg> {
1285         let mut chan_mon_cfgs = Vec::new();
1286         for i in 0..node_count {
1287                 let tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
1288                 let fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
1289                 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
1290                 let logger = test_utils::TestLogger::with_id(format!("node {}", i));
1291                 let persister = test_utils::TestPersister::new();
1292                 let seed = [i as u8; 32];
1293                 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
1294
1295                 chan_mon_cfgs.push(TestChanMonCfg{ tx_broadcaster, fee_estimator, chain_source, logger, persister, keys_manager });
1296         }
1297
1298         chan_mon_cfgs
1299 }
1300
1301 pub fn create_node_cfgs<'a>(node_count: usize, chanmon_cfgs: &'a Vec<TestChanMonCfg>) -> Vec<NodeCfg<'a>> {
1302         let mut nodes = Vec::new();
1303
1304         for i in 0..node_count {
1305                 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);
1306                 let seed = [i as u8; 32];
1307                 nodes.push(NodeCfg { chain_source: &chanmon_cfgs[i].chain_source, logger: &chanmon_cfgs[i].logger, tx_broadcaster: &chanmon_cfgs[i].tx_broadcaster, fee_estimator: &chanmon_cfgs[i].fee_estimator, chain_monitor, keys_manager: &chanmon_cfgs[i].keys_manager, node_seed: seed });
1308         }
1309
1310         nodes
1311 }
1312
1313 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>> {
1314         let mut chanmgrs = Vec::new();
1315         for i in 0..node_count {
1316                 let mut default_config = UserConfig::default();
1317                 // Set cltv_expiry_delta slightly lower to keep the final CLTV values inside one byte in our
1318                 // tests so that our script-length checks don't fail (see ACCEPTED_HTLC_SCRIPT_WEIGHT).
1319                 default_config.channel_options.cltv_expiry_delta = 6*6;
1320                 default_config.channel_options.announced_channel = true;
1321                 default_config.peer_channel_config_limits.force_announced_channel_preference = false;
1322                 default_config.own_channel_config.our_htlc_minimum_msat = 1000; // sanitization being done by the sender, to exerce receiver logic we need to lift of limit
1323                 let network = Network::Testnet;
1324                 let params = ChainParameters {
1325                         network,
1326                         best_block: BestBlock::from_genesis(network),
1327                 };
1328                 let node = ChannelManager::new(cfgs[i].fee_estimator, &cfgs[i].chain_monitor, cfgs[i].tx_broadcaster, cfgs[i].logger, cfgs[i].keys_manager, if node_config[i].is_some() { node_config[i].clone().unwrap() } else { default_config }, params);
1329                 chanmgrs.push(node);
1330         }
1331
1332         chanmgrs
1333 }
1334
1335 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>> {
1336         let mut nodes = Vec::new();
1337         let chan_count = Rc::new(RefCell::new(0));
1338         let payment_count = Rc::new(RefCell::new(0));
1339         let connect_style = Rc::new(RefCell::new(ConnectStyle::FullBlockViaListen));
1340
1341         for i in 0..node_count {
1342                 let net_graph_msg_handler = NetGraphMsgHandler::new(cfgs[i].chain_source.genesis_hash, None, cfgs[i].logger);
1343                 nodes.push(Node{ chain_source: cfgs[i].chain_source,
1344                                  tx_broadcaster: cfgs[i].tx_broadcaster, chain_monitor: &cfgs[i].chain_monitor,
1345                                  keys_manager: &cfgs[i].keys_manager, node: &chan_mgrs[i], net_graph_msg_handler,
1346                                  node_seed: cfgs[i].node_seed, network_chan_count: chan_count.clone(),
1347                                  network_payment_count: payment_count.clone(), logger: cfgs[i].logger,
1348                                  blocks: RefCell::new(vec![(genesis_block(Network::Testnet).header, 0)]),
1349                                  connect_style: Rc::clone(&connect_style),
1350                 })
1351         }
1352
1353         nodes
1354 }
1355
1356 // Note that the following only works for CLTV values up to 128
1357 pub const ACCEPTED_HTLC_SCRIPT_WEIGHT: usize = 137; //Here we have a diff due to HTLC CLTV expiry being < 2^15 in test
1358 pub const OFFERED_HTLC_SCRIPT_WEIGHT: usize = 133;
1359
1360 #[derive(PartialEq)]
1361 pub enum HTLCType { NONE, TIMEOUT, SUCCESS }
1362 /// Tests that the given node has broadcast transactions for the given Channel
1363 ///
1364 /// First checks that the latest holder commitment tx has been broadcast, unless an explicit
1365 /// commitment_tx is provided, which may be used to test that a remote commitment tx was
1366 /// broadcast and the revoked outputs were claimed.
1367 ///
1368 /// Next tests that there is (or is not) a transaction that spends the commitment transaction
1369 /// that appears to be the type of HTLC transaction specified in has_htlc_tx.
1370 ///
1371 /// All broadcast transactions must be accounted for in one of the above three types of we'll
1372 /// also fail.
1373 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>  {
1374         let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
1375         assert!(node_txn.len() >= if commitment_tx.is_some() { 0 } else { 1 } + if has_htlc_tx == HTLCType::NONE { 0 } else { 1 });
1376
1377         let mut res = Vec::with_capacity(2);
1378         node_txn.retain(|tx| {
1379                 if tx.input.len() == 1 && tx.input[0].previous_output.txid == chan.3.txid() {
1380                         check_spends!(tx, chan.3);
1381                         if commitment_tx.is_none() {
1382                                 res.push(tx.clone());
1383                         }
1384                         false
1385                 } else { true }
1386         });
1387         if let Some(explicit_tx) = commitment_tx {
1388                 res.push(explicit_tx.clone());
1389         }
1390
1391         assert_eq!(res.len(), 1);
1392
1393         if has_htlc_tx != HTLCType::NONE {
1394                 node_txn.retain(|tx| {
1395                         if tx.input.len() == 1 && tx.input[0].previous_output.txid == res[0].txid() {
1396                                 check_spends!(tx, res[0]);
1397                                 if has_htlc_tx == HTLCType::TIMEOUT {
1398                                         assert!(tx.lock_time != 0);
1399                                 } else {
1400                                         assert!(tx.lock_time == 0);
1401                                 }
1402                                 res.push(tx.clone());
1403                                 false
1404                         } else { true }
1405                 });
1406                 assert!(res.len() == 2 || res.len() == 3);
1407                 if res.len() == 3 {
1408                         assert_eq!(res[1], res[2]);
1409                 }
1410         }
1411
1412         assert!(node_txn.is_empty());
1413         res
1414 }
1415
1416 /// Tests that the given node has broadcast a claim transaction against the provided revoked
1417 /// HTLC transaction.
1418 pub fn test_revoked_htlc_claim_txn_broadcast<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, revoked_tx: Transaction, commitment_revoked_tx: Transaction)  {
1419         let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
1420         // We may issue multiple claiming transaction on revoked outputs due to block rescan
1421         // for revoked htlc outputs
1422         if node_txn.len() != 1 && node_txn.len() != 2 && node_txn.len() != 3 { assert!(false); }
1423         node_txn.retain(|tx| {
1424                 if tx.input.len() == 1 && tx.input[0].previous_output.txid == revoked_tx.txid() {
1425                         check_spends!(tx, revoked_tx);
1426                         false
1427                 } else { true }
1428         });
1429         node_txn.retain(|tx| {
1430                 check_spends!(tx, commitment_revoked_tx);
1431                 false
1432         });
1433         assert!(node_txn.is_empty());
1434 }
1435
1436 pub fn check_preimage_claim<'a, 'b, 'c>(node: &Node<'a, 'b, 'c>, prev_txn: &Vec<Transaction>) -> Vec<Transaction>  {
1437         let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
1438
1439         assert!(node_txn.len() >= 1);
1440         assert_eq!(node_txn[0].input.len(), 1);
1441         let mut found_prev = false;
1442
1443         for tx in prev_txn {
1444                 if node_txn[0].input[0].previous_output.txid == tx.txid() {
1445                         check_spends!(node_txn[0], tx);
1446                         assert!(node_txn[0].input[0].witness[2].len() > 106); // must spend an htlc output
1447                         assert_eq!(tx.input.len(), 1); // must spend a commitment tx
1448
1449                         found_prev = true;
1450                         break;
1451                 }
1452         }
1453         assert!(found_prev);
1454
1455         let mut res = Vec::new();
1456         mem::swap(&mut *node_txn, &mut res);
1457         res
1458 }
1459
1460 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)  {
1461         let events_1 = nodes[a].node.get_and_clear_pending_msg_events();
1462         assert_eq!(events_1.len(), 2);
1463         let as_update = match events_1[0] {
1464                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
1465                         msg.clone()
1466                 },
1467                 _ => panic!("Unexpected event"),
1468         };
1469         match events_1[1] {
1470                 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1471                         assert_eq!(node_id, nodes[b].node.get_our_node_id());
1472                         assert_eq!(msg.data, expected_error);
1473                         if needs_err_handle {
1474                                 nodes[b].node.handle_error(&nodes[a].node.get_our_node_id(), msg);
1475                         }
1476                 },
1477                 _ => panic!("Unexpected event"),
1478         }
1479
1480         let events_2 = nodes[b].node.get_and_clear_pending_msg_events();
1481         assert_eq!(events_2.len(), if needs_err_handle { 1 } else { 2 });
1482         let bs_update = match events_2[0] {
1483                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
1484                         msg.clone()
1485                 },
1486                 _ => panic!("Unexpected event"),
1487         };
1488         if !needs_err_handle {
1489                 match events_2[1] {
1490                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1491                                 assert_eq!(node_id, nodes[a].node.get_our_node_id());
1492                                 assert_eq!(msg.data, expected_error);
1493                         },
1494                         _ => panic!("Unexpected event"),
1495                 }
1496         }
1497
1498         for node in nodes {
1499                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
1500                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
1501         }
1502 }
1503
1504 pub fn get_announce_close_broadcast_events<'a, 'b, 'c>(nodes: &Vec<Node<'a, 'b, 'c>>, a: usize, b: usize)  {
1505         handle_announce_close_broadcast_events(nodes, a, b, false, "Commitment or closing transaction was confirmed on chain.");
1506 }
1507
1508 #[cfg(test)]
1509 macro_rules! get_channel_value_stat {
1510         ($node: expr, $channel_id: expr) => {{
1511                 let chan_lock = $node.node.channel_state.lock().unwrap();
1512                 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
1513                 chan.get_value_stat()
1514         }}
1515 }
1516
1517 macro_rules! get_chan_reestablish_msgs {
1518         ($src_node: expr, $dst_node: expr) => {
1519                 {
1520                         let mut res = Vec::with_capacity(1);
1521                         for msg in $src_node.node.get_and_clear_pending_msg_events() {
1522                                 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
1523                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
1524                                         res.push(msg.clone());
1525                                 } else {
1526                                         panic!("Unexpected event")
1527                                 }
1528                         }
1529                         res
1530                 }
1531         }
1532 }
1533
1534 macro_rules! handle_chan_reestablish_msgs {
1535         ($src_node: expr, $dst_node: expr) => {
1536                 {
1537                         let msg_events = $src_node.node.get_and_clear_pending_msg_events();
1538                         let mut idx = 0;
1539                         let funding_locked = if let Some(&MessageSendEvent::SendFundingLocked { ref node_id, ref msg }) = msg_events.get(0) {
1540                                 idx += 1;
1541                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
1542                                 Some(msg.clone())
1543                         } else {
1544                                 None
1545                         };
1546
1547                         if let Some(&MessageSendEvent::SendAnnouncementSignatures { ref node_id, msg: _ }) = msg_events.get(idx) {
1548                                 idx += 1;
1549                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
1550                         }
1551
1552                         let mut revoke_and_ack = None;
1553                         let mut commitment_update = None;
1554                         let order = if let Some(ev) = msg_events.get(idx) {
1555                                 idx += 1;
1556                                 match ev {
1557                                         &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
1558                                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
1559                                                 revoke_and_ack = Some(msg.clone());
1560                                                 RAACommitmentOrder::RevokeAndACKFirst
1561                                         },
1562                                         &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
1563                                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
1564                                                 commitment_update = Some(updates.clone());
1565                                                 RAACommitmentOrder::CommitmentFirst
1566                                         },
1567                                         _ => panic!("Unexpected event"),
1568                                 }
1569                         } else {
1570                                 RAACommitmentOrder::CommitmentFirst
1571                         };
1572
1573                         if let Some(ev) = msg_events.get(idx) {
1574                                 match ev {
1575                                         &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
1576                                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
1577                                                 assert!(revoke_and_ack.is_none());
1578                                                 revoke_and_ack = Some(msg.clone());
1579                                         },
1580                                         &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
1581                                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
1582                                                 assert!(commitment_update.is_none());
1583                                                 commitment_update = Some(updates.clone());
1584                                         },
1585                                         _ => panic!("Unexpected event"),
1586                                 }
1587                         }
1588
1589                         (funding_locked, revoke_and_ack, commitment_update, order)
1590                 }
1591         }
1592 }
1593
1594 /// pending_htlc_adds includes both the holding cell and in-flight update_add_htlcs, whereas
1595 /// for claims/fails they are separated out.
1596 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_cell_htlc_claims: (usize, usize), pending_cell_htlc_fails: (usize, usize), pending_raa: (bool, bool))  {
1597         node_a.node.peer_connected(&node_b.node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1598         let reestablish_1 = get_chan_reestablish_msgs!(node_a, node_b);
1599         node_b.node.peer_connected(&node_a.node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1600         let reestablish_2 = get_chan_reestablish_msgs!(node_b, node_a);
1601
1602         if send_funding_locked.0 {
1603                 // If a expects a funding_locked, it better not think it has received a revoke_and_ack
1604                 // from b
1605                 for reestablish in reestablish_1.iter() {
1606                         assert_eq!(reestablish.next_remote_commitment_number, 0);
1607                 }
1608         }
1609         if send_funding_locked.1 {
1610                 // If b expects a funding_locked, it better not think it has received a revoke_and_ack
1611                 // from a
1612                 for reestablish in reestablish_2.iter() {
1613                         assert_eq!(reestablish.next_remote_commitment_number, 0);
1614                 }
1615         }
1616         if send_funding_locked.0 || send_funding_locked.1 {
1617                 // If we expect any funding_locked's, both sides better have set
1618                 // next_holder_commitment_number to 1
1619                 for reestablish in reestablish_1.iter() {
1620                         assert_eq!(reestablish.next_local_commitment_number, 1);
1621                 }
1622                 for reestablish in reestablish_2.iter() {
1623                         assert_eq!(reestablish.next_local_commitment_number, 1);
1624                 }
1625         }
1626
1627         let mut resp_1 = Vec::new();
1628         for msg in reestablish_1 {
1629                 node_b.node.handle_channel_reestablish(&node_a.node.get_our_node_id(), &msg);
1630                 resp_1.push(handle_chan_reestablish_msgs!(node_b, node_a));
1631         }
1632         if pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
1633                 check_added_monitors!(node_b, 1);
1634         } else {
1635                 check_added_monitors!(node_b, 0);
1636         }
1637
1638         let mut resp_2 = Vec::new();
1639         for msg in reestablish_2 {
1640                 node_a.node.handle_channel_reestablish(&node_b.node.get_our_node_id(), &msg);
1641                 resp_2.push(handle_chan_reestablish_msgs!(node_a, node_b));
1642         }
1643         if pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
1644                 check_added_monitors!(node_a, 1);
1645         } else {
1646                 check_added_monitors!(node_a, 0);
1647         }
1648
1649         // We don't yet support both needing updates, as that would require a different commitment dance:
1650         assert!((pending_htlc_adds.0 == 0 && pending_htlc_claims.0 == 0 && pending_cell_htlc_claims.0 == 0 && pending_cell_htlc_fails.0 == 0) ||
1651                         (pending_htlc_adds.1 == 0 && pending_htlc_claims.1 == 0 && pending_cell_htlc_claims.1 == 0 && pending_cell_htlc_fails.1 == 0));
1652
1653         for chan_msgs in resp_1.drain(..) {
1654                 if send_funding_locked.0 {
1655                         node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), &chan_msgs.0.unwrap());
1656                         let announcement_event = node_a.node.get_and_clear_pending_msg_events();
1657                         if !announcement_event.is_empty() {
1658                                 assert_eq!(announcement_event.len(), 1);
1659                                 if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
1660                                         //TODO: Test announcement_sigs re-sending
1661                                 } else { panic!("Unexpected event!"); }
1662                         }
1663                 } else {
1664                         assert!(chan_msgs.0.is_none());
1665                 }
1666                 if pending_raa.0 {
1667                         assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
1668                         node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap());
1669                         assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
1670                         check_added_monitors!(node_a, 1);
1671                 } else {
1672                         assert!(chan_msgs.1.is_none());
1673                 }
1674                 if pending_htlc_adds.0 != 0 || pending_htlc_claims.0 != 0 || pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
1675                         let commitment_update = chan_msgs.2.unwrap();
1676                         if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
1677                                 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.0 as usize);
1678                         } else {
1679                                 assert!(commitment_update.update_add_htlcs.is_empty());
1680                         }
1681                         assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
1682                         assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
1683                         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
1684                         for update_add in commitment_update.update_add_htlcs {
1685                                 node_a.node.handle_update_add_htlc(&node_b.node.get_our_node_id(), &update_add);
1686                         }
1687                         for update_fulfill in commitment_update.update_fulfill_htlcs {
1688                                 node_a.node.handle_update_fulfill_htlc(&node_b.node.get_our_node_id(), &update_fulfill);
1689                         }
1690                         for update_fail in commitment_update.update_fail_htlcs {
1691                                 node_a.node.handle_update_fail_htlc(&node_b.node.get_our_node_id(), &update_fail);
1692                         }
1693
1694                         if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
1695                                 commitment_signed_dance!(node_a, node_b, commitment_update.commitment_signed, false);
1696                         } else {
1697                                 node_a.node.handle_commitment_signed(&node_b.node.get_our_node_id(), &commitment_update.commitment_signed);
1698                                 check_added_monitors!(node_a, 1);
1699                                 let as_revoke_and_ack = get_event_msg!(node_a, MessageSendEvent::SendRevokeAndACK, node_b.node.get_our_node_id());
1700                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
1701                                 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &as_revoke_and_ack);
1702                                 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
1703                                 check_added_monitors!(node_b, 1);
1704                         }
1705                 } else {
1706                         assert!(chan_msgs.2.is_none());
1707                 }
1708         }
1709
1710         for chan_msgs in resp_2.drain(..) {
1711                 if send_funding_locked.1 {
1712                         node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &chan_msgs.0.unwrap());
1713                         let announcement_event = node_b.node.get_and_clear_pending_msg_events();
1714                         if !announcement_event.is_empty() {
1715                                 assert_eq!(announcement_event.len(), 1);
1716                                 if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
1717                                         //TODO: Test announcement_sigs re-sending
1718                                 } else { panic!("Unexpected event!"); }
1719                         }
1720                 } else {
1721                         assert!(chan_msgs.0.is_none());
1722                 }
1723                 if pending_raa.1 {
1724                         assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
1725                         node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap());
1726                         assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
1727                         check_added_monitors!(node_b, 1);
1728                 } else {
1729                         assert!(chan_msgs.1.is_none());
1730                 }
1731                 if pending_htlc_adds.1 != 0 || pending_htlc_claims.1 != 0 || pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
1732                         let commitment_update = chan_msgs.2.unwrap();
1733                         if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
1734                                 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.1 as usize);
1735                         }
1736                         assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
1737                         assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
1738                         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
1739                         for update_add in commitment_update.update_add_htlcs {
1740                                 node_b.node.handle_update_add_htlc(&node_a.node.get_our_node_id(), &update_add);
1741                         }
1742                         for update_fulfill in commitment_update.update_fulfill_htlcs {
1743                                 node_b.node.handle_update_fulfill_htlc(&node_a.node.get_our_node_id(), &update_fulfill);
1744                         }
1745                         for update_fail in commitment_update.update_fail_htlcs {
1746                                 node_b.node.handle_update_fail_htlc(&node_a.node.get_our_node_id(), &update_fail);
1747                         }
1748
1749                         if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
1750                                 commitment_signed_dance!(node_b, node_a, commitment_update.commitment_signed, false);
1751                         } else {
1752                                 node_b.node.handle_commitment_signed(&node_a.node.get_our_node_id(), &commitment_update.commitment_signed);
1753                                 check_added_monitors!(node_b, 1);
1754                                 let bs_revoke_and_ack = get_event_msg!(node_b, MessageSendEvent::SendRevokeAndACK, node_a.node.get_our_node_id());
1755                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
1756                                 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &bs_revoke_and_ack);
1757                                 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
1758                                 check_added_monitors!(node_a, 1);
1759                         }
1760                 } else {
1761                         assert!(chan_msgs.2.is_none());
1762                 }
1763         }
1764 }