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};
9 use ln::features::InitFeatures;
11 use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler};
12 use util::enforcing_trait_impls::EnforcingChannelKeys;
14 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
15 use util::errors::APIError;
16 use util::logger::Logger;
17 use util::config::UserConfig;
19 use bitcoin::util::hash::BitcoinHash;
20 use bitcoin::blockdata::block::BlockHeader;
21 use bitcoin::blockdata::transaction::{Transaction, TxOut};
22 use bitcoin::network::constants::Network;
24 use bitcoin_hashes::sha256::Hash as Sha256;
25 use bitcoin_hashes::sha256d::Hash as Sha256d;
26 use bitcoin_hashes::Hash;
28 use secp256k1::Secp256k1;
29 use secp256k1::key::PublicKey;
31 use rand::{thread_rng,Rng};
33 use std::cell::RefCell;
35 use std::sync::{Arc, Mutex};
38 pub const CHAN_CONFIRM_DEPTH: u32 = 100;
39 pub fn confirm_transaction(notifier: &chaininterface::BlockNotifier, 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 notifier.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 notifier.block_connected_checked(&header, i, &vec![], &[0; 0]);
49 pub fn connect_blocks(notifier: &chaininterface::BlockNotifier, depth: u32, height: u32, parent: bool, prev_blockhash: Sha256d) -> Sha256d {
50 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 };
51 notifier.block_connected_checked(&header, height + 1, &Vec::new(), &Vec::new());
52 for i in 2..depth + 1 {
53 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
54 notifier.block_connected_checked(&header, height + i, &Vec::new(), &Vec::new());
60 pub block_notifier: Arc<chaininterface::BlockNotifier>,
61 pub chain_monitor: Arc<chaininterface::ChainWatchInterfaceUtil>,
62 pub tx_broadcaster: Arc<test_utils::TestBroadcaster>,
63 pub chan_monitor: Arc<test_utils::TestChannelMonitor>,
64 pub keys_manager: Arc<test_utils::TestKeysInterface>,
65 pub node: Arc<ChannelManager<EnforcingChannelKeys>>,
67 pub node_seed: [u8; 32],
68 pub network_payment_count: Rc<RefCell<u8>>,
69 pub network_chan_count: Rc<RefCell<u32>>,
70 pub logger: Arc<test_utils::TestLogger>
74 if !::std::thread::panicking() {
75 // Check that we processed all pending events
76 assert!(self.node.get_and_clear_pending_msg_events().is_empty());
77 assert!(self.node.get_and_clear_pending_events().is_empty());
78 assert!(self.chan_monitor.added_monitors.lock().unwrap().is_empty());
83 pub fn create_chan_between_nodes(node_a: &Node, node_b: &Node, a_flags: InitFeatures, b_flags: InitFeatures) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
84 create_chan_between_nodes_with_value(node_a, node_b, 100000, 10001, a_flags, b_flags)
87 pub fn create_chan_between_nodes_with_value(node_a: &Node, node_b: &Node, channel_value: u64, push_msat: u64, a_flags: InitFeatures, b_flags: InitFeatures) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
88 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);
89 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(node_a, node_b, &funding_locked);
90 (announcement, as_update, bs_update, channel_id, tx)
93 macro_rules! get_revoke_commit_msgs {
94 ($node: expr, $node_id: expr) => {
96 let events = $node.node.get_and_clear_pending_msg_events();
97 assert_eq!(events.len(), 2);
99 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
100 assert_eq!(*node_id, $node_id);
103 _ => panic!("Unexpected event"),
105 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
106 assert_eq!(*node_id, $node_id);
107 assert!(updates.update_add_htlcs.is_empty());
108 assert!(updates.update_fulfill_htlcs.is_empty());
109 assert!(updates.update_fail_htlcs.is_empty());
110 assert!(updates.update_fail_malformed_htlcs.is_empty());
111 assert!(updates.update_fee.is_none());
112 updates.commitment_signed.clone()
114 _ => panic!("Unexpected event"),
120 macro_rules! get_event_msg {
121 ($node: expr, $event_type: path, $node_id: expr) => {
123 let events = $node.node.get_and_clear_pending_msg_events();
124 assert_eq!(events.len(), 1);
126 $event_type { ref node_id, ref msg } => {
127 assert_eq!(*node_id, $node_id);
130 _ => panic!("Unexpected event"),
136 macro_rules! get_htlc_update_msgs {
137 ($node: expr, $node_id: expr) => {
139 let events = $node.node.get_and_clear_pending_msg_events();
140 assert_eq!(events.len(), 1);
142 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
143 assert_eq!(*node_id, $node_id);
146 _ => panic!("Unexpected event"),
152 macro_rules! get_feerate {
153 ($node: expr, $channel_id: expr) => {
155 let chan_lock = $node.node.channel_state.lock().unwrap();
156 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
162 pub fn create_funding_transaction(node: &Node, expected_chan_value: u64, expected_user_chan_id: u64) -> ([u8; 32], Transaction, OutPoint) {
163 let chan_id = *node.network_chan_count.borrow();
165 let events = node.node.get_and_clear_pending_events();
166 assert_eq!(events.len(), 1);
168 Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
169 assert_eq!(*channel_value_satoshis, expected_chan_value);
170 assert_eq!(user_channel_id, expected_user_chan_id);
172 let tx = Transaction { version: chan_id as u32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
173 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
175 let funding_outpoint = OutPoint::new(tx.txid(), 0);
176 (*temporary_channel_id, tx, funding_outpoint)
178 _ => panic!("Unexpected event"),
182 pub fn create_chan_between_nodes_with_value_init(node_a: &Node, node_b: &Node, channel_value: u64, push_msat: u64, a_flags: InitFeatures, b_flags: InitFeatures) -> Transaction {
183 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42).unwrap();
184 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()));
185 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()));
187 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(node_a, channel_value, 42);
190 node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
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();
197 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()));
199 let mut added_monitors = node_b.chan_monitor.added_monitors.lock().unwrap();
200 assert_eq!(added_monitors.len(), 1);
201 assert_eq!(added_monitors[0].0, funding_output);
202 added_monitors.clear();
205 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()));
207 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
208 assert_eq!(added_monitors.len(), 1);
209 assert_eq!(added_monitors[0].0, funding_output);
210 added_monitors.clear();
213 let events_4 = node_a.node.get_and_clear_pending_events();
214 assert_eq!(events_4.len(), 1);
216 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
217 assert_eq!(user_channel_id, 42);
218 assert_eq!(*funding_txo, funding_output);
220 _ => panic!("Unexpected event"),
226 pub fn create_chan_between_nodes_with_value_confirm_first(node_recv: &Node, node_conf: &Node, tx: &Transaction) {
227 confirm_transaction(&node_conf.block_notifier, &node_conf.chain_monitor, &tx, tx.version);
228 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()));
231 pub fn create_chan_between_nodes_with_value_confirm_second(node_recv: &Node, node_conf: &Node) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32]) {
233 let events_6 = node_conf.node.get_and_clear_pending_msg_events();
234 assert_eq!(events_6.len(), 2);
235 ((match events_6[0] {
236 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
237 channel_id = msg.channel_id.clone();
238 assert_eq!(*node_id, node_recv.node.get_our_node_id());
241 _ => panic!("Unexpected event"),
242 }, match events_6[1] {
243 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
244 assert_eq!(*node_id, node_recv.node.get_our_node_id());
247 _ => panic!("Unexpected event"),
251 pub fn create_chan_between_nodes_with_value_confirm(node_a: &Node, node_b: &Node, tx: &Transaction) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32]) {
252 create_chan_between_nodes_with_value_confirm_first(node_a, node_b, tx);
253 confirm_transaction(&node_a.block_notifier, &node_a.chain_monitor, &tx, tx.version);
254 create_chan_between_nodes_with_value_confirm_second(node_b, node_a)
257 pub fn create_chan_between_nodes_with_value_a(node_a: &Node, node_b: &Node, channel_value: u64, push_msat: u64, a_flags: InitFeatures, b_flags: InitFeatures) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32], Transaction) {
258 let tx = create_chan_between_nodes_with_value_init(node_a, node_b, channel_value, push_msat, a_flags, b_flags);
259 let (msgs, chan_id) = create_chan_between_nodes_with_value_confirm(node_a, node_b, &tx);
263 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) {
264 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &as_funding_msgs.0);
265 let bs_announcement_sigs = get_event_msg!(node_b, MessageSendEvent::SendAnnouncementSignatures, node_a.node.get_our_node_id());
266 node_b.node.handle_announcement_signatures(&node_a.node.get_our_node_id(), &as_funding_msgs.1);
268 let events_7 = node_b.node.get_and_clear_pending_msg_events();
269 assert_eq!(events_7.len(), 1);
270 let (announcement, bs_update) = match events_7[0] {
271 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
274 _ => panic!("Unexpected event"),
277 node_a.node.handle_announcement_signatures(&node_b.node.get_our_node_id(), &bs_announcement_sigs);
278 let events_8 = node_a.node.get_and_clear_pending_msg_events();
279 assert_eq!(events_8.len(), 1);
280 let as_update = match events_8[0] {
281 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
282 assert!(*announcement == *msg);
283 assert_eq!(update_msg.contents.short_channel_id, announcement.contents.short_channel_id);
284 assert_eq!(update_msg.contents.short_channel_id, bs_update.contents.short_channel_id);
287 _ => panic!("Unexpected event"),
290 *node_a.network_chan_count.borrow_mut() += 1;
292 ((*announcement).clone(), (*as_update).clone(), (*bs_update).clone())
295 pub fn create_announced_chan_between_nodes(nodes: &Vec<Node>, a: usize, b: usize, a_flags: InitFeatures, b_flags: InitFeatures) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
296 create_announced_chan_between_nodes_with_value(nodes, a, b, 100000, 10001, a_flags, b_flags)
299 pub fn create_announced_chan_between_nodes_with_value(nodes: &Vec<Node>, a: usize, b: usize, channel_value: u64, push_msat: u64, a_flags: InitFeatures, b_flags: InitFeatures) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
300 let chan_announcement = create_chan_between_nodes_with_value(&nodes[a], &nodes[b], channel_value, push_msat, a_flags, b_flags);
302 assert!(node.router.handle_channel_announcement(&chan_announcement.0).unwrap());
303 node.router.handle_channel_update(&chan_announcement.1).unwrap();
304 node.router.handle_channel_update(&chan_announcement.2).unwrap();
306 (chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
309 macro_rules! check_spends {
310 ($tx: expr, $spends_tx: expr) => {
312 $tx.verify(|out_point| {
313 if out_point.txid == $spends_tx.txid() {
314 $spends_tx.output.get(out_point.vout as usize).cloned()
323 macro_rules! get_closing_signed_broadcast {
324 ($node: expr, $dest_pubkey: expr) => {
326 let events = $node.get_and_clear_pending_msg_events();
327 assert!(events.len() == 1 || events.len() == 2);
328 (match events[events.len() - 1] {
329 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
330 assert_eq!(msg.contents.flags & 2, 2);
333 _ => panic!("Unexpected event"),
334 }, if events.len() == 2 {
336 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
337 assert_eq!(*node_id, $dest_pubkey);
340 _ => panic!("Unexpected event"),
347 macro_rules! check_closed_broadcast {
348 ($node: expr, $with_error_msg: expr) => {{
349 let events = $node.node.get_and_clear_pending_msg_events();
350 assert_eq!(events.len(), if $with_error_msg { 2 } else { 1 });
352 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
353 assert_eq!(msg.contents.flags & 2, 2);
355 _ => panic!("Unexpected event"),
359 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
360 // TODO: Check node_id
363 _ => panic!("Unexpected event"),
369 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) {
370 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) };
371 let (node_b, broadcaster_b) = if close_inbound_first { (&outbound_node.node, &outbound_node.tx_broadcaster) } else { (&inbound_node.node, &inbound_node.tx_broadcaster) };
374 node_a.close_channel(channel_id).unwrap();
375 node_b.handle_shutdown(&node_a.get_our_node_id(), &get_event_msg!(struct_a, MessageSendEvent::SendShutdown, node_b.get_our_node_id()));
377 let events_1 = node_b.get_and_clear_pending_msg_events();
378 assert!(events_1.len() >= 1);
379 let shutdown_b = match events_1[0] {
380 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
381 assert_eq!(node_id, &node_a.get_our_node_id());
384 _ => panic!("Unexpected event"),
387 let closing_signed_b = if !close_inbound_first {
388 assert_eq!(events_1.len(), 1);
391 Some(match events_1[1] {
392 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
393 assert_eq!(node_id, &node_a.get_our_node_id());
396 _ => panic!("Unexpected event"),
400 node_a.handle_shutdown(&node_b.get_our_node_id(), &shutdown_b);
401 let (as_update, bs_update) = if close_inbound_first {
402 assert!(node_a.get_and_clear_pending_msg_events().is_empty());
403 node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap());
404 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
405 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
406 let (as_update, closing_signed_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
408 node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap());
409 let (bs_update, none_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
410 assert!(none_b.is_none());
411 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
412 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
413 (as_update, bs_update)
415 let closing_signed_a = get_event_msg!(struct_a, MessageSendEvent::SendClosingSigned, node_b.get_our_node_id());
417 node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a);
418 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
419 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
420 let (bs_update, closing_signed_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
422 node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap());
423 let (as_update, none_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
424 assert!(none_a.is_none());
425 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
426 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
427 (as_update, bs_update)
429 assert_eq!(tx_a, tx_b);
430 check_spends!(tx_a, funding_tx);
432 (as_update, bs_update, tx_a)
435 pub struct SendEvent {
436 pub node_id: PublicKey,
437 pub msgs: Vec<msgs::UpdateAddHTLC>,
438 pub commitment_msg: msgs::CommitmentSigned,
441 pub fn from_commitment_update(node_id: PublicKey, updates: msgs::CommitmentUpdate) -> SendEvent {
442 assert!(updates.update_fulfill_htlcs.is_empty());
443 assert!(updates.update_fail_htlcs.is_empty());
444 assert!(updates.update_fail_malformed_htlcs.is_empty());
445 assert!(updates.update_fee.is_none());
446 SendEvent { node_id: node_id, msgs: updates.update_add_htlcs, commitment_msg: updates.commitment_signed }
449 pub fn from_event(event: MessageSendEvent) -> SendEvent {
451 MessageSendEvent::UpdateHTLCs { node_id, updates } => SendEvent::from_commitment_update(node_id, updates),
452 _ => panic!("Unexpected event type!"),
456 pub fn from_node(node: &Node) -> SendEvent {
457 let mut events = node.node.get_and_clear_pending_msg_events();
458 assert_eq!(events.len(), 1);
459 SendEvent::from_event(events.pop().unwrap())
463 macro_rules! check_added_monitors {
464 ($node: expr, $count: expr) => {
466 let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
467 assert_eq!(added_monitors.len(), $count);
468 added_monitors.clear();
473 macro_rules! commitment_signed_dance {
474 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */) => {
476 check_added_monitors!($node_a, 0);
477 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
478 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed);
479 check_added_monitors!($node_a, 1);
480 commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, false);
483 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */, true /* return last RAA */) => {
485 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!($node_a, $node_b.node.get_our_node_id());
486 check_added_monitors!($node_b, 0);
487 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
488 $node_b.node.handle_revoke_and_ack(&$node_a.node.get_our_node_id(), &as_revoke_and_ack);
489 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
490 check_added_monitors!($node_b, 1);
491 $node_b.node.handle_commitment_signed(&$node_a.node.get_our_node_id(), &as_commitment_signed);
492 let (bs_revoke_and_ack, extra_msg_option) = {
493 let events = $node_b.node.get_and_clear_pending_msg_events();
494 assert!(events.len() <= 2);
496 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
497 assert_eq!(*node_id, $node_a.node.get_our_node_id());
500 _ => panic!("Unexpected event"),
501 }, events.get(1).map(|e| e.clone()))
503 check_added_monitors!($node_b, 1);
505 assert!($node_a.node.get_and_clear_pending_events().is_empty());
506 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
508 (extra_msg_option, bs_revoke_and_ack)
511 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */, false /* return extra message */, true /* return last RAA */) => {
513 check_added_monitors!($node_a, 0);
514 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
515 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed);
516 check_added_monitors!($node_a, 1);
517 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
518 assert!(extra_msg_option.is_none());
522 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */) => {
524 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
525 $node_a.node.handle_revoke_and_ack(&$node_b.node.get_our_node_id(), &bs_revoke_and_ack);
526 check_added_monitors!($node_a, 1);
530 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, false /* no extra message */) => {
532 assert!(commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true).is_none());
535 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr) => {
537 commitment_signed_dance!($node_a, $node_b, $commitment_signed, $fail_backwards, true);
539 expect_pending_htlcs_forwardable!($node_a);
540 check_added_monitors!($node_a, 1);
542 let channel_state = $node_a.node.channel_state.lock().unwrap();
543 assert_eq!(channel_state.pending_msg_events.len(), 1);
544 if let MessageSendEvent::UpdateHTLCs { ref node_id, .. } = channel_state.pending_msg_events[0] {
545 assert_ne!(*node_id, $node_b.node.get_our_node_id());
546 } else { panic!("Unexpected event"); }
548 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
554 macro_rules! get_payment_preimage_hash {
557 let payment_preimage = PaymentPreimage([*$node.network_payment_count.borrow(); 32]);
558 *$node.network_payment_count.borrow_mut() += 1;
559 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner());
560 (payment_preimage, payment_hash)
565 macro_rules! expect_pending_htlcs_forwardable {
567 let events = $node.node.get_and_clear_pending_events();
568 assert_eq!(events.len(), 1);
570 Event::PendingHTLCsForwardable { .. } => { },
571 _ => panic!("Unexpected event"),
573 $node.node.process_pending_htlc_forwards();
577 macro_rules! expect_payment_received {
578 ($node: expr, $expected_payment_hash: expr, $expected_recv_value: expr) => {
579 let events = $node.node.get_and_clear_pending_events();
580 assert_eq!(events.len(), 1);
582 Event::PaymentReceived { ref payment_hash, amt } => {
583 assert_eq!($expected_payment_hash, *payment_hash);
584 assert_eq!($expected_recv_value, amt);
586 _ => panic!("Unexpected event"),
591 macro_rules! expect_payment_sent {
592 ($node: expr, $expected_payment_preimage: expr) => {
593 let events = $node.node.get_and_clear_pending_events();
594 assert_eq!(events.len(), 1);
596 Event::PaymentSent { ref payment_preimage } => {
597 assert_eq!($expected_payment_preimage, *payment_preimage);
599 _ => panic!("Unexpected event"),
604 pub fn send_along_route_with_hash(origin_node: &Node, route: Route, expected_route: &[&Node], recv_value: u64, our_payment_hash: PaymentHash) {
605 let mut payment_event = {
606 origin_node.node.send_payment(route, our_payment_hash).unwrap();
607 check_added_monitors!(origin_node, 1);
609 let mut events = origin_node.node.get_and_clear_pending_msg_events();
610 assert_eq!(events.len(), 1);
611 SendEvent::from_event(events.remove(0))
613 let mut prev_node = origin_node;
615 for (idx, &node) in expected_route.iter().enumerate() {
616 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
618 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
619 check_added_monitors!(node, 0);
620 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
622 expect_pending_htlcs_forwardable!(node);
624 if idx == expected_route.len() - 1 {
625 let events_2 = node.node.get_and_clear_pending_events();
626 assert_eq!(events_2.len(), 1);
628 Event::PaymentReceived { ref payment_hash, amt } => {
629 assert_eq!(our_payment_hash, *payment_hash);
630 assert_eq!(amt, recv_value);
632 _ => panic!("Unexpected event"),
635 let mut events_2 = node.node.get_and_clear_pending_msg_events();
636 assert_eq!(events_2.len(), 1);
637 check_added_monitors!(node, 1);
638 payment_event = SendEvent::from_event(events_2.remove(0));
639 assert_eq!(payment_event.msgs.len(), 1);
646 pub fn send_along_route(origin_node: &Node, route: Route, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
647 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(origin_node);
648 send_along_route_with_hash(origin_node, route, expected_route, recv_value, our_payment_hash);
649 (our_payment_preimage, our_payment_hash)
652 pub fn claim_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_preimage: PaymentPreimage, expected_amount: u64) {
653 assert!(expected_route.last().unwrap().node.claim_funds(our_payment_preimage, expected_amount));
654 check_added_monitors!(expected_route.last().unwrap(), 1);
656 let mut next_msgs: Option<(msgs::UpdateFulfillHTLC, msgs::CommitmentSigned)> = None;
657 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
658 macro_rules! get_next_msgs {
661 let events = $node.node.get_and_clear_pending_msg_events();
662 assert_eq!(events.len(), 1);
664 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 } } => {
665 assert!(update_add_htlcs.is_empty());
666 assert_eq!(update_fulfill_htlcs.len(), 1);
667 assert!(update_fail_htlcs.is_empty());
668 assert!(update_fail_malformed_htlcs.is_empty());
669 assert!(update_fee.is_none());
670 expected_next_node = node_id.clone();
671 Some((update_fulfill_htlcs[0].clone(), commitment_signed.clone()))
673 _ => panic!("Unexpected event"),
679 macro_rules! last_update_fulfill_dance {
680 ($node: expr, $prev_node: expr) => {
682 $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0);
683 check_added_monitors!($node, 0);
684 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
685 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
689 macro_rules! mid_update_fulfill_dance {
690 ($node: expr, $prev_node: expr, $new_msgs: expr) => {
692 $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0);
693 check_added_monitors!($node, 1);
694 let new_next_msgs = if $new_msgs {
695 get_next_msgs!($node)
697 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
700 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
701 next_msgs = new_next_msgs;
706 let mut prev_node = expected_route.last().unwrap();
707 for (idx, node) in expected_route.iter().rev().enumerate() {
708 assert_eq!(expected_next_node, node.node.get_our_node_id());
709 let update_next_msgs = !skip_last || idx != expected_route.len() - 1;
710 if next_msgs.is_some() {
711 mid_update_fulfill_dance!(node, prev_node, update_next_msgs);
712 } else if update_next_msgs {
713 next_msgs = get_next_msgs!(node);
715 assert!(node.node.get_and_clear_pending_msg_events().is_empty());
717 if !skip_last && idx == expected_route.len() - 1 {
718 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
725 last_update_fulfill_dance!(origin_node, expected_route.first().unwrap());
726 expect_payment_sent!(origin_node, our_payment_preimage);
730 pub fn claim_payment(origin_node: &Node, expected_route: &[&Node], our_payment_preimage: PaymentPreimage, expected_amount: u64) {
731 claim_payment_along_route(origin_node, expected_route, false, our_payment_preimage, expected_amount);
734 pub const TEST_FINAL_CLTV: u32 = 32;
736 pub fn route_payment(origin_node: &Node, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
737 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();
738 assert_eq!(route.hops.len(), expected_route.len());
739 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
740 assert_eq!(hop.pubkey, node.node.get_our_node_id());
743 send_along_route(origin_node, route, expected_route, recv_value)
746 pub fn route_over_limit(origin_node: &Node, expected_route: &[&Node], recv_value: u64) {
747 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();
748 assert_eq!(route.hops.len(), expected_route.len());
749 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
750 assert_eq!(hop.pubkey, node.node.get_our_node_id());
753 let (_, our_payment_hash) = get_payment_preimage_hash!(origin_node);
755 let err = origin_node.node.send_payment(route, our_payment_hash).err().unwrap();
757 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over the max HTLC value in flight our peer will accept"),
758 _ => panic!("Unknown error variants"),
762 pub fn send_payment(origin: &Node, expected_route: &[&Node], recv_value: u64, expected_value: u64) {
763 let our_payment_preimage = route_payment(&origin, expected_route, recv_value).0;
764 claim_payment(&origin, expected_route, our_payment_preimage, expected_value);
767 pub fn fail_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_hash: PaymentHash) {
768 assert!(expected_route.last().unwrap().node.fail_htlc_backwards(&our_payment_hash));
769 expect_pending_htlcs_forwardable!(expected_route.last().unwrap());
770 check_added_monitors!(expected_route.last().unwrap(), 1);
772 let mut next_msgs: Option<(msgs::UpdateFailHTLC, msgs::CommitmentSigned)> = None;
773 macro_rules! update_fail_dance {
774 ($node: expr, $prev_node: expr, $last_node: expr) => {
776 $node.node.handle_update_fail_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0);
777 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, !$last_node);
778 if skip_last && $last_node {
779 expect_pending_htlcs_forwardable!($node);
785 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
786 let mut prev_node = expected_route.last().unwrap();
787 for (idx, node) in expected_route.iter().rev().enumerate() {
788 assert_eq!(expected_next_node, node.node.get_our_node_id());
789 if next_msgs.is_some() {
790 // We may be the "last node" for the purpose of the commitment dance if we're
791 // skipping the last node (implying it is disconnected) and we're the
792 // second-to-last node!
793 update_fail_dance!(node, prev_node, skip_last && idx == expected_route.len() - 1);
796 let events = node.node.get_and_clear_pending_msg_events();
797 if !skip_last || idx != expected_route.len() - 1 {
798 assert_eq!(events.len(), 1);
800 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 } } => {
801 assert!(update_add_htlcs.is_empty());
802 assert!(update_fulfill_htlcs.is_empty());
803 assert_eq!(update_fail_htlcs.len(), 1);
804 assert!(update_fail_malformed_htlcs.is_empty());
805 assert!(update_fee.is_none());
806 expected_next_node = node_id.clone();
807 next_msgs = Some((update_fail_htlcs[0].clone(), commitment_signed.clone()));
809 _ => panic!("Unexpected event"),
812 assert!(events.is_empty());
814 if !skip_last && idx == expected_route.len() - 1 {
815 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
822 update_fail_dance!(origin_node, expected_route.first().unwrap(), true);
824 let events = origin_node.node.get_and_clear_pending_events();
825 assert_eq!(events.len(), 1);
827 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
828 assert_eq!(payment_hash, our_payment_hash);
829 assert!(rejected_by_dest);
831 _ => panic!("Unexpected event"),
836 pub fn fail_payment(origin_node: &Node, expected_route: &[&Node], our_payment_hash: PaymentHash) {
837 fail_payment_along_route(origin_node, expected_route, false, our_payment_hash);
840 pub fn create_network(node_count: usize, node_config: &[Option<UserConfig>]) -> Vec<Node> {
841 let mut nodes = Vec::new();
842 let mut rng = thread_rng();
843 let secp_ctx = Secp256k1::new();
845 let chan_count = Rc::new(RefCell::new(0));
846 let payment_count = Rc::new(RefCell::new(0));
848 for i in 0..node_count {
849 let test_logger = Arc::new(test_utils::TestLogger::with_id(format!("node {}", i)));
850 let logger = &(Arc::clone(&test_logger) as Arc<Logger>);
851 let feeest = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 });
852 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
853 let block_notifier = Arc::new(chaininterface::BlockNotifier::new(chain_monitor.clone()));
854 let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())});
855 let mut seed = [0; 32];
856 rng.fill_bytes(&mut seed);
857 let keys_manager = Arc::new(test_utils::TestKeysInterface::new(&seed, Network::Testnet, Arc::clone(&logger)));
858 let chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(chain_monitor.clone(), tx_broadcaster.clone(), logger.clone(), feeest.clone()));
859 let weak_res = Arc::downgrade(&chan_monitor.simple_monitor);
860 block_notifier.register_listener(weak_res);
861 let mut default_config = UserConfig::default();
862 default_config.channel_options.announced_channel = true;
863 default_config.peer_channel_config_limits.force_announced_channel_preference = false;
864 let node = ChannelManager::new(Network::Testnet, feeest.clone(), chan_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();
865 let weak_res = Arc::downgrade(&node);
866 block_notifier.register_listener(weak_res);
867 let router = Router::new(PublicKey::from_secret_key(&secp_ctx, &keys_manager.get_node_secret()), chain_monitor.clone(), Arc::clone(&logger));
868 nodes.push(Node { chain_monitor, tx_broadcaster, chan_monitor, node, router, keys_manager, node_seed: seed,
869 network_payment_count: payment_count.clone(),
870 network_chan_count: chan_count.clone(),
880 pub enum HTLCType { NONE, TIMEOUT, SUCCESS }
881 /// Tests that the given node has broadcast transactions for the given Channel
883 /// First checks that the latest local commitment tx has been broadcast, unless an explicit
884 /// commitment_tx is provided, which may be used to test that a remote commitment tx was
885 /// broadcast and the revoked outputs were claimed.
887 /// Next tests that there is (or is not) a transaction that spends the commitment transaction
888 /// that appears to be the type of HTLC transaction specified in has_htlc_tx.
890 /// All broadcast transactions must be accounted for in one of the above three types of we'll
892 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> {
893 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
894 assert!(node_txn.len() >= if commitment_tx.is_some() { 0 } else { 1 } + if has_htlc_tx == HTLCType::NONE { 0 } else { 1 });
896 let mut res = Vec::with_capacity(2);
897 node_txn.retain(|tx| {
898 if tx.input.len() == 1 && tx.input[0].previous_output.txid == chan.3.txid() {
899 check_spends!(tx, chan.3.clone());
900 if commitment_tx.is_none() {
901 res.push(tx.clone());
906 if let Some(explicit_tx) = commitment_tx {
907 res.push(explicit_tx.clone());
910 assert_eq!(res.len(), 1);
912 if has_htlc_tx != HTLCType::NONE {
913 node_txn.retain(|tx| {
914 if tx.input.len() == 1 && tx.input[0].previous_output.txid == res[0].txid() {
915 check_spends!(tx, res[0].clone());
916 if has_htlc_tx == HTLCType::TIMEOUT {
917 assert!(tx.lock_time != 0);
919 assert!(tx.lock_time == 0);
921 res.push(tx.clone());
925 assert!(res.len() == 2 || res.len() == 3);
927 assert_eq!(res[1], res[2]);
931 assert!(node_txn.is_empty());
935 /// Tests that the given node has broadcast a claim transaction against the provided revoked
936 /// HTLC transaction.
937 pub fn test_revoked_htlc_claim_txn_broadcast(node: &Node, revoked_tx: Transaction, commitment_revoked_tx: Transaction) {
938 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
939 // We should issue a 2nd transaction if one htlc is dropped from initial claiming tx
940 // but sometimes not as feerate is too-low
941 if node_txn.len() != 1 && node_txn.len() != 2 { assert!(false); }
942 node_txn.retain(|tx| {
943 if tx.input.len() == 1 && tx.input[0].previous_output.txid == revoked_tx.txid() {
944 check_spends!(tx, revoked_tx);
948 node_txn.retain(|tx| {
949 check_spends!(tx, commitment_revoked_tx);
952 assert!(node_txn.is_empty());
955 pub fn check_preimage_claim(node: &Node, prev_txn: &Vec<Transaction>) -> Vec<Transaction> {
956 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
958 assert!(node_txn.len() >= 1);
959 assert_eq!(node_txn[0].input.len(), 1);
960 let mut found_prev = false;
963 if node_txn[0].input[0].previous_output.txid == tx.txid() {
964 check_spends!(node_txn[0], tx.clone());
965 assert!(node_txn[0].input[0].witness[2].len() > 106); // must spend an htlc output
966 assert_eq!(tx.input.len(), 1); // must spend a commitment tx
974 let mut res = Vec::new();
975 mem::swap(&mut *node_txn, &mut res);
979 pub fn get_announce_close_broadcast_events(nodes: &Vec<Node>, a: usize, b: usize) {
980 let events_1 = nodes[a].node.get_and_clear_pending_msg_events();
981 assert_eq!(events_1.len(), 1);
982 let as_update = match events_1[0] {
983 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
986 _ => panic!("Unexpected event"),
989 let events_2 = nodes[b].node.get_and_clear_pending_msg_events();
990 assert_eq!(events_2.len(), 1);
991 let bs_update = match events_2[0] {
992 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
995 _ => panic!("Unexpected event"),
999 node.router.handle_channel_update(&as_update).unwrap();
1000 node.router.handle_channel_update(&bs_update).unwrap();
1004 macro_rules! get_channel_value_stat {
1005 ($node: expr, $channel_id: expr) => {{
1006 let chan_lock = $node.node.channel_state.lock().unwrap();
1007 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
1008 chan.get_value_stat()
1012 macro_rules! get_chan_reestablish_msgs {
1013 ($src_node: expr, $dst_node: expr) => {
1015 let mut res = Vec::with_capacity(1);
1016 for msg in $src_node.node.get_and_clear_pending_msg_events() {
1017 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
1018 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
1019 res.push(msg.clone());
1021 panic!("Unexpected event")
1029 macro_rules! handle_chan_reestablish_msgs {
1030 ($src_node: expr, $dst_node: expr) => {
1032 let msg_events = $src_node.node.get_and_clear_pending_msg_events();
1034 let funding_locked = if let Some(&MessageSendEvent::SendFundingLocked { ref node_id, ref msg }) = msg_events.get(0) {
1036 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
1042 let mut revoke_and_ack = None;
1043 let mut commitment_update = None;
1044 let order = if let Some(ev) = msg_events.get(idx) {
1047 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
1048 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
1049 revoke_and_ack = Some(msg.clone());
1050 RAACommitmentOrder::RevokeAndACKFirst
1052 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
1053 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
1054 commitment_update = Some(updates.clone());
1055 RAACommitmentOrder::CommitmentFirst
1057 _ => panic!("Unexpected event"),
1060 RAACommitmentOrder::CommitmentFirst
1063 if let Some(ev) = msg_events.get(idx) {
1065 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
1066 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
1067 assert!(revoke_and_ack.is_none());
1068 revoke_and_ack = Some(msg.clone());
1070 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
1071 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
1072 assert!(commitment_update.is_none());
1073 commitment_update = Some(updates.clone());
1075 _ => panic!("Unexpected event"),
1079 (funding_locked, revoke_and_ack, commitment_update, order)
1084 /// pending_htlc_adds includes both the holding cell and in-flight update_add_htlcs, whereas
1085 /// for claims/fails they are separated out.
1086 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)) {
1087 node_a.node.peer_connected(&node_b.node.get_our_node_id());
1088 let reestablish_1 = get_chan_reestablish_msgs!(node_a, node_b);
1089 node_b.node.peer_connected(&node_a.node.get_our_node_id());
1090 let reestablish_2 = get_chan_reestablish_msgs!(node_b, node_a);
1092 if send_funding_locked.0 {
1093 // If a expects a funding_locked, it better not think it has received a revoke_and_ack
1095 for reestablish in reestablish_1.iter() {
1096 assert_eq!(reestablish.next_remote_commitment_number, 0);
1099 if send_funding_locked.1 {
1100 // If b expects a funding_locked, it better not think it has received a revoke_and_ack
1102 for reestablish in reestablish_2.iter() {
1103 assert_eq!(reestablish.next_remote_commitment_number, 0);
1106 if send_funding_locked.0 || send_funding_locked.1 {
1107 // If we expect any funding_locked's, both sides better have set
1108 // next_local_commitment_number to 1
1109 for reestablish in reestablish_1.iter() {
1110 assert_eq!(reestablish.next_local_commitment_number, 1);
1112 for reestablish in reestablish_2.iter() {
1113 assert_eq!(reestablish.next_local_commitment_number, 1);
1117 let mut resp_1 = Vec::new();
1118 for msg in reestablish_1 {
1119 node_b.node.handle_channel_reestablish(&node_a.node.get_our_node_id(), &msg);
1120 resp_1.push(handle_chan_reestablish_msgs!(node_b, node_a));
1122 if pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
1123 check_added_monitors!(node_b, 1);
1125 check_added_monitors!(node_b, 0);
1128 let mut resp_2 = Vec::new();
1129 for msg in reestablish_2 {
1130 node_a.node.handle_channel_reestablish(&node_b.node.get_our_node_id(), &msg);
1131 resp_2.push(handle_chan_reestablish_msgs!(node_a, node_b));
1133 if pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
1134 check_added_monitors!(node_a, 1);
1136 check_added_monitors!(node_a, 0);
1139 // We don't yet support both needing updates, as that would require a different commitment dance:
1140 assert!((pending_htlc_adds.0 == 0 && pending_htlc_claims.0 == 0 && pending_cell_htlc_claims.0 == 0 && pending_cell_htlc_fails.0 == 0) ||
1141 (pending_htlc_adds.1 == 0 && pending_htlc_claims.1 == 0 && pending_cell_htlc_claims.1 == 0 && pending_cell_htlc_fails.1 == 0));
1143 for chan_msgs in resp_1.drain(..) {
1144 if send_funding_locked.0 {
1145 node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), &chan_msgs.0.unwrap());
1146 let announcement_event = node_a.node.get_and_clear_pending_msg_events();
1147 if !announcement_event.is_empty() {
1148 assert_eq!(announcement_event.len(), 1);
1149 if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
1150 //TODO: Test announcement_sigs re-sending
1151 } else { panic!("Unexpected event!"); }
1154 assert!(chan_msgs.0.is_none());
1157 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
1158 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap());
1159 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
1160 check_added_monitors!(node_a, 1);
1162 assert!(chan_msgs.1.is_none());
1164 if pending_htlc_adds.0 != 0 || pending_htlc_claims.0 != 0 || pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
1165 let commitment_update = chan_msgs.2.unwrap();
1166 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
1167 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.0 as usize);
1169 assert!(commitment_update.update_add_htlcs.is_empty());
1171 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
1172 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
1173 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
1174 for update_add in commitment_update.update_add_htlcs {
1175 node_a.node.handle_update_add_htlc(&node_b.node.get_our_node_id(), &update_add);
1177 for update_fulfill in commitment_update.update_fulfill_htlcs {
1178 node_a.node.handle_update_fulfill_htlc(&node_b.node.get_our_node_id(), &update_fulfill);
1180 for update_fail in commitment_update.update_fail_htlcs {
1181 node_a.node.handle_update_fail_htlc(&node_b.node.get_our_node_id(), &update_fail);
1184 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
1185 commitment_signed_dance!(node_a, node_b, commitment_update.commitment_signed, false);
1187 node_a.node.handle_commitment_signed(&node_b.node.get_our_node_id(), &commitment_update.commitment_signed);
1188 check_added_monitors!(node_a, 1);
1189 let as_revoke_and_ack = get_event_msg!(node_a, MessageSendEvent::SendRevokeAndACK, node_b.node.get_our_node_id());
1190 // No commitment_signed so get_event_msg's assert(len == 1) passes
1191 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &as_revoke_and_ack);
1192 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
1193 check_added_monitors!(node_b, 1);
1196 assert!(chan_msgs.2.is_none());
1200 for chan_msgs in resp_2.drain(..) {
1201 if send_funding_locked.1 {
1202 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &chan_msgs.0.unwrap());
1203 let announcement_event = node_b.node.get_and_clear_pending_msg_events();
1204 if !announcement_event.is_empty() {
1205 assert_eq!(announcement_event.len(), 1);
1206 if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
1207 //TODO: Test announcement_sigs re-sending
1208 } else { panic!("Unexpected event!"); }
1211 assert!(chan_msgs.0.is_none());
1214 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
1215 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap());
1216 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
1217 check_added_monitors!(node_b, 1);
1219 assert!(chan_msgs.1.is_none());
1221 if pending_htlc_adds.1 != 0 || pending_htlc_claims.1 != 0 || pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
1222 let commitment_update = chan_msgs.2.unwrap();
1223 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
1224 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.1 as usize);
1226 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
1227 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
1228 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
1229 for update_add in commitment_update.update_add_htlcs {
1230 node_b.node.handle_update_add_htlc(&node_a.node.get_our_node_id(), &update_add);
1232 for update_fulfill in commitment_update.update_fulfill_htlcs {
1233 node_b.node.handle_update_fulfill_htlc(&node_a.node.get_our_node_id(), &update_fulfill);
1235 for update_fail in commitment_update.update_fail_htlcs {
1236 node_b.node.handle_update_fail_htlc(&node_a.node.get_our_node_id(), &update_fail);
1239 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
1240 commitment_signed_dance!(node_b, node_a, commitment_update.commitment_signed, false);
1242 node_b.node.handle_commitment_signed(&node_a.node.get_our_node_id(), &commitment_update.commitment_signed);
1243 check_added_monitors!(node_b, 1);
1244 let bs_revoke_and_ack = get_event_msg!(node_b, MessageSendEvent::SendRevokeAndACK, node_a.node.get_our_node_id());
1245 // No commitment_signed so get_event_msg's assert(len == 1) passes
1246 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &bs_revoke_and_ack);
1247 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
1248 check_added_monitors!(node_a, 1);
1251 assert!(chan_msgs.2.is_none());