Merge pull request #351 from TheBlueMatt/2019-07-no-instant
[rust-lightning] / src / ln / functional_test_utils.rs
1 //! A bunch of useful utilities for building networks of nodes and exchanging messages between
2 //! nodes for functional tests.
3
4 use chain::chaininterface;
5 use chain::transaction::OutPoint;
6 use chain::keysinterface::KeysInterface;
7 use ln::channelmanager::{ChannelManager,RAACommitmentOrder, PaymentPreimage, PaymentHash};
8 use ln::router::{Route, Router};
9 use ln::msgs;
10 use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler};
11 use util::test_utils;
12 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
13 use util::errors::APIError;
14 use util::logger::Logger;
15 use util::config::UserConfig;
16
17 use bitcoin::util::hash::BitcoinHash;
18 use bitcoin::blockdata::block::BlockHeader;
19 use bitcoin::blockdata::transaction::{Transaction, TxOut};
20 use bitcoin::network::constants::Network;
21
22 use bitcoin_hashes::sha256::Hash as Sha256;
23 use bitcoin_hashes::Hash;
24
25 use secp256k1::Secp256k1;
26 use secp256k1::key::PublicKey;
27
28 use rand::{thread_rng,Rng};
29
30 use std::cell::RefCell;
31 use std::collections::HashMap;
32 use std::default::Default;
33 use std::rc::Rc;
34 use std::sync::{Arc, Mutex};
35 use std::mem;
36
37 pub const CHAN_CONFIRM_DEPTH: u32 = 100;
38 pub fn confirm_transaction(chain: &chaininterface::ChainWatchInterfaceUtil, tx: &Transaction, chan_id: u32) {
39         assert!(chain.does_match_tx(tx));
40         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
41         chain.block_connected_checked(&header, 1, &[tx; 1], &[chan_id; 1]);
42         for i in 2..CHAN_CONFIRM_DEPTH {
43                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
44                 chain.block_connected_checked(&header, i, &[tx; 0], &[0; 0]);
45         }
46 }
47
48 pub struct Node {
49         pub chain_monitor: Arc<chaininterface::ChainWatchInterfaceUtil>,
50         pub tx_broadcaster: Arc<test_utils::TestBroadcaster>,
51         pub chan_monitor: Arc<test_utils::TestChannelMonitor>,
52         pub keys_manager: Arc<test_utils::TestKeysInterface>,
53         pub node: Arc<ChannelManager>,
54         pub router: Router,
55         pub node_seed: [u8; 32],
56         pub network_payment_count: Rc<RefCell<u8>>,
57         pub network_chan_count: Rc<RefCell<u32>>,
58 }
59 impl Drop for Node {
60         fn drop(&mut self) {
61                 if !::std::thread::panicking() {
62                         // Check that we processed all pending events
63                         assert!(self.node.get_and_clear_pending_msg_events().is_empty());
64                         assert!(self.node.get_and_clear_pending_events().is_empty());
65                         assert!(self.chan_monitor.added_monitors.lock().unwrap().is_empty());
66                 }
67         }
68 }
69
70 pub fn create_chan_between_nodes(node_a: &Node, node_b: &Node) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
71         create_chan_between_nodes_with_value(node_a, node_b, 100000, 10001)
72 }
73
74 pub fn create_chan_between_nodes_with_value(node_a: &Node, node_b: &Node, channel_value: u64, push_msat: u64) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
75         let (funding_locked, channel_id, tx) = create_chan_between_nodes_with_value_a(node_a, node_b, channel_value, push_msat);
76         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(node_a, node_b, &funding_locked);
77         (announcement, as_update, bs_update, channel_id, tx)
78 }
79
80 macro_rules! get_revoke_commit_msgs {
81         ($node: expr, $node_id: expr) => {
82                 {
83                         let events = $node.node.get_and_clear_pending_msg_events();
84                         assert_eq!(events.len(), 2);
85                         (match events[0] {
86                                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
87                                         assert_eq!(*node_id, $node_id);
88                                         (*msg).clone()
89                                 },
90                                 _ => panic!("Unexpected event"),
91                         }, match events[1] {
92                                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
93                                         assert_eq!(*node_id, $node_id);
94                                         assert!(updates.update_add_htlcs.is_empty());
95                                         assert!(updates.update_fulfill_htlcs.is_empty());
96                                         assert!(updates.update_fail_htlcs.is_empty());
97                                         assert!(updates.update_fail_malformed_htlcs.is_empty());
98                                         assert!(updates.update_fee.is_none());
99                                         updates.commitment_signed.clone()
100                                 },
101                                 _ => panic!("Unexpected event"),
102                         })
103                 }
104         }
105 }
106
107 macro_rules! get_event_msg {
108         ($node: expr, $event_type: path, $node_id: expr) => {
109                 {
110                         let events = $node.node.get_and_clear_pending_msg_events();
111                         assert_eq!(events.len(), 1);
112                         match events[0] {
113                                 $event_type { ref node_id, ref msg } => {
114                                         assert_eq!(*node_id, $node_id);
115                                         (*msg).clone()
116                                 },
117                                 _ => panic!("Unexpected event"),
118                         }
119                 }
120         }
121 }
122
123 macro_rules! get_htlc_update_msgs {
124         ($node: expr, $node_id: expr) => {
125                 {
126                         let events = $node.node.get_and_clear_pending_msg_events();
127                         assert_eq!(events.len(), 1);
128                         match events[0] {
129                                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
130                                         assert_eq!(*node_id, $node_id);
131                                         (*updates).clone()
132                                 },
133                                 _ => panic!("Unexpected event"),
134                         }
135                 }
136         }
137 }
138
139 macro_rules! get_feerate {
140         ($node: expr, $channel_id: expr) => {
141                 {
142                         let chan_lock = $node.node.channel_state.lock().unwrap();
143                         let chan = chan_lock.by_id.get(&$channel_id).unwrap();
144                         chan.get_feerate()
145                 }
146         }
147 }
148
149
150 pub fn create_chan_between_nodes_with_value_init(node_a: &Node, node_b: &Node, channel_value: u64, push_msat: u64) -> Transaction {
151         node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42).unwrap();
152         node_b.node.handle_open_channel(&node_a.node.get_our_node_id(), &get_event_msg!(node_a, MessageSendEvent::SendOpenChannel, node_b.node.get_our_node_id())).unwrap();
153         node_a.node.handle_accept_channel(&node_b.node.get_our_node_id(), &get_event_msg!(node_b, MessageSendEvent::SendAcceptChannel, node_a.node.get_our_node_id())).unwrap();
154
155         let chan_id = *node_a.network_chan_count.borrow();
156         let tx;
157         let funding_output;
158
159         let events_2 = node_a.node.get_and_clear_pending_events();
160         assert_eq!(events_2.len(), 1);
161         match events_2[0] {
162                 Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
163                         assert_eq!(*channel_value_satoshis, channel_value);
164                         assert_eq!(user_channel_id, 42);
165
166                         tx = Transaction { version: chan_id as u32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
167                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
168                         }]};
169                         funding_output = OutPoint::new(tx.txid(), 0);
170
171                         node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
172                         let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
173                         assert_eq!(added_monitors.len(), 1);
174                         assert_eq!(added_monitors[0].0, funding_output);
175                         added_monitors.clear();
176                 },
177                 _ => panic!("Unexpected event"),
178         }
179
180         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())).unwrap();
181         {
182                 let mut added_monitors = node_b.chan_monitor.added_monitors.lock().unwrap();
183                 assert_eq!(added_monitors.len(), 1);
184                 assert_eq!(added_monitors[0].0, funding_output);
185                 added_monitors.clear();
186         }
187
188         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())).unwrap();
189         {
190                 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
191                 assert_eq!(added_monitors.len(), 1);
192                 assert_eq!(added_monitors[0].0, funding_output);
193                 added_monitors.clear();
194         }
195
196         let events_4 = node_a.node.get_and_clear_pending_events();
197         assert_eq!(events_4.len(), 1);
198         match events_4[0] {
199                 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
200                         assert_eq!(user_channel_id, 42);
201                         assert_eq!(*funding_txo, funding_output);
202                 },
203                 _ => panic!("Unexpected event"),
204         };
205
206         tx
207 }
208
209 pub fn create_chan_between_nodes_with_value_confirm(node_a: &Node, node_b: &Node, tx: &Transaction) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32]) {
210         confirm_transaction(&node_b.chain_monitor, &tx, tx.version);
211         node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), &get_event_msg!(node_b, MessageSendEvent::SendFundingLocked, node_a.node.get_our_node_id())).unwrap();
212
213         let channel_id;
214
215         confirm_transaction(&node_a.chain_monitor, &tx, tx.version);
216         let events_6 = node_a.node.get_and_clear_pending_msg_events();
217         assert_eq!(events_6.len(), 2);
218         ((match events_6[0] {
219                 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
220                         channel_id = msg.channel_id.clone();
221                         assert_eq!(*node_id, node_b.node.get_our_node_id());
222                         msg.clone()
223                 },
224                 _ => panic!("Unexpected event"),
225         }, match events_6[1] {
226                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
227                         assert_eq!(*node_id, node_b.node.get_our_node_id());
228                         msg.clone()
229                 },
230                 _ => panic!("Unexpected event"),
231         }), channel_id)
232 }
233
234 pub fn create_chan_between_nodes_with_value_a(node_a: &Node, node_b: &Node, channel_value: u64, push_msat: u64) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32], Transaction) {
235         let tx = create_chan_between_nodes_with_value_init(node_a, node_b, channel_value, push_msat);
236         let (msgs, chan_id) = create_chan_between_nodes_with_value_confirm(node_a, node_b, &tx);
237         (msgs, chan_id, tx)
238 }
239
240 pub fn create_chan_between_nodes_with_value_b(node_a: &Node, node_b: &Node, as_funding_msgs: &(msgs::FundingLocked, msgs::AnnouncementSignatures)) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate) {
241         node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &as_funding_msgs.0).unwrap();
242         let bs_announcement_sigs = get_event_msg!(node_b, MessageSendEvent::SendAnnouncementSignatures, node_a.node.get_our_node_id());
243         node_b.node.handle_announcement_signatures(&node_a.node.get_our_node_id(), &as_funding_msgs.1).unwrap();
244
245         let events_7 = node_b.node.get_and_clear_pending_msg_events();
246         assert_eq!(events_7.len(), 1);
247         let (announcement, bs_update) = match events_7[0] {
248                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
249                         (msg, update_msg)
250                 },
251                 _ => panic!("Unexpected event"),
252         };
253
254         node_a.node.handle_announcement_signatures(&node_b.node.get_our_node_id(), &bs_announcement_sigs).unwrap();
255         let events_8 = node_a.node.get_and_clear_pending_msg_events();
256         assert_eq!(events_8.len(), 1);
257         let as_update = match events_8[0] {
258                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
259                         assert!(*announcement == *msg);
260                         assert_eq!(update_msg.contents.short_channel_id, announcement.contents.short_channel_id);
261                         assert_eq!(update_msg.contents.short_channel_id, bs_update.contents.short_channel_id);
262                         update_msg
263                 },
264                 _ => panic!("Unexpected event"),
265         };
266
267         *node_a.network_chan_count.borrow_mut() += 1;
268
269         ((*announcement).clone(), (*as_update).clone(), (*bs_update).clone())
270 }
271
272 pub fn create_announced_chan_between_nodes(nodes: &Vec<Node>, a: usize, b: usize) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
273         create_announced_chan_between_nodes_with_value(nodes, a, b, 100000, 10001)
274 }
275
276 pub fn create_announced_chan_between_nodes_with_value(nodes: &Vec<Node>, a: usize, b: usize, channel_value: u64, push_msat: u64) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
277         let chan_announcement = create_chan_between_nodes_with_value(&nodes[a], &nodes[b], channel_value, push_msat);
278         for node in nodes {
279                 assert!(node.router.handle_channel_announcement(&chan_announcement.0).unwrap());
280                 node.router.handle_channel_update(&chan_announcement.1).unwrap();
281                 node.router.handle_channel_update(&chan_announcement.2).unwrap();
282         }
283         (chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
284 }
285
286 macro_rules! check_spends {
287         ($tx: expr, $spends_tx: expr) => {
288                 {
289                         let mut funding_tx_map = HashMap::new();
290                         let spends_tx = $spends_tx;
291                         funding_tx_map.insert(spends_tx.txid(), spends_tx);
292                         $tx.verify(&funding_tx_map).unwrap();
293                 }
294         }
295 }
296
297 macro_rules! get_closing_signed_broadcast {
298         ($node: expr, $dest_pubkey: expr) => {
299                 {
300                         let events = $node.get_and_clear_pending_msg_events();
301                         assert!(events.len() == 1 || events.len() == 2);
302                         (match events[events.len() - 1] {
303                                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
304                                         assert_eq!(msg.contents.flags & 2, 2);
305                                         msg.clone()
306                                 },
307                                 _ => panic!("Unexpected event"),
308                         }, if events.len() == 2 {
309                                 match events[0] {
310                                         MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
311                                                 assert_eq!(*node_id, $dest_pubkey);
312                                                 Some(msg.clone())
313                                         },
314                                         _ => panic!("Unexpected event"),
315                                 }
316                         } else { None })
317                 }
318         }
319 }
320
321 macro_rules! check_closed_broadcast {
322         ($node: expr) => {{
323                 let events = $node.node.get_and_clear_pending_msg_events();
324                 assert_eq!(events.len(), 1);
325                 match events[0] {
326                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
327                                 assert_eq!(msg.contents.flags & 2, 2);
328                         },
329                         _ => panic!("Unexpected event"),
330                 }
331         }}
332 }
333
334 pub fn close_channel(outbound_node: &Node, inbound_node: &Node, channel_id: &[u8; 32], funding_tx: Transaction, close_inbound_first: bool) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, Transaction) {
335         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) };
336         let (node_b, broadcaster_b) = if close_inbound_first { (&outbound_node.node, &outbound_node.tx_broadcaster) } else { (&inbound_node.node, &inbound_node.tx_broadcaster) };
337         let (tx_a, tx_b);
338
339         node_a.close_channel(channel_id).unwrap();
340         node_b.handle_shutdown(&node_a.get_our_node_id(), &get_event_msg!(struct_a, MessageSendEvent::SendShutdown, node_b.get_our_node_id())).unwrap();
341
342         let events_1 = node_b.get_and_clear_pending_msg_events();
343         assert!(events_1.len() >= 1);
344         let shutdown_b = match events_1[0] {
345                 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
346                         assert_eq!(node_id, &node_a.get_our_node_id());
347                         msg.clone()
348                 },
349                 _ => panic!("Unexpected event"),
350         };
351
352         let closing_signed_b = if !close_inbound_first {
353                 assert_eq!(events_1.len(), 1);
354                 None
355         } else {
356                 Some(match events_1[1] {
357                         MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
358                                 assert_eq!(node_id, &node_a.get_our_node_id());
359                                 msg.clone()
360                         },
361                         _ => panic!("Unexpected event"),
362                 })
363         };
364
365         node_a.handle_shutdown(&node_b.get_our_node_id(), &shutdown_b).unwrap();
366         let (as_update, bs_update) = if close_inbound_first {
367                 assert!(node_a.get_and_clear_pending_msg_events().is_empty());
368                 node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
369                 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
370                 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
371                 let (as_update, closing_signed_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
372
373                 node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap()).unwrap();
374                 let (bs_update, none_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
375                 assert!(none_b.is_none());
376                 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
377                 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
378                 (as_update, bs_update)
379         } else {
380                 let closing_signed_a = get_event_msg!(struct_a, MessageSendEvent::SendClosingSigned, node_b.get_our_node_id());
381
382                 node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a).unwrap();
383                 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
384                 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
385                 let (bs_update, closing_signed_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
386
387                 node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
388                 let (as_update, none_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
389                 assert!(none_a.is_none());
390                 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
391                 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
392                 (as_update, bs_update)
393         };
394         assert_eq!(tx_a, tx_b);
395         check_spends!(tx_a, funding_tx);
396
397         (as_update, bs_update, tx_a)
398 }
399
400 pub struct SendEvent {
401         pub node_id: PublicKey,
402         pub msgs: Vec<msgs::UpdateAddHTLC>,
403         pub commitment_msg: msgs::CommitmentSigned,
404 }
405 impl SendEvent {
406         pub fn from_commitment_update(node_id: PublicKey, updates: msgs::CommitmentUpdate) -> SendEvent {
407                 assert!(updates.update_fulfill_htlcs.is_empty());
408                 assert!(updates.update_fail_htlcs.is_empty());
409                 assert!(updates.update_fail_malformed_htlcs.is_empty());
410                 assert!(updates.update_fee.is_none());
411                 SendEvent { node_id: node_id, msgs: updates.update_add_htlcs, commitment_msg: updates.commitment_signed }
412         }
413
414         pub fn from_event(event: MessageSendEvent) -> SendEvent {
415                 match event {
416                         MessageSendEvent::UpdateHTLCs { node_id, updates } => SendEvent::from_commitment_update(node_id, updates),
417                         _ => panic!("Unexpected event type!"),
418                 }
419         }
420
421         pub fn from_node(node: &Node) -> SendEvent {
422                 let mut events = node.node.get_and_clear_pending_msg_events();
423                 assert_eq!(events.len(), 1);
424                 SendEvent::from_event(events.pop().unwrap())
425         }
426 }
427
428 macro_rules! check_added_monitors {
429         ($node: expr, $count: expr) => {
430                 {
431                         let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
432                         assert_eq!(added_monitors.len(), $count);
433                         added_monitors.clear();
434                 }
435         }
436 }
437
438 macro_rules! commitment_signed_dance {
439         ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */) => {
440                 {
441                         check_added_monitors!($node_a, 0);
442                         assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
443                         $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
444                         check_added_monitors!($node_a, 1);
445                         commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, false);
446                 }
447         };
448         ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */, true /* return last RAA */) => {
449                 {
450                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!($node_a, $node_b.node.get_our_node_id());
451                         check_added_monitors!($node_b, 0);
452                         assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
453                         $node_b.node.handle_revoke_and_ack(&$node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
454                         assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
455                         check_added_monitors!($node_b, 1);
456                         $node_b.node.handle_commitment_signed(&$node_a.node.get_our_node_id(), &as_commitment_signed).unwrap();
457                         let (bs_revoke_and_ack, extra_msg_option) = {
458                                 let events = $node_b.node.get_and_clear_pending_msg_events();
459                                 assert!(events.len() <= 2);
460                                 (match events[0] {
461                                         MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
462                                                 assert_eq!(*node_id, $node_a.node.get_our_node_id());
463                                                 (*msg).clone()
464                                         },
465                                         _ => panic!("Unexpected event"),
466                                 }, events.get(1).map(|e| e.clone()))
467                         };
468                         check_added_monitors!($node_b, 1);
469                         if $fail_backwards {
470                                 assert!($node_a.node.get_and_clear_pending_events().is_empty());
471                                 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
472                         }
473                         (extra_msg_option, bs_revoke_and_ack)
474                 }
475         };
476         ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */, false /* return extra message */, true /* return last RAA */) => {
477                 {
478                         check_added_monitors!($node_a, 0);
479                         assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
480                         $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
481                         check_added_monitors!($node_a, 1);
482                         let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
483                         assert!(extra_msg_option.is_none());
484                         bs_revoke_and_ack
485                 }
486         };
487         ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */) => {
488                 {
489                         let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
490                         $node_a.node.handle_revoke_and_ack(&$node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
491                         check_added_monitors!($node_a, 1);
492                         extra_msg_option
493                 }
494         };
495         ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, false /* no extra message */) => {
496                 {
497                         assert!(commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true).is_none());
498                 }
499         };
500         ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr) => {
501                 {
502                         commitment_signed_dance!($node_a, $node_b, $commitment_signed, $fail_backwards, true);
503                         if $fail_backwards {
504                                 expect_pending_htlcs_forwardable!($node_a);
505                                 check_added_monitors!($node_a, 1);
506
507                                 let channel_state = $node_a.node.channel_state.lock().unwrap();
508                                 assert_eq!(channel_state.pending_msg_events.len(), 1);
509                                 if let MessageSendEvent::UpdateHTLCs { ref node_id, .. } = channel_state.pending_msg_events[0] {
510                                         assert_ne!(*node_id, $node_b.node.get_our_node_id());
511                                 } else { panic!("Unexpected event"); }
512                         } else {
513                                 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
514                         }
515                 }
516         }
517 }
518
519 macro_rules! get_payment_preimage_hash {
520         ($node: expr) => {
521                 {
522                         let payment_preimage = PaymentPreimage([*$node.network_payment_count.borrow(); 32]);
523                         *$node.network_payment_count.borrow_mut() += 1;
524                         let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner());
525                         (payment_preimage, payment_hash)
526                 }
527         }
528 }
529
530 macro_rules! expect_pending_htlcs_forwardable {
531         ($node: expr) => {{
532                 let events = $node.node.get_and_clear_pending_events();
533                 assert_eq!(events.len(), 1);
534                 match events[0] {
535                         Event::PendingHTLCsForwardable { .. } => { },
536                         _ => panic!("Unexpected event"),
537                 };
538                 $node.node.process_pending_htlc_forwards();
539         }}
540 }
541
542 macro_rules! expect_payment_received {
543         ($node: expr, $expected_payment_hash: expr, $expected_recv_value: expr) => {
544                 let events = $node.node.get_and_clear_pending_events();
545                 assert_eq!(events.len(), 1);
546                 match events[0] {
547                         Event::PaymentReceived { ref payment_hash, amt } => {
548                                 assert_eq!($expected_payment_hash, *payment_hash);
549                                 assert_eq!($expected_recv_value, amt);
550                         },
551                         _ => panic!("Unexpected event"),
552                 }
553         }
554 }
555
556 macro_rules! expect_payment_sent {
557         ($node: expr, $expected_payment_preimage: expr) => {
558                 let events = $node.node.get_and_clear_pending_events();
559                 assert_eq!(events.len(), 1);
560                 match events[0] {
561                         Event::PaymentSent { ref payment_preimage } => {
562                                 assert_eq!($expected_payment_preimage, *payment_preimage);
563                         },
564                         _ => panic!("Unexpected event"),
565                 }
566         }
567 }
568
569 pub fn send_along_route_with_hash(origin_node: &Node, route: Route, expected_route: &[&Node], recv_value: u64, our_payment_hash: PaymentHash) {
570         let mut payment_event = {
571                 origin_node.node.send_payment(route, our_payment_hash).unwrap();
572                 check_added_monitors!(origin_node, 1);
573
574                 let mut events = origin_node.node.get_and_clear_pending_msg_events();
575                 assert_eq!(events.len(), 1);
576                 SendEvent::from_event(events.remove(0))
577         };
578         let mut prev_node = origin_node;
579
580         for (idx, &node) in expected_route.iter().enumerate() {
581                 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
582
583                 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
584                 check_added_monitors!(node, 0);
585                 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
586
587                 expect_pending_htlcs_forwardable!(node);
588
589                 if idx == expected_route.len() - 1 {
590                         let events_2 = node.node.get_and_clear_pending_events();
591                         assert_eq!(events_2.len(), 1);
592                         match events_2[0] {
593                                 Event::PaymentReceived { ref payment_hash, amt } => {
594                                         assert_eq!(our_payment_hash, *payment_hash);
595                                         assert_eq!(amt, recv_value);
596                                 },
597                                 _ => panic!("Unexpected event"),
598                         }
599                 } else {
600                         let mut events_2 = node.node.get_and_clear_pending_msg_events();
601                         assert_eq!(events_2.len(), 1);
602                         check_added_monitors!(node, 1);
603                         payment_event = SendEvent::from_event(events_2.remove(0));
604                         assert_eq!(payment_event.msgs.len(), 1);
605                 }
606
607                 prev_node = node;
608         }
609 }
610
611 pub fn send_along_route(origin_node: &Node, route: Route, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
612         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(origin_node);
613         send_along_route_with_hash(origin_node, route, expected_route, recv_value, our_payment_hash);
614         (our_payment_preimage, our_payment_hash)
615 }
616
617 pub fn claim_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_preimage: PaymentPreimage) {
618         assert!(expected_route.last().unwrap().node.claim_funds(our_payment_preimage));
619         check_added_monitors!(expected_route.last().unwrap(), 1);
620
621         let mut next_msgs: Option<(msgs::UpdateFulfillHTLC, msgs::CommitmentSigned)> = None;
622         let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
623         macro_rules! get_next_msgs {
624                 ($node: expr) => {
625                         {
626                                 let events = $node.node.get_and_clear_pending_msg_events();
627                                 assert_eq!(events.len(), 1);
628                                 match events[0] {
629                                         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 } } => {
630                                                 assert!(update_add_htlcs.is_empty());
631                                                 assert_eq!(update_fulfill_htlcs.len(), 1);
632                                                 assert!(update_fail_htlcs.is_empty());
633                                                 assert!(update_fail_malformed_htlcs.is_empty());
634                                                 assert!(update_fee.is_none());
635                                                 expected_next_node = node_id.clone();
636                                                 Some((update_fulfill_htlcs[0].clone(), commitment_signed.clone()))
637                                         },
638                                         _ => panic!("Unexpected event"),
639                                 }
640                         }
641                 }
642         }
643
644         macro_rules! last_update_fulfill_dance {
645                 ($node: expr, $prev_node: expr) => {
646                         {
647                                 $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
648                                 check_added_monitors!($node, 0);
649                                 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
650                                 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
651                         }
652                 }
653         }
654         macro_rules! mid_update_fulfill_dance {
655                 ($node: expr, $prev_node: expr, $new_msgs: expr) => {
656                         {
657                                 $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
658                                 check_added_monitors!($node, 1);
659                                 let new_next_msgs = if $new_msgs {
660                                         get_next_msgs!($node)
661                                 } else {
662                                         assert!($node.node.get_and_clear_pending_msg_events().is_empty());
663                                         None
664                                 };
665                                 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
666                                 next_msgs = new_next_msgs;
667                         }
668                 }
669         }
670
671         let mut prev_node = expected_route.last().unwrap();
672         for (idx, node) in expected_route.iter().rev().enumerate() {
673                 assert_eq!(expected_next_node, node.node.get_our_node_id());
674                 let update_next_msgs = !skip_last || idx != expected_route.len() - 1;
675                 if next_msgs.is_some() {
676                         mid_update_fulfill_dance!(node, prev_node, update_next_msgs);
677                 } else if update_next_msgs {
678                         next_msgs = get_next_msgs!(node);
679                 } else {
680                         assert!(node.node.get_and_clear_pending_msg_events().is_empty());
681                 }
682                 if !skip_last && idx == expected_route.len() - 1 {
683                         assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
684                 }
685
686                 prev_node = node;
687         }
688
689         if !skip_last {
690                 last_update_fulfill_dance!(origin_node, expected_route.first().unwrap());
691                 expect_payment_sent!(origin_node, our_payment_preimage);
692         }
693 }
694
695 pub fn claim_payment(origin_node: &Node, expected_route: &[&Node], our_payment_preimage: PaymentPreimage) {
696         claim_payment_along_route(origin_node, expected_route, false, our_payment_preimage);
697 }
698
699 pub const TEST_FINAL_CLTV: u32 = 32;
700
701 pub fn route_payment(origin_node: &Node, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
702         let route = origin_node.router.get_route(&expected_route.last().unwrap().node.get_our_node_id(), None, &Vec::new(), recv_value, TEST_FINAL_CLTV).unwrap();
703         assert_eq!(route.hops.len(), expected_route.len());
704         for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
705                 assert_eq!(hop.pubkey, node.node.get_our_node_id());
706         }
707
708         send_along_route(origin_node, route, expected_route, recv_value)
709 }
710
711 pub fn route_over_limit(origin_node: &Node, expected_route: &[&Node], recv_value: u64) {
712         let route = origin_node.router.get_route(&expected_route.last().unwrap().node.get_our_node_id(), None, &Vec::new(), recv_value, TEST_FINAL_CLTV).unwrap();
713         assert_eq!(route.hops.len(), expected_route.len());
714         for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
715                 assert_eq!(hop.pubkey, node.node.get_our_node_id());
716         }
717
718         let (_, our_payment_hash) = get_payment_preimage_hash!(origin_node);
719
720         let err = origin_node.node.send_payment(route, our_payment_hash).err().unwrap();
721         match err {
722                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over the max HTLC value in flight"),
723                 _ => panic!("Unknown error variants"),
724         };
725 }
726
727 pub fn send_payment(origin: &Node, expected_route: &[&Node], recv_value: u64) {
728         let our_payment_preimage = route_payment(&origin, expected_route, recv_value).0;
729         claim_payment(&origin, expected_route, our_payment_preimage);
730 }
731
732 pub fn fail_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_hash: PaymentHash) {
733         assert!(expected_route.last().unwrap().node.fail_htlc_backwards(&our_payment_hash));
734         expect_pending_htlcs_forwardable!(expected_route.last().unwrap());
735         check_added_monitors!(expected_route.last().unwrap(), 1);
736
737         let mut next_msgs: Option<(msgs::UpdateFailHTLC, msgs::CommitmentSigned)> = None;
738         macro_rules! update_fail_dance {
739                 ($node: expr, $prev_node: expr, $last_node: expr) => {
740                         {
741                                 $node.node.handle_update_fail_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
742                                 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, !$last_node);
743                                 if skip_last && $last_node {
744                                         expect_pending_htlcs_forwardable!($node);
745                                 }
746                         }
747                 }
748         }
749
750         let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
751         let mut prev_node = expected_route.last().unwrap();
752         for (idx, node) in expected_route.iter().rev().enumerate() {
753                 assert_eq!(expected_next_node, node.node.get_our_node_id());
754                 if next_msgs.is_some() {
755                         // We may be the "last node" for the purpose of the commitment dance if we're
756                         // skipping the last node (implying it is disconnected) and we're the
757                         // second-to-last node!
758                         update_fail_dance!(node, prev_node, skip_last && idx == expected_route.len() - 1);
759                 }
760
761                 let events = node.node.get_and_clear_pending_msg_events();
762                 if !skip_last || idx != expected_route.len() - 1 {
763                         assert_eq!(events.len(), 1);
764                         match events[0] {
765                                 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 } } => {
766                                         assert!(update_add_htlcs.is_empty());
767                                         assert!(update_fulfill_htlcs.is_empty());
768                                         assert_eq!(update_fail_htlcs.len(), 1);
769                                         assert!(update_fail_malformed_htlcs.is_empty());
770                                         assert!(update_fee.is_none());
771                                         expected_next_node = node_id.clone();
772                                         next_msgs = Some((update_fail_htlcs[0].clone(), commitment_signed.clone()));
773                                 },
774                                 _ => panic!("Unexpected event"),
775                         }
776                 } else {
777                         assert!(events.is_empty());
778                 }
779                 if !skip_last && idx == expected_route.len() - 1 {
780                         assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
781                 }
782
783                 prev_node = node;
784         }
785
786         if !skip_last {
787                 update_fail_dance!(origin_node, expected_route.first().unwrap(), true);
788
789                 let events = origin_node.node.get_and_clear_pending_events();
790                 assert_eq!(events.len(), 1);
791                 match events[0] {
792                         Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
793                                 assert_eq!(payment_hash, our_payment_hash);
794                                 assert!(rejected_by_dest);
795                         },
796                         _ => panic!("Unexpected event"),
797                 }
798         }
799 }
800
801 pub fn fail_payment(origin_node: &Node, expected_route: &[&Node], our_payment_hash: PaymentHash) {
802         fail_payment_along_route(origin_node, expected_route, false, our_payment_hash);
803 }
804
805 pub fn create_network(node_count: usize) -> Vec<Node> {
806         let mut nodes = Vec::new();
807         let mut rng = thread_rng();
808         let secp_ctx = Secp256k1::new();
809
810         let chan_count = Rc::new(RefCell::new(0));
811         let payment_count = Rc::new(RefCell::new(0));
812
813         for i in 0..node_count {
814                 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::with_id(format!("node {}", i)));
815                 let feeest = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 });
816                 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
817                 let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())});
818                 let mut seed = [0; 32];
819                 rng.fill_bytes(&mut seed);
820                 let keys_manager = Arc::new(test_utils::TestKeysInterface::new(&seed, Network::Testnet, Arc::clone(&logger)));
821                 let chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(chain_monitor.clone(), tx_broadcaster.clone(), logger.clone(), feeest.clone()));
822                 let mut config = UserConfig::new();
823                 config.channel_options.announced_channel = true;
824                 config.peer_channel_config_limits.force_announced_channel_preference = false;
825                 let node = ChannelManager::new(Network::Testnet, feeest.clone(), chan_monitor.clone(), chain_monitor.clone(), tx_broadcaster.clone(), Arc::clone(&logger), keys_manager.clone(), config).unwrap();
826                 let router = Router::new(PublicKey::from_secret_key(&secp_ctx, &keys_manager.get_node_secret()), chain_monitor.clone(), Arc::clone(&logger));
827                 nodes.push(Node { chain_monitor, tx_broadcaster, chan_monitor, node, router, keys_manager, node_seed: seed,
828                         network_payment_count: payment_count.clone(),
829                         network_chan_count: chan_count.clone(),
830                 });
831         }
832
833         nodes
834 }
835
836 #[derive(PartialEq)]
837 pub enum HTLCType { NONE, TIMEOUT, SUCCESS }
838 /// Tests that the given node has broadcast transactions for the given Channel
839 ///
840 /// First checks that the latest local commitment tx has been broadcast, unless an explicit
841 /// commitment_tx is provided, which may be used to test that a remote commitment tx was
842 /// broadcast and the revoked outputs were claimed.
843 ///
844 /// Next tests that there is (or is not) a transaction that spends the commitment transaction
845 /// that appears to be the type of HTLC transaction specified in has_htlc_tx.
846 ///
847 /// All broadcast transactions must be accounted for in one of the above three types of we'll
848 /// also fail.
849 pub fn test_txn_broadcast(node: &Node, chan: &(msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction), commitment_tx: Option<Transaction>, has_htlc_tx: HTLCType) -> Vec<Transaction> {
850         let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
851         assert!(node_txn.len() >= if commitment_tx.is_some() { 0 } else { 1 } + if has_htlc_tx == HTLCType::NONE { 0 } else { 1 });
852
853         let mut res = Vec::with_capacity(2);
854         node_txn.retain(|tx| {
855                 if tx.input.len() == 1 && tx.input[0].previous_output.txid == chan.3.txid() {
856                         check_spends!(tx, chan.3.clone());
857                         if commitment_tx.is_none() {
858                                 res.push(tx.clone());
859                         }
860                         false
861                 } else { true }
862         });
863         if let Some(explicit_tx) = commitment_tx {
864                 res.push(explicit_tx.clone());
865         }
866
867         assert_eq!(res.len(), 1);
868
869         if has_htlc_tx != HTLCType::NONE {
870                 node_txn.retain(|tx| {
871                         if tx.input.len() == 1 && tx.input[0].previous_output.txid == res[0].txid() {
872                                 check_spends!(tx, res[0].clone());
873                                 if has_htlc_tx == HTLCType::TIMEOUT {
874                                         assert!(tx.lock_time != 0);
875                                 } else {
876                                         assert!(tx.lock_time == 0);
877                                 }
878                                 res.push(tx.clone());
879                                 false
880                         } else { true }
881                 });
882                 assert!(res.len() == 2 || res.len() == 3);
883                 if res.len() == 3 {
884                         assert_eq!(res[1], res[2]);
885                 }
886         }
887
888         assert!(node_txn.is_empty());
889         res
890 }
891
892 /// Tests that the given node has broadcast a claim transaction against the provided revoked
893 /// HTLC transaction.
894 pub fn test_revoked_htlc_claim_txn_broadcast(node: &Node, revoked_tx: Transaction) {
895         let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
896         assert_eq!(node_txn.len(), 1);
897         node_txn.retain(|tx| {
898                 if tx.input.len() == 1 && tx.input[0].previous_output.txid == revoked_tx.txid() {
899                         check_spends!(tx, revoked_tx.clone());
900                         false
901                 } else { true }
902         });
903         assert!(node_txn.is_empty());
904 }
905
906 pub fn check_preimage_claim(node: &Node, prev_txn: &Vec<Transaction>) -> Vec<Transaction> {
907         let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
908
909         assert!(node_txn.len() >= 1);
910         assert_eq!(node_txn[0].input.len(), 1);
911         let mut found_prev = false;
912
913         for tx in prev_txn {
914                 if node_txn[0].input[0].previous_output.txid == tx.txid() {
915                         check_spends!(node_txn[0], tx.clone());
916                         assert!(node_txn[0].input[0].witness[2].len() > 106); // must spend an htlc output
917                         assert_eq!(tx.input.len(), 1); // must spend a commitment tx
918
919                         found_prev = true;
920                         break;
921                 }
922         }
923         assert!(found_prev);
924
925         let mut res = Vec::new();
926         mem::swap(&mut *node_txn, &mut res);
927         res
928 }
929
930 pub fn get_announce_close_broadcast_events(nodes: &Vec<Node>, a: usize, b: usize) {
931         let events_1 = nodes[a].node.get_and_clear_pending_msg_events();
932         assert_eq!(events_1.len(), 1);
933         let as_update = match events_1[0] {
934                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
935                         msg.clone()
936                 },
937                 _ => panic!("Unexpected event"),
938         };
939
940         let events_2 = nodes[b].node.get_and_clear_pending_msg_events();
941         assert_eq!(events_2.len(), 1);
942         let bs_update = match events_2[0] {
943                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
944                         msg.clone()
945                 },
946                 _ => panic!("Unexpected event"),
947         };
948
949         for node in nodes {
950                 node.router.handle_channel_update(&as_update).unwrap();
951                 node.router.handle_channel_update(&bs_update).unwrap();
952         }
953 }
954
955 macro_rules! get_channel_value_stat {
956         ($node: expr, $channel_id: expr) => {{
957                 let chan_lock = $node.node.channel_state.lock().unwrap();
958                 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
959                 chan.get_value_stat()
960         }}
961 }
962
963 macro_rules! get_chan_reestablish_msgs {
964         ($src_node: expr, $dst_node: expr) => {
965                 {
966                         let mut res = Vec::with_capacity(1);
967                         for msg in $src_node.node.get_and_clear_pending_msg_events() {
968                                 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
969                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
970                                         res.push(msg.clone());
971                                 } else {
972                                         panic!("Unexpected event")
973                                 }
974                         }
975                         res
976                 }
977         }
978 }
979
980 macro_rules! handle_chan_reestablish_msgs {
981         ($src_node: expr, $dst_node: expr) => {
982                 {
983                         let msg_events = $src_node.node.get_and_clear_pending_msg_events();
984                         let mut idx = 0;
985                         let funding_locked = if let Some(&MessageSendEvent::SendFundingLocked { ref node_id, ref msg }) = msg_events.get(0) {
986                                 idx += 1;
987                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
988                                 Some(msg.clone())
989                         } else {
990                                 None
991                         };
992
993                         let mut revoke_and_ack = None;
994                         let mut commitment_update = None;
995                         let order = if let Some(ev) = msg_events.get(idx) {
996                                 idx += 1;
997                                 match ev {
998                                         &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
999                                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
1000                                                 revoke_and_ack = Some(msg.clone());
1001                                                 RAACommitmentOrder::RevokeAndACKFirst
1002                                         },
1003                                         &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
1004                                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
1005                                                 commitment_update = Some(updates.clone());
1006                                                 RAACommitmentOrder::CommitmentFirst
1007                                         },
1008                                         _ => panic!("Unexpected event"),
1009                                 }
1010                         } else {
1011                                 RAACommitmentOrder::CommitmentFirst
1012                         };
1013
1014                         if let Some(ev) = msg_events.get(idx) {
1015                                 match ev {
1016                                         &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
1017                                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
1018                                                 assert!(revoke_and_ack.is_none());
1019                                                 revoke_and_ack = Some(msg.clone());
1020                                         },
1021                                         &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
1022                                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
1023                                                 assert!(commitment_update.is_none());
1024                                                 commitment_update = Some(updates.clone());
1025                                         },
1026                                         _ => panic!("Unexpected event"),
1027                                 }
1028                         }
1029
1030                         (funding_locked, revoke_and_ack, commitment_update, order)
1031                 }
1032         }
1033 }
1034
1035 /// pending_htlc_adds includes both the holding cell and in-flight update_add_htlcs, whereas
1036 /// for claims/fails they are separated out.
1037 pub fn reconnect_nodes(node_a: &Node, node_b: &Node, 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)) {
1038         node_a.node.peer_connected(&node_b.node.get_our_node_id());
1039         let reestablish_1 = get_chan_reestablish_msgs!(node_a, node_b);
1040         node_b.node.peer_connected(&node_a.node.get_our_node_id());
1041         let reestablish_2 = get_chan_reestablish_msgs!(node_b, node_a);
1042
1043         if send_funding_locked.0 {
1044                 // If a expects a funding_locked, it better not think it has received a revoke_and_ack
1045                 // from b
1046                 for reestablish in reestablish_1.iter() {
1047                         assert_eq!(reestablish.next_remote_commitment_number, 0);
1048                 }
1049         }
1050         if send_funding_locked.1 {
1051                 // If b expects a funding_locked, it better not think it has received a revoke_and_ack
1052                 // from a
1053                 for reestablish in reestablish_2.iter() {
1054                         assert_eq!(reestablish.next_remote_commitment_number, 0);
1055                 }
1056         }
1057         if send_funding_locked.0 || send_funding_locked.1 {
1058                 // If we expect any funding_locked's, both sides better have set
1059                 // next_local_commitment_number to 1
1060                 for reestablish in reestablish_1.iter() {
1061                         assert_eq!(reestablish.next_local_commitment_number, 1);
1062                 }
1063                 for reestablish in reestablish_2.iter() {
1064                         assert_eq!(reestablish.next_local_commitment_number, 1);
1065                 }
1066         }
1067
1068         let mut resp_1 = Vec::new();
1069         for msg in reestablish_1 {
1070                 node_b.node.handle_channel_reestablish(&node_a.node.get_our_node_id(), &msg).unwrap();
1071                 resp_1.push(handle_chan_reestablish_msgs!(node_b, node_a));
1072         }
1073         if pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
1074                 check_added_monitors!(node_b, 1);
1075         } else {
1076                 check_added_monitors!(node_b, 0);
1077         }
1078
1079         let mut resp_2 = Vec::new();
1080         for msg in reestablish_2 {
1081                 node_a.node.handle_channel_reestablish(&node_b.node.get_our_node_id(), &msg).unwrap();
1082                 resp_2.push(handle_chan_reestablish_msgs!(node_a, node_b));
1083         }
1084         if pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
1085                 check_added_monitors!(node_a, 1);
1086         } else {
1087                 check_added_monitors!(node_a, 0);
1088         }
1089
1090         // We don't yet support both needing updates, as that would require a different commitment dance:
1091         assert!((pending_htlc_adds.0 == 0 && pending_htlc_claims.0 == 0 && pending_cell_htlc_claims.0 == 0 && pending_cell_htlc_fails.0 == 0) ||
1092                         (pending_htlc_adds.1 == 0 && pending_htlc_claims.1 == 0 && pending_cell_htlc_claims.1 == 0 && pending_cell_htlc_fails.1 == 0));
1093
1094         for chan_msgs in resp_1.drain(..) {
1095                 if send_funding_locked.0 {
1096                         node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
1097                         let announcement_event = node_a.node.get_and_clear_pending_msg_events();
1098                         if !announcement_event.is_empty() {
1099                                 assert_eq!(announcement_event.len(), 1);
1100                                 if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
1101                                         //TODO: Test announcement_sigs re-sending
1102                                 } else { panic!("Unexpected event!"); }
1103                         }
1104                 } else {
1105                         assert!(chan_msgs.0.is_none());
1106                 }
1107                 if pending_raa.0 {
1108                         assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
1109                         node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
1110                         assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
1111                         check_added_monitors!(node_a, 1);
1112                 } else {
1113                         assert!(chan_msgs.1.is_none());
1114                 }
1115                 if pending_htlc_adds.0 != 0 || pending_htlc_claims.0 != 0 || pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
1116                         let commitment_update = chan_msgs.2.unwrap();
1117                         if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
1118                                 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.0 as usize);
1119                         } else {
1120                                 assert!(commitment_update.update_add_htlcs.is_empty());
1121                         }
1122                         assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
1123                         assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
1124                         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
1125                         for update_add in commitment_update.update_add_htlcs {
1126                                 node_a.node.handle_update_add_htlc(&node_b.node.get_our_node_id(), &update_add).unwrap();
1127                         }
1128                         for update_fulfill in commitment_update.update_fulfill_htlcs {
1129                                 node_a.node.handle_update_fulfill_htlc(&node_b.node.get_our_node_id(), &update_fulfill).unwrap();
1130                         }
1131                         for update_fail in commitment_update.update_fail_htlcs {
1132                                 node_a.node.handle_update_fail_htlc(&node_b.node.get_our_node_id(), &update_fail).unwrap();
1133                         }
1134
1135                         if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
1136                                 commitment_signed_dance!(node_a, node_b, commitment_update.commitment_signed, false);
1137                         } else {
1138                                 node_a.node.handle_commitment_signed(&node_b.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
1139                                 check_added_monitors!(node_a, 1);
1140                                 let as_revoke_and_ack = get_event_msg!(node_a, MessageSendEvent::SendRevokeAndACK, node_b.node.get_our_node_id());
1141                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
1142                                 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
1143                                 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
1144                                 check_added_monitors!(node_b, 1);
1145                         }
1146                 } else {
1147                         assert!(chan_msgs.2.is_none());
1148                 }
1149         }
1150
1151         for chan_msgs in resp_2.drain(..) {
1152                 if send_funding_locked.1 {
1153                         node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
1154                         let announcement_event = node_b.node.get_and_clear_pending_msg_events();
1155                         if !announcement_event.is_empty() {
1156                                 assert_eq!(announcement_event.len(), 1);
1157                                 if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
1158                                         //TODO: Test announcement_sigs re-sending
1159                                 } else { panic!("Unexpected event!"); }
1160                         }
1161                 } else {
1162                         assert!(chan_msgs.0.is_none());
1163                 }
1164                 if pending_raa.1 {
1165                         assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
1166                         node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
1167                         assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
1168                         check_added_monitors!(node_b, 1);
1169                 } else {
1170                         assert!(chan_msgs.1.is_none());
1171                 }
1172                 if pending_htlc_adds.1 != 0 || pending_htlc_claims.1 != 0 || pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
1173                         let commitment_update = chan_msgs.2.unwrap();
1174                         if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
1175                                 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.1 as usize);
1176                         }
1177                         assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
1178                         assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
1179                         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
1180                         for update_add in commitment_update.update_add_htlcs {
1181                                 node_b.node.handle_update_add_htlc(&node_a.node.get_our_node_id(), &update_add).unwrap();
1182                         }
1183                         for update_fulfill in commitment_update.update_fulfill_htlcs {
1184                                 node_b.node.handle_update_fulfill_htlc(&node_a.node.get_our_node_id(), &update_fulfill).unwrap();
1185                         }
1186                         for update_fail in commitment_update.update_fail_htlcs {
1187                                 node_b.node.handle_update_fail_htlc(&node_a.node.get_our_node_id(), &update_fail).unwrap();
1188                         }
1189
1190                         if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
1191                                 commitment_signed_dance!(node_b, node_a, commitment_update.commitment_signed, false);
1192                         } else {
1193                                 node_b.node.handle_commitment_signed(&node_a.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
1194                                 check_added_monitors!(node_b, 1);
1195                                 let bs_revoke_and_ack = get_event_msg!(node_b, MessageSendEvent::SendRevokeAndACK, node_a.node.get_our_node_id());
1196                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
1197                                 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
1198                                 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
1199                                 check_added_monitors!(node_a, 1);
1200                         }
1201                 } else {
1202                         assert!(chan_msgs.2.is_none());
1203                 }
1204         }
1205 }