Clarify policy applied in send htlc error msgs
[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 pub fn send_along_route_with_hash(origin_node: &Node, route: Route, expected_route: &[&Node], recv_value: u64, our_payment_hash: PaymentHash) {
546         let mut payment_event = {
547                 origin_node.node.send_payment(route, our_payment_hash).unwrap();
548                 check_added_monitors!(origin_node, 1);
549
550                 let mut events = origin_node.node.get_and_clear_pending_msg_events();
551                 assert_eq!(events.len(), 1);
552                 SendEvent::from_event(events.remove(0))
553         };
554         let mut prev_node = origin_node;
555
556         for (idx, &node) in expected_route.iter().enumerate() {
557                 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
558
559                 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
560                 check_added_monitors!(node, 0);
561                 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
562
563                 expect_pending_htlcs_forwardable!(node);
564
565                 if idx == expected_route.len() - 1 {
566                         let events_2 = node.node.get_and_clear_pending_events();
567                         assert_eq!(events_2.len(), 1);
568                         match events_2[0] {
569                                 Event::PaymentReceived { ref payment_hash, amt } => {
570                                         assert_eq!(our_payment_hash, *payment_hash);
571                                         assert_eq!(amt, recv_value);
572                                 },
573                                 _ => panic!("Unexpected event"),
574                         }
575                 } else {
576                         let mut events_2 = node.node.get_and_clear_pending_msg_events();
577                         assert_eq!(events_2.len(), 1);
578                         check_added_monitors!(node, 1);
579                         payment_event = SendEvent::from_event(events_2.remove(0));
580                         assert_eq!(payment_event.msgs.len(), 1);
581                 }
582
583                 prev_node = node;
584         }
585 }
586
587 pub fn send_along_route(origin_node: &Node, route: Route, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
588         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(origin_node);
589         send_along_route_with_hash(origin_node, route, expected_route, recv_value, our_payment_hash);
590         (our_payment_preimage, our_payment_hash)
591 }
592
593 pub fn claim_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_preimage: PaymentPreimage) {
594         assert!(expected_route.last().unwrap().node.claim_funds(our_payment_preimage));
595         check_added_monitors!(expected_route.last().unwrap(), 1);
596
597         let mut next_msgs: Option<(msgs::UpdateFulfillHTLC, msgs::CommitmentSigned)> = None;
598         let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
599         macro_rules! get_next_msgs {
600                 ($node: expr) => {
601                         {
602                                 let events = $node.node.get_and_clear_pending_msg_events();
603                                 assert_eq!(events.len(), 1);
604                                 match events[0] {
605                                         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 } } => {
606                                                 assert!(update_add_htlcs.is_empty());
607                                                 assert_eq!(update_fulfill_htlcs.len(), 1);
608                                                 assert!(update_fail_htlcs.is_empty());
609                                                 assert!(update_fail_malformed_htlcs.is_empty());
610                                                 assert!(update_fee.is_none());
611                                                 expected_next_node = node_id.clone();
612                                                 Some((update_fulfill_htlcs[0].clone(), commitment_signed.clone()))
613                                         },
614                                         _ => panic!("Unexpected event"),
615                                 }
616                         }
617                 }
618         }
619
620         macro_rules! last_update_fulfill_dance {
621                 ($node: expr, $prev_node: expr) => {
622                         {
623                                 $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
624                                 check_added_monitors!($node, 0);
625                                 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
626                                 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
627                         }
628                 }
629         }
630         macro_rules! mid_update_fulfill_dance {
631                 ($node: expr, $prev_node: expr, $new_msgs: expr) => {
632                         {
633                                 $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
634                                 check_added_monitors!($node, 1);
635                                 let new_next_msgs = if $new_msgs {
636                                         get_next_msgs!($node)
637                                 } else {
638                                         assert!($node.node.get_and_clear_pending_msg_events().is_empty());
639                                         None
640                                 };
641                                 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
642                                 next_msgs = new_next_msgs;
643                         }
644                 }
645         }
646
647         let mut prev_node = expected_route.last().unwrap();
648         for (idx, node) in expected_route.iter().rev().enumerate() {
649                 assert_eq!(expected_next_node, node.node.get_our_node_id());
650                 let update_next_msgs = !skip_last || idx != expected_route.len() - 1;
651                 if next_msgs.is_some() {
652                         mid_update_fulfill_dance!(node, prev_node, update_next_msgs);
653                 } else if update_next_msgs {
654                         next_msgs = get_next_msgs!(node);
655                 } else {
656                         assert!(node.node.get_and_clear_pending_msg_events().is_empty());
657                 }
658                 if !skip_last && idx == expected_route.len() - 1 {
659                         assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
660                 }
661
662                 prev_node = node;
663         }
664
665         if !skip_last {
666                 last_update_fulfill_dance!(origin_node, expected_route.first().unwrap());
667                 let events = origin_node.node.get_and_clear_pending_events();
668                 assert_eq!(events.len(), 1);
669                 match events[0] {
670                         Event::PaymentSent { payment_preimage } => {
671                                 assert_eq!(payment_preimage, our_payment_preimage);
672                         },
673                         _ => panic!("Unexpected event"),
674                 }
675         }
676 }
677
678 pub fn claim_payment(origin_node: &Node, expected_route: &[&Node], our_payment_preimage: PaymentPreimage) {
679         claim_payment_along_route(origin_node, expected_route, false, our_payment_preimage);
680 }
681
682 pub const TEST_FINAL_CLTV: u32 = 32;
683
684 pub fn route_payment(origin_node: &Node, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
685         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();
686         assert_eq!(route.hops.len(), expected_route.len());
687         for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
688                 assert_eq!(hop.pubkey, node.node.get_our_node_id());
689         }
690
691         send_along_route(origin_node, route, expected_route, recv_value)
692 }
693
694 pub fn route_over_limit(origin_node: &Node, expected_route: &[&Node], recv_value: u64) {
695         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();
696         assert_eq!(route.hops.len(), expected_route.len());
697         for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
698                 assert_eq!(hop.pubkey, node.node.get_our_node_id());
699         }
700
701         let (_, our_payment_hash) = get_payment_preimage_hash!(origin_node);
702
703         let err = origin_node.node.send_payment(route, our_payment_hash).err().unwrap();
704         match err {
705                 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over the max HTLC value in flight our peer will accept"),
706                 _ => panic!("Unknown error variants"),
707         };
708 }
709
710 pub fn send_payment(origin: &Node, expected_route: &[&Node], recv_value: u64) {
711         let our_payment_preimage = route_payment(&origin, expected_route, recv_value).0;
712         claim_payment(&origin, expected_route, our_payment_preimage);
713 }
714
715 pub fn fail_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_hash: PaymentHash) {
716         assert!(expected_route.last().unwrap().node.fail_htlc_backwards(&our_payment_hash));
717         expect_pending_htlcs_forwardable!(expected_route.last().unwrap());
718         check_added_monitors!(expected_route.last().unwrap(), 1);
719
720         let mut next_msgs: Option<(msgs::UpdateFailHTLC, msgs::CommitmentSigned)> = None;
721         macro_rules! update_fail_dance {
722                 ($node: expr, $prev_node: expr, $last_node: expr) => {
723                         {
724                                 $node.node.handle_update_fail_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
725                                 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, !$last_node);
726                                 if skip_last && $last_node {
727                                         expect_pending_htlcs_forwardable!($node);
728                                 }
729                         }
730                 }
731         }
732
733         let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
734         let mut prev_node = expected_route.last().unwrap();
735         for (idx, node) in expected_route.iter().rev().enumerate() {
736                 assert_eq!(expected_next_node, node.node.get_our_node_id());
737                 if next_msgs.is_some() {
738                         // We may be the "last node" for the purpose of the commitment dance if we're
739                         // skipping the last node (implying it is disconnected) and we're the
740                         // second-to-last node!
741                         update_fail_dance!(node, prev_node, skip_last && idx == expected_route.len() - 1);
742                 }
743
744                 let events = node.node.get_and_clear_pending_msg_events();
745                 if !skip_last || idx != expected_route.len() - 1 {
746                         assert_eq!(events.len(), 1);
747                         match events[0] {
748                                 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 } } => {
749                                         assert!(update_add_htlcs.is_empty());
750                                         assert!(update_fulfill_htlcs.is_empty());
751                                         assert_eq!(update_fail_htlcs.len(), 1);
752                                         assert!(update_fail_malformed_htlcs.is_empty());
753                                         assert!(update_fee.is_none());
754                                         expected_next_node = node_id.clone();
755                                         next_msgs = Some((update_fail_htlcs[0].clone(), commitment_signed.clone()));
756                                 },
757                                 _ => panic!("Unexpected event"),
758                         }
759                 } else {
760                         assert!(events.is_empty());
761                 }
762                 if !skip_last && idx == expected_route.len() - 1 {
763                         assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
764                 }
765
766                 prev_node = node;
767         }
768
769         if !skip_last {
770                 update_fail_dance!(origin_node, expected_route.first().unwrap(), true);
771
772                 let events = origin_node.node.get_and_clear_pending_events();
773                 assert_eq!(events.len(), 1);
774                 match events[0] {
775                         Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
776                                 assert_eq!(payment_hash, our_payment_hash);
777                                 assert!(rejected_by_dest);
778                         },
779                         _ => panic!("Unexpected event"),
780                 }
781         }
782 }
783
784 pub fn fail_payment(origin_node: &Node, expected_route: &[&Node], our_payment_hash: PaymentHash) {
785         fail_payment_along_route(origin_node, expected_route, false, our_payment_hash);
786 }
787
788 pub fn create_network(node_count: usize) -> Vec<Node> {
789         let mut nodes = Vec::new();
790         let mut rng = thread_rng();
791         let secp_ctx = Secp256k1::new();
792
793         let chan_count = Rc::new(RefCell::new(0));
794         let payment_count = Rc::new(RefCell::new(0));
795
796         for i in 0..node_count {
797                 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::with_id(format!("node {}", i)));
798                 let feeest = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 });
799                 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
800                 let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())});
801                 let mut seed = [0; 32];
802                 rng.fill_bytes(&mut seed);
803                 let keys_manager = Arc::new(test_utils::TestKeysInterface::new(&seed, Network::Testnet, Arc::clone(&logger)));
804                 let chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(chain_monitor.clone(), tx_broadcaster.clone(), logger.clone()));
805                 let mut config = UserConfig::new();
806                 config.channel_options.announced_channel = true;
807                 config.channel_limits.force_announced_channel_preference = false;
808                 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();
809                 let router = Router::new(PublicKey::from_secret_key(&secp_ctx, &keys_manager.get_node_secret()), chain_monitor.clone(), Arc::clone(&logger));
810                 nodes.push(Node { chain_monitor, tx_broadcaster, chan_monitor, node, router, keys_manager, node_seed: seed,
811                         network_payment_count: payment_count.clone(),
812                         network_chan_count: chan_count.clone(),
813                 });
814         }
815
816         nodes
817 }
818
819 #[derive(PartialEq)]
820 pub enum HTLCType { NONE, TIMEOUT, SUCCESS }
821 /// Tests that the given node has broadcast transactions for the given Channel
822 ///
823 /// First checks that the latest local commitment tx has been broadcast, unless an explicit
824 /// commitment_tx is provided, which may be used to test that a remote commitment tx was
825 /// broadcast and the revoked outputs were claimed.
826 ///
827 /// Next tests that there is (or is not) a transaction that spends the commitment transaction
828 /// that appears to be the type of HTLC transaction specified in has_htlc_tx.
829 ///
830 /// All broadcast transactions must be accounted for in one of the above three types of we'll
831 /// also fail.
832 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> {
833         let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
834         assert!(node_txn.len() >= if commitment_tx.is_some() { 0 } else { 1 } + if has_htlc_tx == HTLCType::NONE { 0 } else { 1 });
835
836         let mut res = Vec::with_capacity(2);
837         node_txn.retain(|tx| {
838                 if tx.input.len() == 1 && tx.input[0].previous_output.txid == chan.3.txid() {
839                         check_spends!(tx, chan.3.clone());
840                         if commitment_tx.is_none() {
841                                 res.push(tx.clone());
842                         }
843                         false
844                 } else { true }
845         });
846         if let Some(explicit_tx) = commitment_tx {
847                 res.push(explicit_tx.clone());
848         }
849
850         assert_eq!(res.len(), 1);
851
852         if has_htlc_tx != HTLCType::NONE {
853                 node_txn.retain(|tx| {
854                         if tx.input.len() == 1 && tx.input[0].previous_output.txid == res[0].txid() {
855                                 check_spends!(tx, res[0].clone());
856                                 if has_htlc_tx == HTLCType::TIMEOUT {
857                                         assert!(tx.lock_time != 0);
858                                 } else {
859                                         assert!(tx.lock_time == 0);
860                                 }
861                                 res.push(tx.clone());
862                                 false
863                         } else { true }
864                 });
865                 assert!(res.len() == 2 || res.len() == 3);
866                 if res.len() == 3 {
867                         assert_eq!(res[1], res[2]);
868                 }
869         }
870
871         assert!(node_txn.is_empty());
872         res
873 }
874
875 /// Tests that the given node has broadcast a claim transaction against the provided revoked
876 /// HTLC transaction.
877 pub fn test_revoked_htlc_claim_txn_broadcast(node: &Node, revoked_tx: Transaction) {
878         let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
879         assert_eq!(node_txn.len(), 1);
880         node_txn.retain(|tx| {
881                 if tx.input.len() == 1 && tx.input[0].previous_output.txid == revoked_tx.txid() {
882                         check_spends!(tx, revoked_tx.clone());
883                         false
884                 } else { true }
885         });
886         assert!(node_txn.is_empty());
887 }
888
889 pub fn check_preimage_claim(node: &Node, prev_txn: &Vec<Transaction>) -> Vec<Transaction> {
890         let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
891
892         assert!(node_txn.len() >= 1);
893         assert_eq!(node_txn[0].input.len(), 1);
894         let mut found_prev = false;
895
896         for tx in prev_txn {
897                 if node_txn[0].input[0].previous_output.txid == tx.txid() {
898                         check_spends!(node_txn[0], tx.clone());
899                         assert!(node_txn[0].input[0].witness[2].len() > 106); // must spend an htlc output
900                         assert_eq!(tx.input.len(), 1); // must spend a commitment tx
901
902                         found_prev = true;
903                         break;
904                 }
905         }
906         assert!(found_prev);
907
908         let mut res = Vec::new();
909         mem::swap(&mut *node_txn, &mut res);
910         res
911 }
912
913 pub fn get_announce_close_broadcast_events(nodes: &Vec<Node>, a: usize, b: usize) {
914         let events_1 = nodes[a].node.get_and_clear_pending_msg_events();
915         assert_eq!(events_1.len(), 1);
916         let as_update = match events_1[0] {
917                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
918                         msg.clone()
919                 },
920                 _ => panic!("Unexpected event"),
921         };
922
923         let events_2 = nodes[b].node.get_and_clear_pending_msg_events();
924         assert_eq!(events_2.len(), 1);
925         let bs_update = match events_2[0] {
926                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
927                         msg.clone()
928                 },
929                 _ => panic!("Unexpected event"),
930         };
931
932         for node in nodes {
933                 node.router.handle_channel_update(&as_update).unwrap();
934                 node.router.handle_channel_update(&bs_update).unwrap();
935         }
936 }
937
938 macro_rules! expect_payment_received {
939         ($node: expr, $expected_payment_hash: expr, $expected_recv_value: expr) => {
940                 let events = $node.node.get_and_clear_pending_events();
941                 assert_eq!(events.len(), 1);
942                 match events[0] {
943                         Event::PaymentReceived { ref payment_hash, amt } => {
944                                 assert_eq!($expected_payment_hash, *payment_hash);
945                                 assert_eq!($expected_recv_value, amt);
946                         },
947                         _ => panic!("Unexpected event"),
948                 }
949         }
950 }
951
952 macro_rules! get_channel_value_stat {
953         ($node: expr, $channel_id: expr) => {{
954                 let chan_lock = $node.node.channel_state.lock().unwrap();
955                 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
956                 chan.get_value_stat()
957         }}
958 }
959
960 macro_rules! get_chan_reestablish_msgs {
961         ($src_node: expr, $dst_node: expr) => {
962                 {
963                         let mut res = Vec::with_capacity(1);
964                         for msg in $src_node.node.get_and_clear_pending_msg_events() {
965                                 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
966                                         assert_eq!(*node_id, $dst_node.node.get_our_node_id());
967                                         res.push(msg.clone());
968                                 } else {
969                                         panic!("Unexpected event")
970                                 }
971                         }
972                         res
973                 }
974         }
975 }
976
977 macro_rules! handle_chan_reestablish_msgs {
978         ($src_node: expr, $dst_node: expr) => {
979                 {
980                         let msg_events = $src_node.node.get_and_clear_pending_msg_events();
981                         let mut idx = 0;
982                         let funding_locked = if let Some(&MessageSendEvent::SendFundingLocked { ref node_id, ref msg }) = msg_events.get(0) {
983                                 idx += 1;
984                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
985                                 Some(msg.clone())
986                         } else {
987                                 None
988                         };
989
990                         let mut revoke_and_ack = None;
991                         let mut commitment_update = None;
992                         let order = if let Some(ev) = msg_events.get(idx) {
993                                 idx += 1;
994                                 match ev {
995                                         &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
996                                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
997                                                 revoke_and_ack = Some(msg.clone());
998                                                 RAACommitmentOrder::RevokeAndACKFirst
999                                         },
1000                                         &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
1001                                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
1002                                                 commitment_update = Some(updates.clone());
1003                                                 RAACommitmentOrder::CommitmentFirst
1004                                         },
1005                                         _ => panic!("Unexpected event"),
1006                                 }
1007                         } else {
1008                                 RAACommitmentOrder::CommitmentFirst
1009                         };
1010
1011                         if let Some(ev) = msg_events.get(idx) {
1012                                 match ev {
1013                                         &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
1014                                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
1015                                                 assert!(revoke_and_ack.is_none());
1016                                                 revoke_and_ack = Some(msg.clone());
1017                                         },
1018                                         &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
1019                                                 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
1020                                                 assert!(commitment_update.is_none());
1021                                                 commitment_update = Some(updates.clone());
1022                                         },
1023                                         _ => panic!("Unexpected event"),
1024                                 }
1025                         }
1026
1027                         (funding_locked, revoke_and_ack, commitment_update, order)
1028                 }
1029         }
1030 }
1031
1032 /// pending_htlc_adds includes both the holding cell and in-flight update_add_htlcs, whereas
1033 /// for claims/fails they are separated out.
1034 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)) {
1035         node_a.node.peer_connected(&node_b.node.get_our_node_id());
1036         let reestablish_1 = get_chan_reestablish_msgs!(node_a, node_b);
1037         node_b.node.peer_connected(&node_a.node.get_our_node_id());
1038         let reestablish_2 = get_chan_reestablish_msgs!(node_b, node_a);
1039
1040         if send_funding_locked.0 {
1041                 // If a expects a funding_locked, it better not think it has received a revoke_and_ack
1042                 // from b
1043                 for reestablish in reestablish_1.iter() {
1044                         assert_eq!(reestablish.next_remote_commitment_number, 0);
1045                 }
1046         }
1047         if send_funding_locked.1 {
1048                 // If b expects a funding_locked, it better not think it has received a revoke_and_ack
1049                 // from a
1050                 for reestablish in reestablish_2.iter() {
1051                         assert_eq!(reestablish.next_remote_commitment_number, 0);
1052                 }
1053         }
1054         if send_funding_locked.0 || send_funding_locked.1 {
1055                 // If we expect any funding_locked's, both sides better have set
1056                 // next_local_commitment_number to 1
1057                 for reestablish in reestablish_1.iter() {
1058                         assert_eq!(reestablish.next_local_commitment_number, 1);
1059                 }
1060                 for reestablish in reestablish_2.iter() {
1061                         assert_eq!(reestablish.next_local_commitment_number, 1);
1062                 }
1063         }
1064
1065         let mut resp_1 = Vec::new();
1066         for msg in reestablish_1 {
1067                 node_b.node.handle_channel_reestablish(&node_a.node.get_our_node_id(), &msg).unwrap();
1068                 resp_1.push(handle_chan_reestablish_msgs!(node_b, node_a));
1069         }
1070         if pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
1071                 check_added_monitors!(node_b, 1);
1072         } else {
1073                 check_added_monitors!(node_b, 0);
1074         }
1075
1076         let mut resp_2 = Vec::new();
1077         for msg in reestablish_2 {
1078                 node_a.node.handle_channel_reestablish(&node_b.node.get_our_node_id(), &msg).unwrap();
1079                 resp_2.push(handle_chan_reestablish_msgs!(node_a, node_b));
1080         }
1081         if pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
1082                 check_added_monitors!(node_a, 1);
1083         } else {
1084                 check_added_monitors!(node_a, 0);
1085         }
1086
1087         // We don't yet support both needing updates, as that would require a different commitment dance:
1088         assert!((pending_htlc_adds.0 == 0 && pending_htlc_claims.0 == 0 && pending_cell_htlc_claims.0 == 0 && pending_cell_htlc_fails.0 == 0) ||
1089                         (pending_htlc_adds.1 == 0 && pending_htlc_claims.1 == 0 && pending_cell_htlc_claims.1 == 0 && pending_cell_htlc_fails.1 == 0));
1090
1091         for chan_msgs in resp_1.drain(..) {
1092                 if send_funding_locked.0 {
1093                         node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
1094                         let announcement_event = node_a.node.get_and_clear_pending_msg_events();
1095                         if !announcement_event.is_empty() {
1096                                 assert_eq!(announcement_event.len(), 1);
1097                                 if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
1098                                         //TODO: Test announcement_sigs re-sending
1099                                 } else { panic!("Unexpected event!"); }
1100                         }
1101                 } else {
1102                         assert!(chan_msgs.0.is_none());
1103                 }
1104                 if pending_raa.0 {
1105                         assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
1106                         node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
1107                         assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
1108                         check_added_monitors!(node_a, 1);
1109                 } else {
1110                         assert!(chan_msgs.1.is_none());
1111                 }
1112                 if pending_htlc_adds.0 != 0 || pending_htlc_claims.0 != 0 || pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
1113                         let commitment_update = chan_msgs.2.unwrap();
1114                         if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
1115                                 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.0 as usize);
1116                         } else {
1117                                 assert!(commitment_update.update_add_htlcs.is_empty());
1118                         }
1119                         assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
1120                         assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
1121                         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
1122                         for update_add in commitment_update.update_add_htlcs {
1123                                 node_a.node.handle_update_add_htlc(&node_b.node.get_our_node_id(), &update_add).unwrap();
1124                         }
1125                         for update_fulfill in commitment_update.update_fulfill_htlcs {
1126                                 node_a.node.handle_update_fulfill_htlc(&node_b.node.get_our_node_id(), &update_fulfill).unwrap();
1127                         }
1128                         for update_fail in commitment_update.update_fail_htlcs {
1129                                 node_a.node.handle_update_fail_htlc(&node_b.node.get_our_node_id(), &update_fail).unwrap();
1130                         }
1131
1132                         if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
1133                                 commitment_signed_dance!(node_a, node_b, commitment_update.commitment_signed, false);
1134                         } else {
1135                                 node_a.node.handle_commitment_signed(&node_b.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
1136                                 check_added_monitors!(node_a, 1);
1137                                 let as_revoke_and_ack = get_event_msg!(node_a, MessageSendEvent::SendRevokeAndACK, node_b.node.get_our_node_id());
1138                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
1139                                 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
1140                                 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
1141                                 check_added_monitors!(node_b, 1);
1142                         }
1143                 } else {
1144                         assert!(chan_msgs.2.is_none());
1145                 }
1146         }
1147
1148         for chan_msgs in resp_2.drain(..) {
1149                 if send_funding_locked.1 {
1150                         node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
1151                         let announcement_event = node_b.node.get_and_clear_pending_msg_events();
1152                         if !announcement_event.is_empty() {
1153                                 assert_eq!(announcement_event.len(), 1);
1154                                 if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
1155                                         //TODO: Test announcement_sigs re-sending
1156                                 } else { panic!("Unexpected event!"); }
1157                         }
1158                 } else {
1159                         assert!(chan_msgs.0.is_none());
1160                 }
1161                 if pending_raa.1 {
1162                         assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
1163                         node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
1164                         assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
1165                         check_added_monitors!(node_b, 1);
1166                 } else {
1167                         assert!(chan_msgs.1.is_none());
1168                 }
1169                 if pending_htlc_adds.1 != 0 || pending_htlc_claims.1 != 0 || pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
1170                         let commitment_update = chan_msgs.2.unwrap();
1171                         if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
1172                                 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.1 as usize);
1173                         }
1174                         assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
1175                         assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
1176                         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
1177                         for update_add in commitment_update.update_add_htlcs {
1178                                 node_b.node.handle_update_add_htlc(&node_a.node.get_our_node_id(), &update_add).unwrap();
1179                         }
1180                         for update_fulfill in commitment_update.update_fulfill_htlcs {
1181                                 node_b.node.handle_update_fulfill_htlc(&node_a.node.get_our_node_id(), &update_fulfill).unwrap();
1182                         }
1183                         for update_fail in commitment_update.update_fail_htlcs {
1184                                 node_b.node.handle_update_fail_htlc(&node_a.node.get_our_node_id(), &update_fail).unwrap();
1185                         }
1186
1187                         if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
1188                                 commitment_signed_dance!(node_b, node_a, commitment_update.commitment_signed, false);
1189                         } else {
1190                                 node_b.node.handle_commitment_signed(&node_a.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
1191                                 check_added_monitors!(node_b, 1);
1192                                 let bs_revoke_and_ack = get_event_msg!(node_b, MessageSendEvent::SendRevokeAndACK, node_a.node.get_our_node_id());
1193                                 // No commitment_signed so get_event_msg's assert(len == 1) passes
1194                                 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
1195                                 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
1196                                 check_added_monitors!(node_a, 1);
1197                         }
1198                 } else {
1199                         assert!(chan_msgs.2.is_none());
1200                 }
1201         }
1202 }