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