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(notifier: &chaininterface::BlockNotifier, 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 notifier.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 notifier.block_connected_checked(&header, i, &vec![], &[0; 0]);
47 pub fn connect_blocks(notifier: &chaininterface::BlockNotifier, 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 notifier.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 notifier.block_connected_checked(&header, height + i, &Vec::new(), &Vec::new());
57 pub struct Node<'a, 'b: 'a> {
58 pub block_notifier: Arc<chaininterface::BlockNotifier<'a>>,
59 pub chain_monitor: Arc<chaininterface::ChainWatchInterfaceUtil>,
60 pub tx_broadcaster: Arc<test_utils::TestBroadcaster>,
61 pub chan_monitor: Arc<test_utils::TestChannelMonitor>,
62 pub keys_manager: Arc<test_utils::TestKeysInterface>,
63 pub node: Arc<ChannelManager<'b>>,
65 pub node_seed: [u8; 32],
66 pub network_payment_count: Rc<RefCell<u8>>,
67 pub network_chan_count: Rc<RefCell<u32>>,
69 impl<'a, 'b> Drop for Node<'a, 'b> {
71 if !::std::thread::panicking() {
72 // Check that we processed all pending events
73 assert!(self.node.get_and_clear_pending_msg_events().is_empty());
74 assert!(self.node.get_and_clear_pending_events().is_empty());
75 assert!(self.chan_monitor.added_monitors.lock().unwrap().is_empty());
80 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) {
81 create_chan_between_nodes_with_value(node_a, node_b, 100000, 10001, a_flags, b_flags)
84 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) {
85 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);
86 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(node_a, node_b, &funding_locked);
87 (announcement, as_update, bs_update, channel_id, tx)
90 macro_rules! get_revoke_commit_msgs {
91 ($node: expr, $node_id: expr) => {
93 let events = $node.node.get_and_clear_pending_msg_events();
94 assert_eq!(events.len(), 2);
96 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
97 assert_eq!(*node_id, $node_id);
100 _ => panic!("Unexpected event"),
102 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
103 assert_eq!(*node_id, $node_id);
104 assert!(updates.update_add_htlcs.is_empty());
105 assert!(updates.update_fulfill_htlcs.is_empty());
106 assert!(updates.update_fail_htlcs.is_empty());
107 assert!(updates.update_fail_malformed_htlcs.is_empty());
108 assert!(updates.update_fee.is_none());
109 updates.commitment_signed.clone()
111 _ => panic!("Unexpected event"),
117 macro_rules! get_event_msg {
118 ($node: expr, $event_type: path, $node_id: expr) => {
120 let events = $node.node.get_and_clear_pending_msg_events();
121 assert_eq!(events.len(), 1);
123 $event_type { ref node_id, ref msg } => {
124 assert_eq!(*node_id, $node_id);
127 _ => panic!("Unexpected event"),
133 macro_rules! get_htlc_update_msgs {
134 ($node: expr, $node_id: expr) => {
136 let events = $node.node.get_and_clear_pending_msg_events();
137 assert_eq!(events.len(), 1);
139 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
140 assert_eq!(*node_id, $node_id);
143 _ => panic!("Unexpected event"),
149 macro_rules! get_feerate {
150 ($node: expr, $channel_id: expr) => {
152 let chan_lock = $node.node.channel_state.lock().unwrap();
153 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
159 pub fn create_funding_transaction(node: &Node, expected_chan_value: u64, expected_user_chan_id: u64) -> ([u8; 32], Transaction, OutPoint) {
160 let chan_id = *node.network_chan_count.borrow();
162 let events = node.node.get_and_clear_pending_events();
163 assert_eq!(events.len(), 1);
165 Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
166 assert_eq!(*channel_value_satoshis, expected_chan_value);
167 assert_eq!(user_channel_id, expected_user_chan_id);
169 let tx = Transaction { version: chan_id as u32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
170 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
172 let funding_outpoint = OutPoint::new(tx.txid(), 0);
173 (*temporary_channel_id, tx, funding_outpoint)
175 _ => panic!("Unexpected event"),
179 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 {
180 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42).unwrap();
181 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();
182 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();
184 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(node_a, channel_value, 42);
187 node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
188 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
189 assert_eq!(added_monitors.len(), 1);
190 assert_eq!(added_monitors[0].0, funding_output);
191 added_monitors.clear();
194 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();
196 let mut added_monitors = node_b.chan_monitor.added_monitors.lock().unwrap();
197 assert_eq!(added_monitors.len(), 1);
198 assert_eq!(added_monitors[0].0, funding_output);
199 added_monitors.clear();
202 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();
204 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
205 assert_eq!(added_monitors.len(), 1);
206 assert_eq!(added_monitors[0].0, funding_output);
207 added_monitors.clear();
210 let events_4 = node_a.node.get_and_clear_pending_events();
211 assert_eq!(events_4.len(), 1);
213 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
214 assert_eq!(user_channel_id, 42);
215 assert_eq!(*funding_txo, funding_output);
217 _ => panic!("Unexpected event"),
223 pub fn create_chan_between_nodes_with_value_confirm_first(node_recv: &Node, node_conf: &Node, tx: &Transaction) {
224 confirm_transaction(&node_conf.block_notifier, &node_conf.chain_monitor, &tx, tx.version);
225 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();
228 pub fn create_chan_between_nodes_with_value_confirm_second(node_recv: &Node, node_conf: &Node) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32]) {
230 let events_6 = node_conf.node.get_and_clear_pending_msg_events();
231 assert_eq!(events_6.len(), 2);
232 ((match events_6[0] {
233 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
234 channel_id = msg.channel_id.clone();
235 assert_eq!(*node_id, node_recv.node.get_our_node_id());
238 _ => panic!("Unexpected event"),
239 }, match events_6[1] {
240 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
241 assert_eq!(*node_id, node_recv.node.get_our_node_id());
244 _ => panic!("Unexpected event"),
248 pub fn create_chan_between_nodes_with_value_confirm(node_a: &Node, node_b: &Node, tx: &Transaction) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32]) {
249 create_chan_between_nodes_with_value_confirm_first(node_a, node_b, tx);
250 confirm_transaction(&node_a.block_notifier, &node_a.chain_monitor, &tx, tx.version);
251 create_chan_between_nodes_with_value_confirm_second(node_b, node_a)
254 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) {
255 let tx = create_chan_between_nodes_with_value_init(node_a, node_b, channel_value, push_msat, a_flags, b_flags);
256 let (msgs, chan_id) = create_chan_between_nodes_with_value_confirm(node_a, node_b, &tx);
260 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) {
261 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &as_funding_msgs.0).unwrap();
262 let bs_announcement_sigs = get_event_msg!(node_b, MessageSendEvent::SendAnnouncementSignatures, node_a.node.get_our_node_id());
263 node_b.node.handle_announcement_signatures(&node_a.node.get_our_node_id(), &as_funding_msgs.1).unwrap();
265 let events_7 = node_b.node.get_and_clear_pending_msg_events();
266 assert_eq!(events_7.len(), 1);
267 let (announcement, bs_update) = match events_7[0] {
268 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
271 _ => panic!("Unexpected event"),
274 node_a.node.handle_announcement_signatures(&node_b.node.get_our_node_id(), &bs_announcement_sigs).unwrap();
275 let events_8 = node_a.node.get_and_clear_pending_msg_events();
276 assert_eq!(events_8.len(), 1);
277 let as_update = match events_8[0] {
278 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
279 assert!(*announcement == *msg);
280 assert_eq!(update_msg.contents.short_channel_id, announcement.contents.short_channel_id);
281 assert_eq!(update_msg.contents.short_channel_id, bs_update.contents.short_channel_id);
284 _ => panic!("Unexpected event"),
287 *node_a.network_chan_count.borrow_mut() += 1;
289 ((*announcement).clone(), (*as_update).clone(), (*bs_update).clone())
292 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) {
293 create_announced_chan_between_nodes_with_value(nodes, a, b, 100000, 10001, a_flags, b_flags)
296 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) {
297 let chan_announcement = create_chan_between_nodes_with_value(&nodes[a], &nodes[b], channel_value, push_msat, a_flags, b_flags);
299 assert!(node.router.handle_channel_announcement(&chan_announcement.0).unwrap());
300 node.router.handle_channel_update(&chan_announcement.1).unwrap();
301 node.router.handle_channel_update(&chan_announcement.2).unwrap();
303 (chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
306 macro_rules! check_spends {
307 ($tx: expr, $spends_tx: expr) => {
309 $tx.verify(|out_point| {
310 if out_point.txid == $spends_tx.txid() {
311 $spends_tx.output.get(out_point.vout as usize).cloned()
320 macro_rules! get_closing_signed_broadcast {
321 ($node: expr, $dest_pubkey: expr) => {
323 let events = $node.get_and_clear_pending_msg_events();
324 assert!(events.len() == 1 || events.len() == 2);
325 (match events[events.len() - 1] {
326 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
327 assert_eq!(msg.contents.flags & 2, 2);
330 _ => panic!("Unexpected event"),
331 }, if events.len() == 2 {
333 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
334 assert_eq!(*node_id, $dest_pubkey);
337 _ => panic!("Unexpected event"),
344 macro_rules! check_closed_broadcast {
346 let events = $node.node.get_and_clear_pending_msg_events();
347 assert_eq!(events.len(), 1);
349 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
350 assert_eq!(msg.contents.flags & 2, 2);
352 _ => panic!("Unexpected event"),
357 pub fn close_channel<'a, 'b>(outbound_node: &Node<'a, 'b>, inbound_node: &Node<'a, 'b>, channel_id: &[u8; 32], funding_tx: Transaction, close_inbound_first: bool) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, Transaction) {
358 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) };
359 let (node_b, broadcaster_b) = if close_inbound_first { (&outbound_node.node, &outbound_node.tx_broadcaster) } else { (&inbound_node.node, &inbound_node.tx_broadcaster) };
362 node_a.close_channel(channel_id).unwrap();
363 node_b.handle_shutdown(&node_a.get_our_node_id(), &get_event_msg!(struct_a, MessageSendEvent::SendShutdown, node_b.get_our_node_id())).unwrap();
365 let events_1 = node_b.get_and_clear_pending_msg_events();
366 assert!(events_1.len() >= 1);
367 let shutdown_b = match events_1[0] {
368 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
369 assert_eq!(node_id, &node_a.get_our_node_id());
372 _ => panic!("Unexpected event"),
375 let closing_signed_b = if !close_inbound_first {
376 assert_eq!(events_1.len(), 1);
379 Some(match events_1[1] {
380 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
381 assert_eq!(node_id, &node_a.get_our_node_id());
384 _ => panic!("Unexpected event"),
388 node_a.handle_shutdown(&node_b.get_our_node_id(), &shutdown_b).unwrap();
389 let (as_update, bs_update) = if close_inbound_first {
390 assert!(node_a.get_and_clear_pending_msg_events().is_empty());
391 node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
392 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
393 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
394 let (as_update, closing_signed_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
396 node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap()).unwrap();
397 let (bs_update, none_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
398 assert!(none_b.is_none());
399 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
400 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
401 (as_update, bs_update)
403 let closing_signed_a = get_event_msg!(struct_a, MessageSendEvent::SendClosingSigned, node_b.get_our_node_id());
405 node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a).unwrap();
406 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
407 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
408 let (bs_update, closing_signed_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
410 node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
411 let (as_update, none_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
412 assert!(none_a.is_none());
413 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
414 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
415 (as_update, bs_update)
417 assert_eq!(tx_a, tx_b);
418 check_spends!(tx_a, funding_tx);
420 (as_update, bs_update, tx_a)
423 pub struct SendEvent {
424 pub node_id: PublicKey,
425 pub msgs: Vec<msgs::UpdateAddHTLC>,
426 pub commitment_msg: msgs::CommitmentSigned,
429 pub fn from_commitment_update(node_id: PublicKey, updates: msgs::CommitmentUpdate) -> SendEvent {
430 assert!(updates.update_fulfill_htlcs.is_empty());
431 assert!(updates.update_fail_htlcs.is_empty());
432 assert!(updates.update_fail_malformed_htlcs.is_empty());
433 assert!(updates.update_fee.is_none());
434 SendEvent { node_id: node_id, msgs: updates.update_add_htlcs, commitment_msg: updates.commitment_signed }
437 pub fn from_event(event: MessageSendEvent) -> SendEvent {
439 MessageSendEvent::UpdateHTLCs { node_id, updates } => SendEvent::from_commitment_update(node_id, updates),
440 _ => panic!("Unexpected event type!"),
444 pub fn from_node(node: &Node) -> SendEvent {
445 let mut events = node.node.get_and_clear_pending_msg_events();
446 assert_eq!(events.len(), 1);
447 SendEvent::from_event(events.pop().unwrap())
451 macro_rules! check_added_monitors {
452 ($node: expr, $count: expr) => {
454 let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
455 assert_eq!(added_monitors.len(), $count);
456 added_monitors.clear();
461 macro_rules! commitment_signed_dance {
462 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */) => {
464 check_added_monitors!($node_a, 0);
465 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
466 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
467 check_added_monitors!($node_a, 1);
468 commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, false);
471 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */, true /* return last RAA */) => {
473 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!($node_a, $node_b.node.get_our_node_id());
474 check_added_monitors!($node_b, 0);
475 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
476 $node_b.node.handle_revoke_and_ack(&$node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
477 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
478 check_added_monitors!($node_b, 1);
479 $node_b.node.handle_commitment_signed(&$node_a.node.get_our_node_id(), &as_commitment_signed).unwrap();
480 let (bs_revoke_and_ack, extra_msg_option) = {
481 let events = $node_b.node.get_and_clear_pending_msg_events();
482 assert!(events.len() <= 2);
484 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
485 assert_eq!(*node_id, $node_a.node.get_our_node_id());
488 _ => panic!("Unexpected event"),
489 }, events.get(1).map(|e| e.clone()))
491 check_added_monitors!($node_b, 1);
493 assert!($node_a.node.get_and_clear_pending_events().is_empty());
494 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
496 (extra_msg_option, bs_revoke_and_ack)
499 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */, false /* return extra message */, true /* return last RAA */) => {
501 check_added_monitors!($node_a, 0);
502 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
503 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
504 check_added_monitors!($node_a, 1);
505 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
506 assert!(extra_msg_option.is_none());
510 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */) => {
512 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
513 $node_a.node.handle_revoke_and_ack(&$node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
514 check_added_monitors!($node_a, 1);
518 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, false /* no extra message */) => {
520 assert!(commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true).is_none());
523 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr) => {
525 commitment_signed_dance!($node_a, $node_b, $commitment_signed, $fail_backwards, true);
527 expect_pending_htlcs_forwardable!($node_a);
528 check_added_monitors!($node_a, 1);
530 let channel_state = $node_a.node.channel_state.lock().unwrap();
531 assert_eq!(channel_state.pending_msg_events.len(), 1);
532 if let MessageSendEvent::UpdateHTLCs { ref node_id, .. } = channel_state.pending_msg_events[0] {
533 assert_ne!(*node_id, $node_b.node.get_our_node_id());
534 } else { panic!("Unexpected event"); }
536 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
542 macro_rules! get_payment_preimage_hash {
545 let payment_preimage = PaymentPreimage([*$node.network_payment_count.borrow(); 32]);
546 *$node.network_payment_count.borrow_mut() += 1;
547 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner());
548 (payment_preimage, payment_hash)
553 macro_rules! expect_pending_htlcs_forwardable {
555 let events = $node.node.get_and_clear_pending_events();
556 assert_eq!(events.len(), 1);
558 Event::PendingHTLCsForwardable { .. } => { },
559 _ => panic!("Unexpected event"),
561 $node.node.process_pending_htlc_forwards();
565 macro_rules! expect_payment_received {
566 ($node: expr, $expected_payment_hash: expr, $expected_recv_value: expr) => {
567 let events = $node.node.get_and_clear_pending_events();
568 assert_eq!(events.len(), 1);
570 Event::PaymentReceived { ref payment_hash, amt } => {
571 assert_eq!($expected_payment_hash, *payment_hash);
572 assert_eq!($expected_recv_value, amt);
574 _ => panic!("Unexpected event"),
579 macro_rules! expect_payment_sent {
580 ($node: expr, $expected_payment_preimage: expr) => {
581 let events = $node.node.get_and_clear_pending_events();
582 assert_eq!(events.len(), 1);
584 Event::PaymentSent { ref payment_preimage } => {
585 assert_eq!($expected_payment_preimage, *payment_preimage);
587 _ => panic!("Unexpected event"),
592 pub fn send_along_route_with_hash<'a, 'b>(origin_node: &Node<'a, 'b>, route: Route, expected_route: &[&Node<'a, 'b>], recv_value: u64, our_payment_hash: PaymentHash) {
593 let mut payment_event = {
594 origin_node.node.send_payment(route, our_payment_hash).unwrap();
595 check_added_monitors!(origin_node, 1);
597 let mut events = origin_node.node.get_and_clear_pending_msg_events();
598 assert_eq!(events.len(), 1);
599 SendEvent::from_event(events.remove(0))
601 let mut prev_node = origin_node;
603 for (idx, &node) in expected_route.iter().enumerate() {
604 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
606 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
607 check_added_monitors!(node, 0);
608 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
610 expect_pending_htlcs_forwardable!(node);
612 if idx == expected_route.len() - 1 {
613 let events_2 = node.node.get_and_clear_pending_events();
614 assert_eq!(events_2.len(), 1);
616 Event::PaymentReceived { ref payment_hash, amt } => {
617 assert_eq!(our_payment_hash, *payment_hash);
618 assert_eq!(amt, recv_value);
620 _ => panic!("Unexpected event"),
623 let mut events_2 = node.node.get_and_clear_pending_msg_events();
624 assert_eq!(events_2.len(), 1);
625 check_added_monitors!(node, 1);
626 payment_event = SendEvent::from_event(events_2.remove(0));
627 assert_eq!(payment_event.msgs.len(), 1);
634 pub fn send_along_route<'a, 'b>(origin_node: &Node<'a, 'b>, route: Route, expected_route: &[&Node<'a, 'b>], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
635 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(origin_node);
636 send_along_route_with_hash(origin_node, route, expected_route, recv_value, our_payment_hash);
637 (our_payment_preimage, our_payment_hash)
640 pub fn claim_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_preimage: PaymentPreimage, expected_amount: u64) {
641 assert!(expected_route.last().unwrap().node.claim_funds(our_payment_preimage, expected_amount));
642 check_added_monitors!(expected_route.last().unwrap(), 1);
644 let mut next_msgs: Option<(msgs::UpdateFulfillHTLC, msgs::CommitmentSigned)> = None;
645 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
646 macro_rules! get_next_msgs {
649 let events = $node.node.get_and_clear_pending_msg_events();
650 assert_eq!(events.len(), 1);
652 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 } } => {
653 assert!(update_add_htlcs.is_empty());
654 assert_eq!(update_fulfill_htlcs.len(), 1);
655 assert!(update_fail_htlcs.is_empty());
656 assert!(update_fail_malformed_htlcs.is_empty());
657 assert!(update_fee.is_none());
658 expected_next_node = node_id.clone();
659 Some((update_fulfill_htlcs[0].clone(), commitment_signed.clone()))
661 _ => panic!("Unexpected event"),
667 macro_rules! last_update_fulfill_dance {
668 ($node: expr, $prev_node: expr) => {
670 $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
671 check_added_monitors!($node, 0);
672 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
673 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
677 macro_rules! mid_update_fulfill_dance {
678 ($node: expr, $prev_node: expr, $new_msgs: expr) => {
680 $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
681 check_added_monitors!($node, 1);
682 let new_next_msgs = if $new_msgs {
683 get_next_msgs!($node)
685 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
688 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
689 next_msgs = new_next_msgs;
694 let mut prev_node = expected_route.last().unwrap();
695 for (idx, node) in expected_route.iter().rev().enumerate() {
696 assert_eq!(expected_next_node, node.node.get_our_node_id());
697 let update_next_msgs = !skip_last || idx != expected_route.len() - 1;
698 if next_msgs.is_some() {
699 mid_update_fulfill_dance!(node, prev_node, update_next_msgs);
700 } else if update_next_msgs {
701 next_msgs = get_next_msgs!(node);
703 assert!(node.node.get_and_clear_pending_msg_events().is_empty());
705 if !skip_last && idx == expected_route.len() - 1 {
706 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
713 last_update_fulfill_dance!(origin_node, expected_route.first().unwrap());
714 expect_payment_sent!(origin_node, our_payment_preimage);
718 pub fn claim_payment(origin_node: &Node, expected_route: &[&Node], our_payment_preimage: PaymentPreimage, expected_amount: u64) {
719 claim_payment_along_route(origin_node, expected_route, false, our_payment_preimage, expected_amount);
722 pub const TEST_FINAL_CLTV: u32 = 32;
724 pub fn route_payment<'a, 'b>(origin_node: &Node<'a, 'b>, expected_route: &[&Node<'a, 'b>], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
725 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();
726 assert_eq!(route.hops.len(), expected_route.len());
727 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
728 assert_eq!(hop.pubkey, node.node.get_our_node_id());
731 send_along_route(origin_node, route, expected_route, recv_value)
734 pub fn route_over_limit(origin_node: &Node, expected_route: &[&Node], recv_value: u64) {
735 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();
736 assert_eq!(route.hops.len(), expected_route.len());
737 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
738 assert_eq!(hop.pubkey, node.node.get_our_node_id());
741 let (_, our_payment_hash) = get_payment_preimage_hash!(origin_node);
743 let err = origin_node.node.send_payment(route, our_payment_hash).err().unwrap();
745 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over the max HTLC value in flight our peer will accept"),
746 _ => panic!("Unknown error variants"),
750 pub fn send_payment<'a, 'b>(origin: &Node<'a, 'b>, expected_route: &[&Node<'a, 'b>], recv_value: u64, expected_value: u64) {
751 let our_payment_preimage = route_payment(&origin, expected_route, recv_value).0;
752 claim_payment(&origin, expected_route, our_payment_preimage, expected_value);
755 pub fn fail_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_hash: PaymentHash) {
756 assert!(expected_route.last().unwrap().node.fail_htlc_backwards(&our_payment_hash));
757 expect_pending_htlcs_forwardable!(expected_route.last().unwrap());
758 check_added_monitors!(expected_route.last().unwrap(), 1);
760 let mut next_msgs: Option<(msgs::UpdateFailHTLC, msgs::CommitmentSigned)> = None;
761 macro_rules! update_fail_dance {
762 ($node: expr, $prev_node: expr, $last_node: expr) => {
764 $node.node.handle_update_fail_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
765 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, !$last_node);
766 if skip_last && $last_node {
767 expect_pending_htlcs_forwardable!($node);
773 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
774 let mut prev_node = expected_route.last().unwrap();
775 for (idx, node) in expected_route.iter().rev().enumerate() {
776 assert_eq!(expected_next_node, node.node.get_our_node_id());
777 if next_msgs.is_some() {
778 // We may be the "last node" for the purpose of the commitment dance if we're
779 // skipping the last node (implying it is disconnected) and we're the
780 // second-to-last node!
781 update_fail_dance!(node, prev_node, skip_last && idx == expected_route.len() - 1);
784 let events = node.node.get_and_clear_pending_msg_events();
785 if !skip_last || idx != expected_route.len() - 1 {
786 assert_eq!(events.len(), 1);
788 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 } } => {
789 assert!(update_add_htlcs.is_empty());
790 assert!(update_fulfill_htlcs.is_empty());
791 assert_eq!(update_fail_htlcs.len(), 1);
792 assert!(update_fail_malformed_htlcs.is_empty());
793 assert!(update_fee.is_none());
794 expected_next_node = node_id.clone();
795 next_msgs = Some((update_fail_htlcs[0].clone(), commitment_signed.clone()));
797 _ => panic!("Unexpected event"),
800 assert!(events.is_empty());
802 if !skip_last && idx == expected_route.len() - 1 {
803 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
810 update_fail_dance!(origin_node, expected_route.first().unwrap(), true);
812 let events = origin_node.node.get_and_clear_pending_events();
813 assert_eq!(events.len(), 1);
815 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
816 assert_eq!(payment_hash, our_payment_hash);
817 assert!(rejected_by_dest);
819 _ => panic!("Unexpected event"),
824 pub fn fail_payment(origin_node: &Node, expected_route: &[&Node], our_payment_hash: PaymentHash) {
825 fail_payment_along_route(origin_node, expected_route, false, our_payment_hash);
828 pub fn create_network(node_count: usize, node_config: &[Option<UserConfig>]) -> Vec<Node> {
829 let mut nodes = Vec::new();
830 let mut rng = thread_rng();
831 let secp_ctx = Secp256k1::new();
833 let chan_count = Rc::new(RefCell::new(0));
834 let payment_count = Rc::new(RefCell::new(0));
836 for i in 0..node_count {
837 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::with_id(format!("node {}", i)));
838 let feeest = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 });
839 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
840 let block_notifier = Arc::new(chaininterface::BlockNotifier::new(chain_monitor.clone()));
841 let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())});
842 let mut seed = [0; 32];
843 rng.fill_bytes(&mut seed);
844 let keys_manager = Arc::new(test_utils::TestKeysInterface::new(&seed, Network::Testnet, Arc::clone(&logger)));
845 let chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(chain_monitor.clone(), tx_broadcaster.clone(), logger.clone(), feeest.clone()));
846 let weak_res = Arc::downgrade(&chan_monitor.simple_monitor);
847 block_notifier.register_listener(weak_res);
848 let mut default_config = UserConfig::new();
849 default_config.channel_options.announced_channel = true;
850 default_config.peer_channel_config_limits.force_announced_channel_preference = false;
851 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();
852 let weak_res = Arc::downgrade(&node);
853 block_notifier.register_listener(weak_res);
854 let router = Router::new(PublicKey::from_secret_key(&secp_ctx, &keys_manager.get_node_secret()), chain_monitor.clone(), Arc::clone(&logger));
855 nodes.push(Node { chain_monitor, tx_broadcaster, chan_monitor, node, router, keys_manager, node_seed: seed,
856 network_payment_count: payment_count.clone(),
857 network_chan_count: chan_count.clone(),
866 pub enum HTLCType { NONE, TIMEOUT, SUCCESS }
867 /// Tests that the given node has broadcast transactions for the given Channel
869 /// First checks that the latest local commitment tx has been broadcast, unless an explicit
870 /// commitment_tx is provided, which may be used to test that a remote commitment tx was
871 /// broadcast and the revoked outputs were claimed.
873 /// Next tests that there is (or is not) a transaction that spends the commitment transaction
874 /// that appears to be the type of HTLC transaction specified in has_htlc_tx.
876 /// All broadcast transactions must be accounted for in one of the above three types of we'll
878 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> {
879 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
880 assert!(node_txn.len() >= if commitment_tx.is_some() { 0 } else { 1 } + if has_htlc_tx == HTLCType::NONE { 0 } else { 1 });
882 let mut res = Vec::with_capacity(2);
883 node_txn.retain(|tx| {
884 if tx.input.len() == 1 && tx.input[0].previous_output.txid == chan.3.txid() {
885 check_spends!(tx, chan.3.clone());
886 if commitment_tx.is_none() {
887 res.push(tx.clone());
892 if let Some(explicit_tx) = commitment_tx {
893 res.push(explicit_tx.clone());
896 assert_eq!(res.len(), 1);
898 if has_htlc_tx != HTLCType::NONE {
899 node_txn.retain(|tx| {
900 if tx.input.len() == 1 && tx.input[0].previous_output.txid == res[0].txid() {
901 check_spends!(tx, res[0].clone());
902 if has_htlc_tx == HTLCType::TIMEOUT {
903 assert!(tx.lock_time != 0);
905 assert!(tx.lock_time == 0);
907 res.push(tx.clone());
911 assert!(res.len() == 2 || res.len() == 3);
913 assert_eq!(res[1], res[2]);
917 assert!(node_txn.is_empty());
921 /// Tests that the given node has broadcast a claim transaction against the provided revoked
922 /// HTLC transaction.
923 pub fn test_revoked_htlc_claim_txn_broadcast(node: &Node, revoked_tx: Transaction) {
924 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
925 assert_eq!(node_txn.len(), 1);
926 node_txn.retain(|tx| {
927 if tx.input.len() == 1 && tx.input[0].previous_output.txid == revoked_tx.txid() {
928 check_spends!(tx, revoked_tx.clone());
932 assert!(node_txn.is_empty());
935 pub fn check_preimage_claim(node: &Node, prev_txn: &Vec<Transaction>) -> Vec<Transaction> {
936 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
938 assert!(node_txn.len() >= 1);
939 assert_eq!(node_txn[0].input.len(), 1);
940 let mut found_prev = false;
943 if node_txn[0].input[0].previous_output.txid == tx.txid() {
944 check_spends!(node_txn[0], tx.clone());
945 assert!(node_txn[0].input[0].witness[2].len() > 106); // must spend an htlc output
946 assert_eq!(tx.input.len(), 1); // must spend a commitment tx
954 let mut res = Vec::new();
955 mem::swap(&mut *node_txn, &mut res);
959 pub fn get_announce_close_broadcast_events(nodes: &Vec<Node>, a: usize, b: usize) {
960 let events_1 = nodes[a].node.get_and_clear_pending_msg_events();
961 assert_eq!(events_1.len(), 1);
962 let as_update = match events_1[0] {
963 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
966 _ => panic!("Unexpected event"),
969 let events_2 = nodes[b].node.get_and_clear_pending_msg_events();
970 assert_eq!(events_2.len(), 1);
971 let bs_update = match events_2[0] {
972 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
975 _ => panic!("Unexpected event"),
979 node.router.handle_channel_update(&as_update).unwrap();
980 node.router.handle_channel_update(&bs_update).unwrap();
984 macro_rules! get_channel_value_stat {
985 ($node: expr, $channel_id: expr) => {{
986 let chan_lock = $node.node.channel_state.lock().unwrap();
987 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
988 chan.get_value_stat()
992 macro_rules! get_chan_reestablish_msgs {
993 ($src_node: expr, $dst_node: expr) => {
995 let mut res = Vec::with_capacity(1);
996 for msg in $src_node.node.get_and_clear_pending_msg_events() {
997 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
998 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
999 res.push(msg.clone());
1001 panic!("Unexpected event")
1009 macro_rules! handle_chan_reestablish_msgs {
1010 ($src_node: expr, $dst_node: expr) => {
1012 let msg_events = $src_node.node.get_and_clear_pending_msg_events();
1014 let funding_locked = if let Some(&MessageSendEvent::SendFundingLocked { ref node_id, ref msg }) = msg_events.get(0) {
1016 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
1022 let mut revoke_and_ack = None;
1023 let mut commitment_update = None;
1024 let order = if let Some(ev) = msg_events.get(idx) {
1027 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
1028 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
1029 revoke_and_ack = Some(msg.clone());
1030 RAACommitmentOrder::RevokeAndACKFirst
1032 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
1033 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
1034 commitment_update = Some(updates.clone());
1035 RAACommitmentOrder::CommitmentFirst
1037 _ => panic!("Unexpected event"),
1040 RAACommitmentOrder::CommitmentFirst
1043 if let Some(ev) = msg_events.get(idx) {
1045 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
1046 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
1047 assert!(revoke_and_ack.is_none());
1048 revoke_and_ack = Some(msg.clone());
1050 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
1051 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
1052 assert!(commitment_update.is_none());
1053 commitment_update = Some(updates.clone());
1055 _ => panic!("Unexpected event"),
1059 (funding_locked, revoke_and_ack, commitment_update, order)
1064 /// pending_htlc_adds includes both the holding cell and in-flight update_add_htlcs, whereas
1065 /// for claims/fails they are separated out.
1066 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)) {
1067 node_a.node.peer_connected(&node_b.node.get_our_node_id());
1068 let reestablish_1 = get_chan_reestablish_msgs!(node_a, node_b);
1069 node_b.node.peer_connected(&node_a.node.get_our_node_id());
1070 let reestablish_2 = get_chan_reestablish_msgs!(node_b, node_a);
1072 if send_funding_locked.0 {
1073 // If a expects a funding_locked, it better not think it has received a revoke_and_ack
1075 for reestablish in reestablish_1.iter() {
1076 assert_eq!(reestablish.next_remote_commitment_number, 0);
1079 if send_funding_locked.1 {
1080 // If b expects a funding_locked, it better not think it has received a revoke_and_ack
1082 for reestablish in reestablish_2.iter() {
1083 assert_eq!(reestablish.next_remote_commitment_number, 0);
1086 if send_funding_locked.0 || send_funding_locked.1 {
1087 // If we expect any funding_locked's, both sides better have set
1088 // next_local_commitment_number to 1
1089 for reestablish in reestablish_1.iter() {
1090 assert_eq!(reestablish.next_local_commitment_number, 1);
1092 for reestablish in reestablish_2.iter() {
1093 assert_eq!(reestablish.next_local_commitment_number, 1);
1097 let mut resp_1 = Vec::new();
1098 for msg in reestablish_1 {
1099 node_b.node.handle_channel_reestablish(&node_a.node.get_our_node_id(), &msg).unwrap();
1100 resp_1.push(handle_chan_reestablish_msgs!(node_b, node_a));
1102 if pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
1103 check_added_monitors!(node_b, 1);
1105 check_added_monitors!(node_b, 0);
1108 let mut resp_2 = Vec::new();
1109 for msg in reestablish_2 {
1110 node_a.node.handle_channel_reestablish(&node_b.node.get_our_node_id(), &msg).unwrap();
1111 resp_2.push(handle_chan_reestablish_msgs!(node_a, node_b));
1113 if pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
1114 check_added_monitors!(node_a, 1);
1116 check_added_monitors!(node_a, 0);
1119 // We don't yet support both needing updates, as that would require a different commitment dance:
1120 assert!((pending_htlc_adds.0 == 0 && pending_htlc_claims.0 == 0 && pending_cell_htlc_claims.0 == 0 && pending_cell_htlc_fails.0 == 0) ||
1121 (pending_htlc_adds.1 == 0 && pending_htlc_claims.1 == 0 && pending_cell_htlc_claims.1 == 0 && pending_cell_htlc_fails.1 == 0));
1123 for chan_msgs in resp_1.drain(..) {
1124 if send_funding_locked.0 {
1125 node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
1126 let announcement_event = node_a.node.get_and_clear_pending_msg_events();
1127 if !announcement_event.is_empty() {
1128 assert_eq!(announcement_event.len(), 1);
1129 if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
1130 //TODO: Test announcement_sigs re-sending
1131 } else { panic!("Unexpected event!"); }
1134 assert!(chan_msgs.0.is_none());
1137 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
1138 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
1139 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
1140 check_added_monitors!(node_a, 1);
1142 assert!(chan_msgs.1.is_none());
1144 if pending_htlc_adds.0 != 0 || pending_htlc_claims.0 != 0 || pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
1145 let commitment_update = chan_msgs.2.unwrap();
1146 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
1147 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.0 as usize);
1149 assert!(commitment_update.update_add_htlcs.is_empty());
1151 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
1152 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
1153 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
1154 for update_add in commitment_update.update_add_htlcs {
1155 node_a.node.handle_update_add_htlc(&node_b.node.get_our_node_id(), &update_add).unwrap();
1157 for update_fulfill in commitment_update.update_fulfill_htlcs {
1158 node_a.node.handle_update_fulfill_htlc(&node_b.node.get_our_node_id(), &update_fulfill).unwrap();
1160 for update_fail in commitment_update.update_fail_htlcs {
1161 node_a.node.handle_update_fail_htlc(&node_b.node.get_our_node_id(), &update_fail).unwrap();
1164 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
1165 commitment_signed_dance!(node_a, node_b, commitment_update.commitment_signed, false);
1167 node_a.node.handle_commitment_signed(&node_b.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
1168 check_added_monitors!(node_a, 1);
1169 let as_revoke_and_ack = get_event_msg!(node_a, MessageSendEvent::SendRevokeAndACK, node_b.node.get_our_node_id());
1170 // No commitment_signed so get_event_msg's assert(len == 1) passes
1171 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
1172 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
1173 check_added_monitors!(node_b, 1);
1176 assert!(chan_msgs.2.is_none());
1180 for chan_msgs in resp_2.drain(..) {
1181 if send_funding_locked.1 {
1182 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
1183 let announcement_event = node_b.node.get_and_clear_pending_msg_events();
1184 if !announcement_event.is_empty() {
1185 assert_eq!(announcement_event.len(), 1);
1186 if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
1187 //TODO: Test announcement_sigs re-sending
1188 } else { panic!("Unexpected event!"); }
1191 assert!(chan_msgs.0.is_none());
1194 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
1195 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
1196 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
1197 check_added_monitors!(node_b, 1);
1199 assert!(chan_msgs.1.is_none());
1201 if pending_htlc_adds.1 != 0 || pending_htlc_claims.1 != 0 || pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
1202 let commitment_update = chan_msgs.2.unwrap();
1203 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
1204 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.1 as usize);
1206 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
1207 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
1208 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
1209 for update_add in commitment_update.update_add_htlcs {
1210 node_b.node.handle_update_add_htlc(&node_a.node.get_our_node_id(), &update_add).unwrap();
1212 for update_fulfill in commitment_update.update_fulfill_htlcs {
1213 node_b.node.handle_update_fulfill_htlc(&node_a.node.get_our_node_id(), &update_fulfill).unwrap();
1215 for update_fail in commitment_update.update_fail_htlcs {
1216 node_b.node.handle_update_fail_htlc(&node_a.node.get_our_node_id(), &update_fail).unwrap();
1219 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
1220 commitment_signed_dance!(node_b, node_a, commitment_update.commitment_signed, false);
1222 node_b.node.handle_commitment_signed(&node_a.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
1223 check_added_monitors!(node_b, 1);
1224 let bs_revoke_and_ack = get_event_msg!(node_b, MessageSendEvent::SendRevokeAndACK, node_a.node.get_our_node_id());
1225 // No commitment_signed so get_event_msg's assert(len == 1) passes
1226 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
1227 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
1228 check_added_monitors!(node_a, 1);
1231 assert!(chan_msgs.2.is_none());