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