1 //! A bunch of useful utilities for building networks of nodes and exchanging messages between
2 //! nodes for functional tests.
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};
10 use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler, LocalFeatures};
12 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
13 use util::errors::APIError;
14 use util::logger::Logger;
15 use util::config::UserConfig;
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;
22 use bitcoin_hashes::sha256::Hash as Sha256;
23 use bitcoin_hashes::sha256d::Hash as Sha256d;
24 use bitcoin_hashes::Hash;
26 use secp256k1::Secp256k1;
27 use secp256k1::key::PublicKey;
29 use rand::{thread_rng,Rng};
31 use std::cell::RefCell;
33 use std::sync::{Arc, Mutex};
36 pub const CHAN_CONFIRM_DEPTH: u32 = 100;
37 pub fn confirm_transaction(chain: &chaininterface::ChainWatchInterfaceUtil, tx: &Transaction, chan_id: u32) {
38 assert!(chain.does_match_tx(tx));
39 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
40 chain.block_connected_checked(&header, 1, &[tx; 1], &[chan_id; 1]);
41 for i in 2..CHAN_CONFIRM_DEPTH {
42 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
43 chain.block_connected_checked(&header, i, &[tx; 0], &[0; 0]);
47 pub fn connect_blocks(chain: &chaininterface::ChainWatchInterfaceUtil, depth: u32, height: u32, parent: bool, prev_blockhash: Sha256d) -> Sha256d {
48 let mut header = BlockHeader { version: 0x2000000, prev_blockhash: if parent { prev_blockhash } else { Default::default() }, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
49 chain.block_connected_checked(&header, height + 1, &Vec::new(), &Vec::new());
50 for i in 2..depth + 1 {
51 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
52 chain.block_connected_checked(&header, height + i, &Vec::new(), &Vec::new());
58 pub chain_monitor: Arc<chaininterface::ChainWatchInterfaceUtil>,
59 pub tx_broadcaster: Arc<test_utils::TestBroadcaster>,
60 pub chan_monitor: Arc<test_utils::TestChannelMonitor>,
61 pub keys_manager: Arc<test_utils::TestKeysInterface>,
62 pub node: Arc<ChannelManager>,
64 pub node_seed: [u8; 32],
65 pub network_payment_count: Rc<RefCell<u8>>,
66 pub network_chan_count: Rc<RefCell<u32>>,
70 if !::std::thread::panicking() {
71 // Check that we processed all pending events
72 assert!(self.node.get_and_clear_pending_msg_events().is_empty());
73 assert!(self.node.get_and_clear_pending_events().is_empty());
74 assert!(self.chan_monitor.added_monitors.lock().unwrap().is_empty());
79 pub fn create_chan_between_nodes(node_a: &Node, node_b: &Node, a_flags: LocalFeatures, b_flags: LocalFeatures) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
80 create_chan_between_nodes_with_value(node_a, node_b, 100000, 10001, a_flags, b_flags)
83 pub fn create_chan_between_nodes_with_value(node_a: &Node, node_b: &Node, channel_value: u64, push_msat: u64, a_flags: LocalFeatures, b_flags: LocalFeatures) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
84 let (funding_locked, channel_id, tx) = create_chan_between_nodes_with_value_a(node_a, node_b, channel_value, push_msat, a_flags, b_flags);
85 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(node_a, node_b, &funding_locked);
86 (announcement, as_update, bs_update, channel_id, tx)
89 macro_rules! get_revoke_commit_msgs {
90 ($node: expr, $node_id: expr) => {
92 let events = $node.node.get_and_clear_pending_msg_events();
93 assert_eq!(events.len(), 2);
95 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
96 assert_eq!(*node_id, $node_id);
99 _ => panic!("Unexpected event"),
101 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
102 assert_eq!(*node_id, $node_id);
103 assert!(updates.update_add_htlcs.is_empty());
104 assert!(updates.update_fulfill_htlcs.is_empty());
105 assert!(updates.update_fail_htlcs.is_empty());
106 assert!(updates.update_fail_malformed_htlcs.is_empty());
107 assert!(updates.update_fee.is_none());
108 updates.commitment_signed.clone()
110 _ => panic!("Unexpected event"),
116 macro_rules! get_event_msg {
117 ($node: expr, $event_type: path, $node_id: expr) => {
119 let events = $node.node.get_and_clear_pending_msg_events();
120 assert_eq!(events.len(), 1);
122 $event_type { ref node_id, ref msg } => {
123 assert_eq!(*node_id, $node_id);
126 _ => panic!("Unexpected event"),
132 macro_rules! get_htlc_update_msgs {
133 ($node: expr, $node_id: expr) => {
135 let events = $node.node.get_and_clear_pending_msg_events();
136 assert_eq!(events.len(), 1);
138 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
139 assert_eq!(*node_id, $node_id);
142 _ => panic!("Unexpected event"),
148 macro_rules! get_feerate {
149 ($node: expr, $channel_id: expr) => {
151 let chan_lock = $node.node.channel_state.lock().unwrap();
152 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
158 pub fn create_funding_transaction(node: &Node, expected_chan_value: u64, expected_user_chan_id: u64) -> ([u8; 32], Transaction, OutPoint) {
159 let chan_id = *node.network_chan_count.borrow();
161 let events = node.node.get_and_clear_pending_events();
162 assert_eq!(events.len(), 1);
164 Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
165 assert_eq!(*channel_value_satoshis, expected_chan_value);
166 assert_eq!(user_channel_id, expected_user_chan_id);
168 let tx = Transaction { version: chan_id as u32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
169 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
171 let funding_outpoint = OutPoint::new(tx.txid(), 0);
172 (*temporary_channel_id, tx, funding_outpoint)
174 _ => panic!("Unexpected event"),
178 pub fn create_chan_between_nodes_with_value_init(node_a: &Node, node_b: &Node, channel_value: u64, push_msat: u64, a_flags: LocalFeatures, b_flags: LocalFeatures) -> Transaction {
179 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42).unwrap();
180 node_b.node.handle_open_channel(&node_a.node.get_our_node_id(), a_flags, &get_event_msg!(node_a, MessageSendEvent::SendOpenChannel, node_b.node.get_our_node_id())).unwrap();
181 node_a.node.handle_accept_channel(&node_b.node.get_our_node_id(), b_flags, &get_event_msg!(node_b, MessageSendEvent::SendAcceptChannel, node_a.node.get_our_node_id())).unwrap();
183 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(node_a, channel_value, 42);
186 node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
187 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
188 assert_eq!(added_monitors.len(), 1);
189 assert_eq!(added_monitors[0].0, funding_output);
190 added_monitors.clear();
193 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();
195 let mut added_monitors = node_b.chan_monitor.added_monitors.lock().unwrap();
196 assert_eq!(added_monitors.len(), 1);
197 assert_eq!(added_monitors[0].0, funding_output);
198 added_monitors.clear();
201 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();
203 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
204 assert_eq!(added_monitors.len(), 1);
205 assert_eq!(added_monitors[0].0, funding_output);
206 added_monitors.clear();
209 let events_4 = node_a.node.get_and_clear_pending_events();
210 assert_eq!(events_4.len(), 1);
212 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
213 assert_eq!(user_channel_id, 42);
214 assert_eq!(*funding_txo, funding_output);
216 _ => panic!("Unexpected event"),
222 pub fn create_chan_between_nodes_with_value_confirm_first(node_recv: &Node, node_conf: &Node, tx: &Transaction) {
223 confirm_transaction(&node_conf.chain_monitor, &tx, tx.version);
224 node_recv.node.handle_funding_locked(&node_conf.node.get_our_node_id(), &get_event_msg!(node_conf, MessageSendEvent::SendFundingLocked, node_recv.node.get_our_node_id())).unwrap();
227 pub fn create_chan_between_nodes_with_value_confirm_second(node_recv: &Node, node_conf: &Node) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32]) {
229 let events_6 = node_conf.node.get_and_clear_pending_msg_events();
230 assert_eq!(events_6.len(), 2);
231 ((match events_6[0] {
232 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
233 channel_id = msg.channel_id.clone();
234 assert_eq!(*node_id, node_recv.node.get_our_node_id());
237 _ => panic!("Unexpected event"),
238 }, match events_6[1] {
239 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
240 assert_eq!(*node_id, node_recv.node.get_our_node_id());
243 _ => panic!("Unexpected event"),
247 pub fn create_chan_between_nodes_with_value_confirm(node_a: &Node, node_b: &Node, tx: &Transaction) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32]) {
248 create_chan_between_nodes_with_value_confirm_first(node_a, node_b, tx);
249 confirm_transaction(&node_a.chain_monitor, &tx, tx.version);
250 create_chan_between_nodes_with_value_confirm_second(node_b, node_a)
253 pub fn create_chan_between_nodes_with_value_a(node_a: &Node, node_b: &Node, channel_value: u64, push_msat: u64, a_flags: LocalFeatures, b_flags: LocalFeatures) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32], Transaction) {
254 let tx = create_chan_between_nodes_with_value_init(node_a, node_b, channel_value, push_msat, a_flags, b_flags);
255 let (msgs, chan_id) = create_chan_between_nodes_with_value_confirm(node_a, node_b, &tx);
259 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) {
260 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &as_funding_msgs.0).unwrap();
261 let bs_announcement_sigs = get_event_msg!(node_b, MessageSendEvent::SendAnnouncementSignatures, node_a.node.get_our_node_id());
262 node_b.node.handle_announcement_signatures(&node_a.node.get_our_node_id(), &as_funding_msgs.1).unwrap();
264 let events_7 = node_b.node.get_and_clear_pending_msg_events();
265 assert_eq!(events_7.len(), 1);
266 let (announcement, bs_update) = match events_7[0] {
267 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
270 _ => panic!("Unexpected event"),
273 node_a.node.handle_announcement_signatures(&node_b.node.get_our_node_id(), &bs_announcement_sigs).unwrap();
274 let events_8 = node_a.node.get_and_clear_pending_msg_events();
275 assert_eq!(events_8.len(), 1);
276 let as_update = match events_8[0] {
277 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
278 assert!(*announcement == *msg);
279 assert_eq!(update_msg.contents.short_channel_id, announcement.contents.short_channel_id);
280 assert_eq!(update_msg.contents.short_channel_id, bs_update.contents.short_channel_id);
283 _ => panic!("Unexpected event"),
286 *node_a.network_chan_count.borrow_mut() += 1;
288 ((*announcement).clone(), (*as_update).clone(), (*bs_update).clone())
291 pub fn create_announced_chan_between_nodes(nodes: &Vec<Node>, a: usize, b: usize, a_flags: LocalFeatures, b_flags: LocalFeatures) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
292 create_announced_chan_between_nodes_with_value(nodes, a, b, 100000, 10001, a_flags, b_flags)
295 pub fn create_announced_chan_between_nodes_with_value(nodes: &Vec<Node>, a: usize, b: usize, channel_value: u64, push_msat: u64, a_flags: LocalFeatures, b_flags: LocalFeatures) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
296 let chan_announcement = create_chan_between_nodes_with_value(&nodes[a], &nodes[b], channel_value, push_msat, a_flags, b_flags);
298 assert!(node.router.handle_channel_announcement(&chan_announcement.0).unwrap());
299 node.router.handle_channel_update(&chan_announcement.1).unwrap();
300 node.router.handle_channel_update(&chan_announcement.2).unwrap();
302 (chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
305 macro_rules! check_spends {
306 ($tx: expr, $spends_tx: expr) => {
308 $tx.verify(|out_point| {
309 if out_point.txid == $spends_tx.txid() {
310 $spends_tx.output.get(out_point.vout as usize).cloned()
319 macro_rules! get_closing_signed_broadcast {
320 ($node: expr, $dest_pubkey: expr) => {
322 let events = $node.get_and_clear_pending_msg_events();
323 assert!(events.len() == 1 || events.len() == 2);
324 (match events[events.len() - 1] {
325 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
326 assert_eq!(msg.contents.flags & 2, 2);
329 _ => panic!("Unexpected event"),
330 }, if events.len() == 2 {
332 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
333 assert_eq!(*node_id, $dest_pubkey);
336 _ => panic!("Unexpected event"),
343 macro_rules! check_closed_broadcast {
345 let events = $node.node.get_and_clear_pending_msg_events();
346 assert_eq!(events.len(), 1);
348 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
349 assert_eq!(msg.contents.flags & 2, 2);
351 _ => panic!("Unexpected event"),
356 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) {
357 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) };
358 let (node_b, broadcaster_b) = if close_inbound_first { (&outbound_node.node, &outbound_node.tx_broadcaster) } else { (&inbound_node.node, &inbound_node.tx_broadcaster) };
361 node_a.close_channel(channel_id).unwrap();
362 node_b.handle_shutdown(&node_a.get_our_node_id(), &get_event_msg!(struct_a, MessageSendEvent::SendShutdown, node_b.get_our_node_id())).unwrap();
364 let events_1 = node_b.get_and_clear_pending_msg_events();
365 assert!(events_1.len() >= 1);
366 let shutdown_b = match events_1[0] {
367 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
368 assert_eq!(node_id, &node_a.get_our_node_id());
371 _ => panic!("Unexpected event"),
374 let closing_signed_b = if !close_inbound_first {
375 assert_eq!(events_1.len(), 1);
378 Some(match events_1[1] {
379 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
380 assert_eq!(node_id, &node_a.get_our_node_id());
383 _ => panic!("Unexpected event"),
387 node_a.handle_shutdown(&node_b.get_our_node_id(), &shutdown_b).unwrap();
388 let (as_update, bs_update) = if close_inbound_first {
389 assert!(node_a.get_and_clear_pending_msg_events().is_empty());
390 node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
391 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
392 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
393 let (as_update, closing_signed_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
395 node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap()).unwrap();
396 let (bs_update, none_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
397 assert!(none_b.is_none());
398 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
399 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
400 (as_update, bs_update)
402 let closing_signed_a = get_event_msg!(struct_a, MessageSendEvent::SendClosingSigned, node_b.get_our_node_id());
404 node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a).unwrap();
405 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
406 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
407 let (bs_update, closing_signed_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
409 node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
410 let (as_update, none_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
411 assert!(none_a.is_none());
412 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
413 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
414 (as_update, bs_update)
416 assert_eq!(tx_a, tx_b);
417 check_spends!(tx_a, funding_tx);
419 (as_update, bs_update, tx_a)
422 pub struct SendEvent {
423 pub node_id: PublicKey,
424 pub msgs: Vec<msgs::UpdateAddHTLC>,
425 pub commitment_msg: msgs::CommitmentSigned,
428 pub fn from_commitment_update(node_id: PublicKey, updates: msgs::CommitmentUpdate) -> SendEvent {
429 assert!(updates.update_fulfill_htlcs.is_empty());
430 assert!(updates.update_fail_htlcs.is_empty());
431 assert!(updates.update_fail_malformed_htlcs.is_empty());
432 assert!(updates.update_fee.is_none());
433 SendEvent { node_id: node_id, msgs: updates.update_add_htlcs, commitment_msg: updates.commitment_signed }
436 pub fn from_event(event: MessageSendEvent) -> SendEvent {
438 MessageSendEvent::UpdateHTLCs { node_id, updates } => SendEvent::from_commitment_update(node_id, updates),
439 _ => panic!("Unexpected event type!"),
443 pub fn from_node(node: &Node) -> SendEvent {
444 let mut events = node.node.get_and_clear_pending_msg_events();
445 assert_eq!(events.len(), 1);
446 SendEvent::from_event(events.pop().unwrap())
450 macro_rules! check_added_monitors {
451 ($node: expr, $count: expr) => {
453 let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
454 assert_eq!(added_monitors.len(), $count);
455 added_monitors.clear();
460 macro_rules! commitment_signed_dance {
461 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */) => {
463 check_added_monitors!($node_a, 0);
464 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
465 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
466 check_added_monitors!($node_a, 1);
467 commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, false);
470 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */, true /* return last RAA */) => {
472 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!($node_a, $node_b.node.get_our_node_id());
473 check_added_monitors!($node_b, 0);
474 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
475 $node_b.node.handle_revoke_and_ack(&$node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
476 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
477 check_added_monitors!($node_b, 1);
478 $node_b.node.handle_commitment_signed(&$node_a.node.get_our_node_id(), &as_commitment_signed).unwrap();
479 let (bs_revoke_and_ack, extra_msg_option) = {
480 let events = $node_b.node.get_and_clear_pending_msg_events();
481 assert!(events.len() <= 2);
483 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
484 assert_eq!(*node_id, $node_a.node.get_our_node_id());
487 _ => panic!("Unexpected event"),
488 }, events.get(1).map(|e| e.clone()))
490 check_added_monitors!($node_b, 1);
492 assert!($node_a.node.get_and_clear_pending_events().is_empty());
493 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
495 (extra_msg_option, bs_revoke_and_ack)
498 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */, false /* return extra message */, true /* return last RAA */) => {
500 check_added_monitors!($node_a, 0);
501 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
502 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
503 check_added_monitors!($node_a, 1);
504 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
505 assert!(extra_msg_option.is_none());
509 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */) => {
511 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
512 $node_a.node.handle_revoke_and_ack(&$node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
513 check_added_monitors!($node_a, 1);
517 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, false /* no extra message */) => {
519 assert!(commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true).is_none());
522 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr) => {
524 commitment_signed_dance!($node_a, $node_b, $commitment_signed, $fail_backwards, true);
526 expect_pending_htlcs_forwardable!($node_a);
527 check_added_monitors!($node_a, 1);
529 let channel_state = $node_a.node.channel_state.lock().unwrap();
530 assert_eq!(channel_state.pending_msg_events.len(), 1);
531 if let MessageSendEvent::UpdateHTLCs { ref node_id, .. } = channel_state.pending_msg_events[0] {
532 assert_ne!(*node_id, $node_b.node.get_our_node_id());
533 } else { panic!("Unexpected event"); }
535 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
541 macro_rules! get_payment_preimage_hash {
544 let payment_preimage = PaymentPreimage([*$node.network_payment_count.borrow(); 32]);
545 *$node.network_payment_count.borrow_mut() += 1;
546 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner());
547 (payment_preimage, payment_hash)
552 macro_rules! expect_pending_htlcs_forwardable {
554 let events = $node.node.get_and_clear_pending_events();
555 assert_eq!(events.len(), 1);
557 Event::PendingHTLCsForwardable { .. } => { },
558 _ => panic!("Unexpected event"),
560 $node.node.process_pending_htlc_forwards();
564 macro_rules! expect_payment_received {
565 ($node: expr, $expected_payment_hash: expr, $expected_recv_value: expr) => {
566 let events = $node.node.get_and_clear_pending_events();
567 assert_eq!(events.len(), 1);
569 Event::PaymentReceived { ref payment_hash, amt } => {
570 assert_eq!($expected_payment_hash, *payment_hash);
571 assert_eq!($expected_recv_value, amt);
573 _ => panic!("Unexpected event"),
578 macro_rules! expect_payment_sent {
579 ($node: expr, $expected_payment_preimage: expr) => {
580 let events = $node.node.get_and_clear_pending_events();
581 assert_eq!(events.len(), 1);
583 Event::PaymentSent { ref payment_preimage } => {
584 assert_eq!($expected_payment_preimage, *payment_preimage);
586 _ => panic!("Unexpected event"),
591 pub fn send_along_route_with_hash(origin_node: &Node, route: Route, expected_route: &[&Node], recv_value: u64, our_payment_hash: PaymentHash) {
592 let mut payment_event = {
593 origin_node.node.send_payment(route, our_payment_hash).unwrap();
594 check_added_monitors!(origin_node, 1);
596 let mut events = origin_node.node.get_and_clear_pending_msg_events();
597 assert_eq!(events.len(), 1);
598 SendEvent::from_event(events.remove(0))
600 let mut prev_node = origin_node;
602 for (idx, &node) in expected_route.iter().enumerate() {
603 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
605 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
606 check_added_monitors!(node, 0);
607 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
609 expect_pending_htlcs_forwardable!(node);
611 if idx == expected_route.len() - 1 {
612 let events_2 = node.node.get_and_clear_pending_events();
613 assert_eq!(events_2.len(), 1);
615 Event::PaymentReceived { ref payment_hash, amt } => {
616 assert_eq!(our_payment_hash, *payment_hash);
617 assert_eq!(amt, recv_value);
619 _ => panic!("Unexpected event"),
622 let mut events_2 = node.node.get_and_clear_pending_msg_events();
623 assert_eq!(events_2.len(), 1);
624 check_added_monitors!(node, 1);
625 payment_event = SendEvent::from_event(events_2.remove(0));
626 assert_eq!(payment_event.msgs.len(), 1);
633 pub fn send_along_route(origin_node: &Node, route: Route, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
634 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(origin_node);
635 send_along_route_with_hash(origin_node, route, expected_route, recv_value, our_payment_hash);
636 (our_payment_preimage, our_payment_hash)
639 pub fn claim_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_preimage: PaymentPreimage, expected_amount: u64) {
640 assert!(expected_route.last().unwrap().node.claim_funds(our_payment_preimage, expected_amount));
641 check_added_monitors!(expected_route.last().unwrap(), 1);
643 let mut next_msgs: Option<(msgs::UpdateFulfillHTLC, msgs::CommitmentSigned)> = None;
644 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
645 macro_rules! get_next_msgs {
648 let events = $node.node.get_and_clear_pending_msg_events();
649 assert_eq!(events.len(), 1);
651 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 } } => {
652 assert!(update_add_htlcs.is_empty());
653 assert_eq!(update_fulfill_htlcs.len(), 1);
654 assert!(update_fail_htlcs.is_empty());
655 assert!(update_fail_malformed_htlcs.is_empty());
656 assert!(update_fee.is_none());
657 expected_next_node = node_id.clone();
658 Some((update_fulfill_htlcs[0].clone(), commitment_signed.clone()))
660 _ => panic!("Unexpected event"),
666 macro_rules! last_update_fulfill_dance {
667 ($node: expr, $prev_node: expr) => {
669 $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
670 check_added_monitors!($node, 0);
671 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
672 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
676 macro_rules! mid_update_fulfill_dance {
677 ($node: expr, $prev_node: expr, $new_msgs: expr) => {
679 $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
680 check_added_monitors!($node, 1);
681 let new_next_msgs = if $new_msgs {
682 get_next_msgs!($node)
684 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
687 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
688 next_msgs = new_next_msgs;
693 let mut prev_node = expected_route.last().unwrap();
694 for (idx, node) in expected_route.iter().rev().enumerate() {
695 assert_eq!(expected_next_node, node.node.get_our_node_id());
696 let update_next_msgs = !skip_last || idx != expected_route.len() - 1;
697 if next_msgs.is_some() {
698 mid_update_fulfill_dance!(node, prev_node, update_next_msgs);
699 } else if update_next_msgs {
700 next_msgs = get_next_msgs!(node);
702 assert!(node.node.get_and_clear_pending_msg_events().is_empty());
704 if !skip_last && idx == expected_route.len() - 1 {
705 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
712 last_update_fulfill_dance!(origin_node, expected_route.first().unwrap());
713 expect_payment_sent!(origin_node, our_payment_preimage);
717 pub fn claim_payment(origin_node: &Node, expected_route: &[&Node], our_payment_preimage: PaymentPreimage, expected_amount: u64) {
718 claim_payment_along_route(origin_node, expected_route, false, our_payment_preimage, expected_amount);
721 pub const TEST_FINAL_CLTV: u32 = 32;
723 pub fn route_payment(origin_node: &Node, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
724 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();
725 assert_eq!(route.hops.len(), expected_route.len());
726 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
727 assert_eq!(hop.pubkey, node.node.get_our_node_id());
730 send_along_route(origin_node, route, expected_route, recv_value)
733 pub fn route_over_limit(origin_node: &Node, expected_route: &[&Node], recv_value: u64) {
734 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();
735 assert_eq!(route.hops.len(), expected_route.len());
736 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
737 assert_eq!(hop.pubkey, node.node.get_our_node_id());
740 let (_, our_payment_hash) = get_payment_preimage_hash!(origin_node);
742 let err = origin_node.node.send_payment(route, our_payment_hash).err().unwrap();
744 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over the max HTLC value in flight our peer will accept"),
745 _ => panic!("Unknown error variants"),
749 pub fn send_payment(origin: &Node, expected_route: &[&Node], recv_value: u64, expected_value: u64) {
750 let our_payment_preimage = route_payment(&origin, expected_route, recv_value).0;
751 claim_payment(&origin, expected_route, our_payment_preimage, expected_value);
754 pub fn fail_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_hash: PaymentHash) {
755 assert!(expected_route.last().unwrap().node.fail_htlc_backwards(&our_payment_hash));
756 expect_pending_htlcs_forwardable!(expected_route.last().unwrap());
757 check_added_monitors!(expected_route.last().unwrap(), 1);
759 let mut next_msgs: Option<(msgs::UpdateFailHTLC, msgs::CommitmentSigned)> = None;
760 macro_rules! update_fail_dance {
761 ($node: expr, $prev_node: expr, $last_node: expr) => {
763 $node.node.handle_update_fail_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
764 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, !$last_node);
765 if skip_last && $last_node {
766 expect_pending_htlcs_forwardable!($node);
772 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
773 let mut prev_node = expected_route.last().unwrap();
774 for (idx, node) in expected_route.iter().rev().enumerate() {
775 assert_eq!(expected_next_node, node.node.get_our_node_id());
776 if next_msgs.is_some() {
777 // We may be the "last node" for the purpose of the commitment dance if we're
778 // skipping the last node (implying it is disconnected) and we're the
779 // second-to-last node!
780 update_fail_dance!(node, prev_node, skip_last && idx == expected_route.len() - 1);
783 let events = node.node.get_and_clear_pending_msg_events();
784 if !skip_last || idx != expected_route.len() - 1 {
785 assert_eq!(events.len(), 1);
787 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 } } => {
788 assert!(update_add_htlcs.is_empty());
789 assert!(update_fulfill_htlcs.is_empty());
790 assert_eq!(update_fail_htlcs.len(), 1);
791 assert!(update_fail_malformed_htlcs.is_empty());
792 assert!(update_fee.is_none());
793 expected_next_node = node_id.clone();
794 next_msgs = Some((update_fail_htlcs[0].clone(), commitment_signed.clone()));
796 _ => panic!("Unexpected event"),
799 assert!(events.is_empty());
801 if !skip_last && idx == expected_route.len() - 1 {
802 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
809 update_fail_dance!(origin_node, expected_route.first().unwrap(), true);
811 let events = origin_node.node.get_and_clear_pending_events();
812 assert_eq!(events.len(), 1);
814 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
815 assert_eq!(payment_hash, our_payment_hash);
816 assert!(rejected_by_dest);
818 _ => panic!("Unexpected event"),
823 pub fn fail_payment(origin_node: &Node, expected_route: &[&Node], our_payment_hash: PaymentHash) {
824 fail_payment_along_route(origin_node, expected_route, false, our_payment_hash);
827 pub fn create_network(node_count: usize, node_config: &[Option<UserConfig>]) -> Vec<Node> {
828 let mut nodes = Vec::new();
829 let mut rng = thread_rng();
830 let secp_ctx = Secp256k1::new();
832 let chan_count = Rc::new(RefCell::new(0));
833 let payment_count = Rc::new(RefCell::new(0));
835 for i in 0..node_count {
836 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::with_id(format!("node {}", i)));
837 let feeest = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 });
838 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
839 let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())});
840 let mut seed = [0; 32];
841 rng.fill_bytes(&mut seed);
842 let keys_manager = Arc::new(test_utils::TestKeysInterface::new(&seed, Network::Testnet, Arc::clone(&logger)));
843 let chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(chain_monitor.clone(), tx_broadcaster.clone(), logger.clone(), feeest.clone()));
844 let mut default_config = UserConfig::new();
845 default_config.channel_options.announced_channel = true;
846 default_config.peer_channel_config_limits.force_announced_channel_preference = false;
847 let node = ChannelManager::new(Network::Testnet, feeest.clone(), chan_monitor.clone(), chain_monitor.clone(), tx_broadcaster.clone(), Arc::clone(&logger), keys_manager.clone(), if node_config[i].is_some() { node_config[i].clone().unwrap() } else { default_config }, 0).unwrap();
848 let router = Router::new(PublicKey::from_secret_key(&secp_ctx, &keys_manager.get_node_secret()), chain_monitor.clone(), Arc::clone(&logger));
849 nodes.push(Node { chain_monitor, tx_broadcaster, chan_monitor, node, router, keys_manager, node_seed: seed,
850 network_payment_count: payment_count.clone(),
851 network_chan_count: chan_count.clone(),
859 pub enum HTLCType { NONE, TIMEOUT, SUCCESS }
860 /// Tests that the given node has broadcast transactions for the given Channel
862 /// First checks that the latest local commitment tx has been broadcast, unless an explicit
863 /// commitment_tx is provided, which may be used to test that a remote commitment tx was
864 /// broadcast and the revoked outputs were claimed.
866 /// Next tests that there is (or is not) a transaction that spends the commitment transaction
867 /// that appears to be the type of HTLC transaction specified in has_htlc_tx.
869 /// All broadcast transactions must be accounted for in one of the above three types of we'll
871 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> {
872 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
873 assert!(node_txn.len() >= if commitment_tx.is_some() { 0 } else { 1 } + if has_htlc_tx == HTLCType::NONE { 0 } else { 1 });
875 let mut res = Vec::with_capacity(2);
876 node_txn.retain(|tx| {
877 if tx.input.len() == 1 && tx.input[0].previous_output.txid == chan.3.txid() {
878 check_spends!(tx, chan.3.clone());
879 if commitment_tx.is_none() {
880 res.push(tx.clone());
885 if let Some(explicit_tx) = commitment_tx {
886 res.push(explicit_tx.clone());
889 assert_eq!(res.len(), 1);
891 if has_htlc_tx != HTLCType::NONE {
892 node_txn.retain(|tx| {
893 if tx.input.len() == 1 && tx.input[0].previous_output.txid == res[0].txid() {
894 check_spends!(tx, res[0].clone());
895 if has_htlc_tx == HTLCType::TIMEOUT {
896 assert!(tx.lock_time != 0);
898 assert!(tx.lock_time == 0);
900 res.push(tx.clone());
904 assert!(res.len() == 2 || res.len() == 3);
906 assert_eq!(res[1], res[2]);
910 assert!(node_txn.is_empty());
914 /// Tests that the given node has broadcast a claim transaction against the provided revoked
915 /// HTLC transaction.
916 pub fn test_revoked_htlc_claim_txn_broadcast(node: &Node, revoked_tx: Transaction) {
917 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
918 assert_eq!(node_txn.len(), 1);
919 node_txn.retain(|tx| {
920 if tx.input.len() == 1 && tx.input[0].previous_output.txid == revoked_tx.txid() {
921 check_spends!(tx, revoked_tx.clone());
925 assert!(node_txn.is_empty());
928 pub fn check_preimage_claim(node: &Node, prev_txn: &Vec<Transaction>) -> Vec<Transaction> {
929 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
931 assert!(node_txn.len() >= 1);
932 assert_eq!(node_txn[0].input.len(), 1);
933 let mut found_prev = false;
936 if node_txn[0].input[0].previous_output.txid == tx.txid() {
937 check_spends!(node_txn[0], tx.clone());
938 assert!(node_txn[0].input[0].witness[2].len() > 106); // must spend an htlc output
939 assert_eq!(tx.input.len(), 1); // must spend a commitment tx
947 let mut res = Vec::new();
948 mem::swap(&mut *node_txn, &mut res);
952 pub fn get_announce_close_broadcast_events(nodes: &Vec<Node>, a: usize, b: usize) {
953 let events_1 = nodes[a].node.get_and_clear_pending_msg_events();
954 assert_eq!(events_1.len(), 1);
955 let as_update = match events_1[0] {
956 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
959 _ => panic!("Unexpected event"),
962 let events_2 = nodes[b].node.get_and_clear_pending_msg_events();
963 assert_eq!(events_2.len(), 1);
964 let bs_update = match events_2[0] {
965 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
968 _ => panic!("Unexpected event"),
972 node.router.handle_channel_update(&as_update).unwrap();
973 node.router.handle_channel_update(&bs_update).unwrap();
977 macro_rules! get_channel_value_stat {
978 ($node: expr, $channel_id: expr) => {{
979 let chan_lock = $node.node.channel_state.lock().unwrap();
980 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
981 chan.get_value_stat()
985 macro_rules! get_chan_reestablish_msgs {
986 ($src_node: expr, $dst_node: expr) => {
988 let mut res = Vec::with_capacity(1);
989 for msg in $src_node.node.get_and_clear_pending_msg_events() {
990 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
991 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
992 res.push(msg.clone());
994 panic!("Unexpected event")
1002 macro_rules! handle_chan_reestablish_msgs {
1003 ($src_node: expr, $dst_node: expr) => {
1005 let msg_events = $src_node.node.get_and_clear_pending_msg_events();
1007 let funding_locked = if let Some(&MessageSendEvent::SendFundingLocked { ref node_id, ref msg }) = msg_events.get(0) {
1009 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
1015 let mut revoke_and_ack = None;
1016 let mut commitment_update = None;
1017 let order = if let Some(ev) = msg_events.get(idx) {
1020 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
1021 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
1022 revoke_and_ack = Some(msg.clone());
1023 RAACommitmentOrder::RevokeAndACKFirst
1025 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
1026 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
1027 commitment_update = Some(updates.clone());
1028 RAACommitmentOrder::CommitmentFirst
1030 _ => panic!("Unexpected event"),
1033 RAACommitmentOrder::CommitmentFirst
1036 if let Some(ev) = msg_events.get(idx) {
1038 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
1039 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
1040 assert!(revoke_and_ack.is_none());
1041 revoke_and_ack = Some(msg.clone());
1043 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
1044 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
1045 assert!(commitment_update.is_none());
1046 commitment_update = Some(updates.clone());
1048 _ => panic!("Unexpected event"),
1052 (funding_locked, revoke_and_ack, commitment_update, order)
1057 /// pending_htlc_adds includes both the holding cell and in-flight update_add_htlcs, whereas
1058 /// for claims/fails they are separated out.
1059 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)) {
1060 node_a.node.peer_connected(&node_b.node.get_our_node_id());
1061 let reestablish_1 = get_chan_reestablish_msgs!(node_a, node_b);
1062 node_b.node.peer_connected(&node_a.node.get_our_node_id());
1063 let reestablish_2 = get_chan_reestablish_msgs!(node_b, node_a);
1065 if send_funding_locked.0 {
1066 // If a expects a funding_locked, it better not think it has received a revoke_and_ack
1068 for reestablish in reestablish_1.iter() {
1069 assert_eq!(reestablish.next_remote_commitment_number, 0);
1072 if send_funding_locked.1 {
1073 // If b expects a funding_locked, it better not think it has received a revoke_and_ack
1075 for reestablish in reestablish_2.iter() {
1076 assert_eq!(reestablish.next_remote_commitment_number, 0);
1079 if send_funding_locked.0 || send_funding_locked.1 {
1080 // If we expect any funding_locked's, both sides better have set
1081 // next_local_commitment_number to 1
1082 for reestablish in reestablish_1.iter() {
1083 assert_eq!(reestablish.next_local_commitment_number, 1);
1085 for reestablish in reestablish_2.iter() {
1086 assert_eq!(reestablish.next_local_commitment_number, 1);
1090 let mut resp_1 = Vec::new();
1091 for msg in reestablish_1 {
1092 node_b.node.handle_channel_reestablish(&node_a.node.get_our_node_id(), &msg).unwrap();
1093 resp_1.push(handle_chan_reestablish_msgs!(node_b, node_a));
1095 if pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
1096 check_added_monitors!(node_b, 1);
1098 check_added_monitors!(node_b, 0);
1101 let mut resp_2 = Vec::new();
1102 for msg in reestablish_2 {
1103 node_a.node.handle_channel_reestablish(&node_b.node.get_our_node_id(), &msg).unwrap();
1104 resp_2.push(handle_chan_reestablish_msgs!(node_a, node_b));
1106 if pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
1107 check_added_monitors!(node_a, 1);
1109 check_added_monitors!(node_a, 0);
1112 // We don't yet support both needing updates, as that would require a different commitment dance:
1113 assert!((pending_htlc_adds.0 == 0 && pending_htlc_claims.0 == 0 && pending_cell_htlc_claims.0 == 0 && pending_cell_htlc_fails.0 == 0) ||
1114 (pending_htlc_adds.1 == 0 && pending_htlc_claims.1 == 0 && pending_cell_htlc_claims.1 == 0 && pending_cell_htlc_fails.1 == 0));
1116 for chan_msgs in resp_1.drain(..) {
1117 if send_funding_locked.0 {
1118 node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
1119 let announcement_event = node_a.node.get_and_clear_pending_msg_events();
1120 if !announcement_event.is_empty() {
1121 assert_eq!(announcement_event.len(), 1);
1122 if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
1123 //TODO: Test announcement_sigs re-sending
1124 } else { panic!("Unexpected event!"); }
1127 assert!(chan_msgs.0.is_none());
1130 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
1131 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
1132 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
1133 check_added_monitors!(node_a, 1);
1135 assert!(chan_msgs.1.is_none());
1137 if pending_htlc_adds.0 != 0 || pending_htlc_claims.0 != 0 || pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
1138 let commitment_update = chan_msgs.2.unwrap();
1139 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
1140 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.0 as usize);
1142 assert!(commitment_update.update_add_htlcs.is_empty());
1144 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
1145 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
1146 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
1147 for update_add in commitment_update.update_add_htlcs {
1148 node_a.node.handle_update_add_htlc(&node_b.node.get_our_node_id(), &update_add).unwrap();
1150 for update_fulfill in commitment_update.update_fulfill_htlcs {
1151 node_a.node.handle_update_fulfill_htlc(&node_b.node.get_our_node_id(), &update_fulfill).unwrap();
1153 for update_fail in commitment_update.update_fail_htlcs {
1154 node_a.node.handle_update_fail_htlc(&node_b.node.get_our_node_id(), &update_fail).unwrap();
1157 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
1158 commitment_signed_dance!(node_a, node_b, commitment_update.commitment_signed, false);
1160 node_a.node.handle_commitment_signed(&node_b.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
1161 check_added_monitors!(node_a, 1);
1162 let as_revoke_and_ack = get_event_msg!(node_a, MessageSendEvent::SendRevokeAndACK, node_b.node.get_our_node_id());
1163 // No commitment_signed so get_event_msg's assert(len == 1) passes
1164 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
1165 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
1166 check_added_monitors!(node_b, 1);
1169 assert!(chan_msgs.2.is_none());
1173 for chan_msgs in resp_2.drain(..) {
1174 if send_funding_locked.1 {
1175 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
1176 let announcement_event = node_b.node.get_and_clear_pending_msg_events();
1177 if !announcement_event.is_empty() {
1178 assert_eq!(announcement_event.len(), 1);
1179 if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
1180 //TODO: Test announcement_sigs re-sending
1181 } else { panic!("Unexpected event!"); }
1184 assert!(chan_msgs.0.is_none());
1187 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
1188 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
1189 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
1190 check_added_monitors!(node_b, 1);
1192 assert!(chan_msgs.1.is_none());
1194 if pending_htlc_adds.1 != 0 || pending_htlc_claims.1 != 0 || pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
1195 let commitment_update = chan_msgs.2.unwrap();
1196 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
1197 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.1 as usize);
1199 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
1200 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
1201 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
1202 for update_add in commitment_update.update_add_htlcs {
1203 node_b.node.handle_update_add_htlc(&node_a.node.get_our_node_id(), &update_add).unwrap();
1205 for update_fulfill in commitment_update.update_fulfill_htlcs {
1206 node_b.node.handle_update_fulfill_htlc(&node_a.node.get_our_node_id(), &update_fulfill).unwrap();
1208 for update_fail in commitment_update.update_fail_htlcs {
1209 node_b.node.handle_update_fail_htlc(&node_a.node.get_our_node_id(), &update_fail).unwrap();
1212 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
1213 commitment_signed_dance!(node_b, node_a, commitment_update.commitment_signed, false);
1215 node_b.node.handle_commitment_signed(&node_a.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
1216 check_added_monitors!(node_b, 1);
1217 let bs_revoke_and_ack = get_event_msg!(node_b, MessageSendEvent::SendRevokeAndACK, node_a.node.get_our_node_id());
1218 // No commitment_signed so get_event_msg's assert(len == 1) passes
1219 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
1220 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
1221 check_added_monitors!(node_a, 1);
1224 assert!(chan_msgs.2.is_none());