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