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::test_utils::TestChannelMonitor;
15 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
16 use util::errors::APIError;
17 use util::logger::Logger;
18 use util::config::UserConfig;
20 use bitcoin::util::hash::BitcoinHash;
21 use bitcoin::blockdata::block::BlockHeader;
22 use bitcoin::blockdata::transaction::{Transaction, TxOut};
23 use bitcoin::network::constants::Network;
25 use bitcoin_hashes::sha256::Hash as Sha256;
26 use bitcoin_hashes::sha256d::Hash as Sha256d;
27 use bitcoin_hashes::Hash;
29 use secp256k1::Secp256k1;
30 use secp256k1::key::PublicKey;
32 use rand::{thread_rng,Rng};
34 use std::cell::RefCell;
36 use std::sync::{Arc, Mutex};
38 use std::collections::HashSet;
40 pub const CHAN_CONFIRM_DEPTH: u32 = 100;
41 pub fn confirm_transaction<'a, 'b: 'a>(notifier: &'a chaininterface::BlockNotifierRef<'b>, chain: &chaininterface::ChainWatchInterfaceUtil, tx: &Transaction, chan_id: u32) {
42 assert!(chain.does_match_tx(tx));
43 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
44 notifier.block_connected_checked(&header, 1, &[tx; 1], &[chan_id; 1]);
45 for i in 2..CHAN_CONFIRM_DEPTH {
46 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
47 notifier.block_connected_checked(&header, i, &vec![], &[0; 0]);
51 pub fn connect_blocks<'a, 'b>(notifier: &'a chaininterface::BlockNotifierRef<'b>, depth: u32, height: u32, parent: bool, prev_blockhash: Sha256d) -> Sha256d {
52 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 };
53 notifier.block_connected_checked(&header, height + 1, &Vec::new(), &Vec::new());
54 for i in 2..depth + 1 {
55 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
56 notifier.block_connected_checked(&header, height + i, &Vec::new(), &Vec::new());
62 pub chain_monitor: Arc<chaininterface::ChainWatchInterfaceUtil>,
63 pub tx_broadcaster: Arc<test_utils::TestBroadcaster>,
64 pub fee_estimator: Arc<test_utils::TestFeeEstimator>,
65 pub chan_monitor: test_utils::TestChannelMonitor,
66 pub keys_manager: Arc<test_utils::TestKeysInterface>,
67 pub logger: Arc<test_utils::TestLogger>,
68 pub node_seed: [u8; 32],
71 pub struct Node<'a, 'b: 'a> {
72 pub block_notifier: chaininterface::BlockNotifierRef<'b>,
73 pub chain_monitor: Arc<chaininterface::ChainWatchInterfaceUtil>,
74 pub tx_broadcaster: Arc<test_utils::TestBroadcaster>,
75 pub chan_monitor: &'b test_utils::TestChannelMonitor,
76 pub keys_manager: Arc<test_utils::TestKeysInterface>,
77 pub node: &'a ChannelManager<EnforcingChannelKeys, &'b TestChannelMonitor>,
79 pub node_seed: [u8; 32],
80 pub network_payment_count: Rc<RefCell<u8>>,
81 pub network_chan_count: Rc<RefCell<u32>>,
82 pub logger: Arc<test_utils::TestLogger>
85 impl<'a, 'b> Drop for Node<'a, 'b> {
87 if !::std::thread::panicking() {
88 // Check that we processed all pending events
89 assert!(self.node.get_and_clear_pending_msg_events().is_empty());
90 assert!(self.node.get_and_clear_pending_events().is_empty());
91 assert!(self.chan_monitor.added_monitors.lock().unwrap().is_empty());
96 pub fn create_chan_between_nodes<'a, 'b, 'c>(node_a: &'a Node<'b, 'c>, node_b: &'a Node<'b, 'c>, a_flags: InitFeatures, b_flags: InitFeatures) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
97 create_chan_between_nodes_with_value(node_a, node_b, 100000, 10001, a_flags, b_flags)
100 pub fn create_chan_between_nodes_with_value<'a, 'b, 'c>(node_a: &'a Node<'b, 'c>, node_b: &'a Node<'b, 'c>, channel_value: u64, push_msat: u64, a_flags: InitFeatures, b_flags: InitFeatures) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
101 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);
102 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(node_a, node_b, &funding_locked);
103 (announcement, as_update, bs_update, channel_id, tx)
106 macro_rules! get_revoke_commit_msgs {
107 ($node: expr, $node_id: expr) => {
109 let events = $node.node.get_and_clear_pending_msg_events();
110 assert_eq!(events.len(), 2);
112 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
113 assert_eq!(*node_id, $node_id);
116 _ => panic!("Unexpected event"),
118 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
119 assert_eq!(*node_id, $node_id);
120 assert!(updates.update_add_htlcs.is_empty());
121 assert!(updates.update_fulfill_htlcs.is_empty());
122 assert!(updates.update_fail_htlcs.is_empty());
123 assert!(updates.update_fail_malformed_htlcs.is_empty());
124 assert!(updates.update_fee.is_none());
125 updates.commitment_signed.clone()
127 _ => panic!("Unexpected event"),
133 macro_rules! get_event_msg {
134 ($node: expr, $event_type: path, $node_id: expr) => {
136 let events = $node.node.get_and_clear_pending_msg_events();
137 assert_eq!(events.len(), 1);
139 $event_type { ref node_id, ref msg } => {
140 assert_eq!(*node_id, $node_id);
143 _ => panic!("Unexpected event"),
149 macro_rules! get_htlc_update_msgs {
150 ($node: expr, $node_id: expr) => {
152 let events = $node.node.get_and_clear_pending_msg_events();
153 assert_eq!(events.len(), 1);
155 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
156 assert_eq!(*node_id, $node_id);
159 _ => panic!("Unexpected event"),
165 macro_rules! get_feerate {
166 ($node: expr, $channel_id: expr) => {
168 let chan_lock = $node.node.channel_state.lock().unwrap();
169 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
175 pub fn create_funding_transaction<'a, 'b>(node: &Node<'a, 'b>, expected_chan_value: u64, expected_user_chan_id: u64) -> ([u8; 32], Transaction, OutPoint) {
176 let chan_id = *node.network_chan_count.borrow();
178 let events = node.node.get_and_clear_pending_events();
179 assert_eq!(events.len(), 1);
181 Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
182 assert_eq!(*channel_value_satoshis, expected_chan_value);
183 assert_eq!(user_channel_id, expected_user_chan_id);
185 let tx = Transaction { version: chan_id as u32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
186 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
188 let funding_outpoint = OutPoint::new(tx.txid(), 0);
189 (*temporary_channel_id, tx, funding_outpoint)
191 _ => panic!("Unexpected event"),
195 pub fn create_chan_between_nodes_with_value_init<'a, 'b>(node_a: &Node<'a, 'b>, node_b: &Node<'a, 'b>, channel_value: u64, push_msat: u64, a_flags: InitFeatures, b_flags: InitFeatures) -> Transaction {
196 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42).unwrap();
197 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()));
198 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()));
200 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(node_a, channel_value, 42);
203 node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
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 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()));
212 let mut added_monitors = node_b.chan_monitor.added_monitors.lock().unwrap();
213 assert_eq!(added_monitors.len(), 1);
214 assert_eq!(added_monitors[0].0, funding_output);
215 added_monitors.clear();
218 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()));
220 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
221 assert_eq!(added_monitors.len(), 1);
222 assert_eq!(added_monitors[0].0, funding_output);
223 added_monitors.clear();
226 let events_4 = node_a.node.get_and_clear_pending_events();
227 assert_eq!(events_4.len(), 1);
229 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
230 assert_eq!(user_channel_id, 42);
231 assert_eq!(*funding_txo, funding_output);
233 _ => panic!("Unexpected event"),
239 pub fn create_chan_between_nodes_with_value_confirm_first<'a, 'b, 'c>(node_recv: &'a Node<'a, 'b>, node_conf: &'a Node<'a, 'b>, tx: &Transaction) {
240 confirm_transaction(&node_conf.block_notifier, &node_conf.chain_monitor, &tx, tx.version);
241 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()));
244 pub fn create_chan_between_nodes_with_value_confirm_second<'a, 'b>(node_recv: &Node<'a, 'b>, node_conf: &Node<'a, 'b>) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32]) {
246 let events_6 = node_conf.node.get_and_clear_pending_msg_events();
247 assert_eq!(events_6.len(), 2);
248 ((match events_6[0] {
249 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
250 channel_id = msg.channel_id.clone();
251 assert_eq!(*node_id, node_recv.node.get_our_node_id());
254 _ => panic!("Unexpected event"),
255 }, match events_6[1] {
256 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
257 assert_eq!(*node_id, node_recv.node.get_our_node_id());
260 _ => panic!("Unexpected event"),
264 pub fn create_chan_between_nodes_with_value_confirm<'a, 'b, 'c>(node_a: &'a Node<'b, 'c>, node_b: &'a Node<'b, 'c>, tx: &Transaction) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32]) {
265 create_chan_between_nodes_with_value_confirm_first(node_a, node_b, tx);
266 confirm_transaction(&node_a.block_notifier, &node_a.chain_monitor, &tx, tx.version);
267 create_chan_between_nodes_with_value_confirm_second(node_b, node_a)
270 pub fn create_chan_between_nodes_with_value_a<'a, 'b, 'c>(node_a: &'a Node<'b, 'c>, node_b: &'a Node<'b, 'c>, channel_value: u64, push_msat: u64, a_flags: InitFeatures, b_flags: InitFeatures) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32], Transaction) {
271 let tx = create_chan_between_nodes_with_value_init(node_a, node_b, channel_value, push_msat, a_flags, b_flags);
272 let (msgs, chan_id) = create_chan_between_nodes_with_value_confirm(node_a, node_b, &tx);
276 pub fn create_chan_between_nodes_with_value_b<'a, 'b>(node_a: &Node<'a, 'b>, node_b: &Node<'a, 'b>, as_funding_msgs: &(msgs::FundingLocked, msgs::AnnouncementSignatures)) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate) {
277 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &as_funding_msgs.0);
278 let bs_announcement_sigs = get_event_msg!(node_b, MessageSendEvent::SendAnnouncementSignatures, node_a.node.get_our_node_id());
279 node_b.node.handle_announcement_signatures(&node_a.node.get_our_node_id(), &as_funding_msgs.1);
281 let events_7 = node_b.node.get_and_clear_pending_msg_events();
282 assert_eq!(events_7.len(), 1);
283 let (announcement, bs_update) = match events_7[0] {
284 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
287 _ => panic!("Unexpected event"),
290 node_a.node.handle_announcement_signatures(&node_b.node.get_our_node_id(), &bs_announcement_sigs);
291 let events_8 = node_a.node.get_and_clear_pending_msg_events();
292 assert_eq!(events_8.len(), 1);
293 let as_update = match events_8[0] {
294 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
295 assert!(*announcement == *msg);
296 assert_eq!(update_msg.contents.short_channel_id, announcement.contents.short_channel_id);
297 assert_eq!(update_msg.contents.short_channel_id, bs_update.contents.short_channel_id);
300 _ => panic!("Unexpected event"),
303 *node_a.network_chan_count.borrow_mut() += 1;
305 ((*announcement).clone(), (*as_update).clone(), (*bs_update).clone())
308 pub fn create_announced_chan_between_nodes<'a, 'b, 'c>(nodes: &'a Vec<Node<'b, 'c>>, a: usize, b: usize, a_flags: InitFeatures, b_flags: InitFeatures) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
309 create_announced_chan_between_nodes_with_value(nodes, a, b, 100000, 10001, a_flags, b_flags)
312 pub fn create_announced_chan_between_nodes_with_value<'a, 'b, 'c>(nodes: &'a Vec<Node<'b, 'c>>, a: usize, b: usize, channel_value: u64, push_msat: u64, a_flags: InitFeatures, b_flags: InitFeatures) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
313 let chan_announcement = create_chan_between_nodes_with_value(&nodes[a], &nodes[b], channel_value, push_msat, a_flags, b_flags);
315 assert!(node.router.handle_channel_announcement(&chan_announcement.0).unwrap());
316 node.router.handle_channel_update(&chan_announcement.1).unwrap();
317 node.router.handle_channel_update(&chan_announcement.2).unwrap();
319 (chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
322 macro_rules! check_spends {
323 ($tx: expr, $spends_tx: expr) => {
325 $tx.verify(|out_point| {
326 if out_point.txid == $spends_tx.txid() {
327 $spends_tx.output.get(out_point.vout as usize).cloned()
336 macro_rules! get_closing_signed_broadcast {
337 ($node: expr, $dest_pubkey: expr) => {
339 let events = $node.get_and_clear_pending_msg_events();
340 assert!(events.len() == 1 || events.len() == 2);
341 (match events[events.len() - 1] {
342 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
343 assert_eq!(msg.contents.flags & 2, 2);
346 _ => panic!("Unexpected event"),
347 }, if events.len() == 2 {
349 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
350 assert_eq!(*node_id, $dest_pubkey);
353 _ => panic!("Unexpected event"),
360 macro_rules! check_closed_broadcast {
361 ($node: expr, $with_error_msg: expr) => {{
362 let events = $node.node.get_and_clear_pending_msg_events();
363 assert_eq!(events.len(), if $with_error_msg { 2 } else { 1 });
365 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
366 assert_eq!(msg.contents.flags & 2, 2);
368 _ => panic!("Unexpected event"),
372 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
373 // TODO: Check node_id
376 _ => panic!("Unexpected event"),
382 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) {
383 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) };
384 let (node_b, broadcaster_b) = if close_inbound_first { (&outbound_node.node, &outbound_node.tx_broadcaster) } else { (&inbound_node.node, &inbound_node.tx_broadcaster) };
387 node_a.close_channel(channel_id).unwrap();
388 node_b.handle_shutdown(&node_a.get_our_node_id(), &get_event_msg!(struct_a, MessageSendEvent::SendShutdown, node_b.get_our_node_id()));
390 let events_1 = node_b.get_and_clear_pending_msg_events();
391 assert!(events_1.len() >= 1);
392 let shutdown_b = match events_1[0] {
393 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
394 assert_eq!(node_id, &node_a.get_our_node_id());
397 _ => panic!("Unexpected event"),
400 let closing_signed_b = if !close_inbound_first {
401 assert_eq!(events_1.len(), 1);
404 Some(match events_1[1] {
405 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
406 assert_eq!(node_id, &node_a.get_our_node_id());
409 _ => panic!("Unexpected event"),
413 node_a.handle_shutdown(&node_b.get_our_node_id(), &shutdown_b);
414 let (as_update, bs_update) = if close_inbound_first {
415 assert!(node_a.get_and_clear_pending_msg_events().is_empty());
416 node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap());
417 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
418 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
419 let (as_update, closing_signed_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
421 node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap());
422 let (bs_update, none_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
423 assert!(none_b.is_none());
424 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
425 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
426 (as_update, bs_update)
428 let closing_signed_a = get_event_msg!(struct_a, MessageSendEvent::SendClosingSigned, node_b.get_our_node_id());
430 node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a);
431 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
432 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
433 let (bs_update, closing_signed_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
435 node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap());
436 let (as_update, none_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
437 assert!(none_a.is_none());
438 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
439 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
440 (as_update, bs_update)
442 assert_eq!(tx_a, tx_b);
443 check_spends!(tx_a, funding_tx);
445 (as_update, bs_update, tx_a)
448 pub struct SendEvent {
449 pub node_id: PublicKey,
450 pub msgs: Vec<msgs::UpdateAddHTLC>,
451 pub commitment_msg: msgs::CommitmentSigned,
454 pub fn from_commitment_update(node_id: PublicKey, updates: msgs::CommitmentUpdate) -> SendEvent {
455 assert!(updates.update_fulfill_htlcs.is_empty());
456 assert!(updates.update_fail_htlcs.is_empty());
457 assert!(updates.update_fail_malformed_htlcs.is_empty());
458 assert!(updates.update_fee.is_none());
459 SendEvent { node_id: node_id, msgs: updates.update_add_htlcs, commitment_msg: updates.commitment_signed }
462 pub fn from_event(event: MessageSendEvent) -> SendEvent {
464 MessageSendEvent::UpdateHTLCs { node_id, updates } => SendEvent::from_commitment_update(node_id, updates),
465 _ => panic!("Unexpected event type!"),
469 pub fn from_node<'a, 'b>(node: &Node<'a, 'b>) -> SendEvent {
470 let mut events = node.node.get_and_clear_pending_msg_events();
471 assert_eq!(events.len(), 1);
472 SendEvent::from_event(events.pop().unwrap())
476 macro_rules! check_added_monitors {
477 ($node: expr, $count: expr) => {
479 let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
480 assert_eq!(added_monitors.len(), $count);
481 added_monitors.clear();
486 macro_rules! commitment_signed_dance {
487 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */) => {
489 check_added_monitors!($node_a, 0);
490 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
491 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed);
492 check_added_monitors!($node_a, 1);
493 commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, false);
496 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */, true /* return last RAA */) => {
498 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!($node_a, $node_b.node.get_our_node_id());
499 check_added_monitors!($node_b, 0);
500 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
501 $node_b.node.handle_revoke_and_ack(&$node_a.node.get_our_node_id(), &as_revoke_and_ack);
502 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
503 check_added_monitors!($node_b, 1);
504 $node_b.node.handle_commitment_signed(&$node_a.node.get_our_node_id(), &as_commitment_signed);
505 let (bs_revoke_and_ack, extra_msg_option) = {
506 let events = $node_b.node.get_and_clear_pending_msg_events();
507 assert!(events.len() <= 2);
509 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
510 assert_eq!(*node_id, $node_a.node.get_our_node_id());
513 _ => panic!("Unexpected event"),
514 }, events.get(1).map(|e| e.clone()))
516 check_added_monitors!($node_b, 1);
518 assert!($node_a.node.get_and_clear_pending_events().is_empty());
519 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
521 (extra_msg_option, bs_revoke_and_ack)
524 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */, false /* return extra message */, true /* return last RAA */) => {
526 check_added_monitors!($node_a, 0);
527 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
528 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed);
529 check_added_monitors!($node_a, 1);
530 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
531 assert!(extra_msg_option.is_none());
535 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */) => {
537 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
538 $node_a.node.handle_revoke_and_ack(&$node_b.node.get_our_node_id(), &bs_revoke_and_ack);
539 check_added_monitors!($node_a, 1);
543 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, false /* no extra message */) => {
545 assert!(commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true).is_none());
548 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr) => {
550 commitment_signed_dance!($node_a, $node_b, $commitment_signed, $fail_backwards, true);
552 expect_pending_htlcs_forwardable!($node_a);
553 check_added_monitors!($node_a, 1);
555 let channel_state = $node_a.node.channel_state.lock().unwrap();
556 assert_eq!(channel_state.pending_msg_events.len(), 1);
557 if let MessageSendEvent::UpdateHTLCs { ref node_id, .. } = channel_state.pending_msg_events[0] {
558 assert_ne!(*node_id, $node_b.node.get_our_node_id());
559 } else { panic!("Unexpected event"); }
561 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
567 macro_rules! get_payment_preimage_hash {
570 let payment_preimage = PaymentPreimage([*$node.network_payment_count.borrow(); 32]);
571 *$node.network_payment_count.borrow_mut() += 1;
572 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner());
573 (payment_preimage, payment_hash)
578 macro_rules! expect_pending_htlcs_forwardable {
580 let events = $node.node.get_and_clear_pending_events();
581 assert_eq!(events.len(), 1);
583 Event::PendingHTLCsForwardable { .. } => { },
584 _ => panic!("Unexpected event"),
586 $node.node.process_pending_htlc_forwards();
590 macro_rules! expect_payment_received {
591 ($node: expr, $expected_payment_hash: expr, $expected_recv_value: expr) => {
592 let events = $node.node.get_and_clear_pending_events();
593 assert_eq!(events.len(), 1);
595 Event::PaymentReceived { ref payment_hash, amt } => {
596 assert_eq!($expected_payment_hash, *payment_hash);
597 assert_eq!($expected_recv_value, amt);
599 _ => panic!("Unexpected event"),
604 macro_rules! expect_payment_sent {
605 ($node: expr, $expected_payment_preimage: expr) => {
606 let events = $node.node.get_and_clear_pending_events();
607 assert_eq!(events.len(), 1);
609 Event::PaymentSent { ref payment_preimage } => {
610 assert_eq!($expected_payment_preimage, *payment_preimage);
612 _ => panic!("Unexpected event"),
617 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) {
618 let mut payment_event = {
619 origin_node.node.send_payment(route, our_payment_hash).unwrap();
620 check_added_monitors!(origin_node, 1);
622 let mut events = origin_node.node.get_and_clear_pending_msg_events();
623 assert_eq!(events.len(), 1);
624 SendEvent::from_event(events.remove(0))
626 let mut prev_node = origin_node;
628 for (idx, &node) in expected_route.iter().enumerate() {
629 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
631 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
632 check_added_monitors!(node, 0);
633 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
635 expect_pending_htlcs_forwardable!(node);
637 if idx == expected_route.len() - 1 {
638 let events_2 = node.node.get_and_clear_pending_events();
639 assert_eq!(events_2.len(), 1);
641 Event::PaymentReceived { ref payment_hash, amt } => {
642 assert_eq!(our_payment_hash, *payment_hash);
643 assert_eq!(amt, recv_value);
645 _ => panic!("Unexpected event"),
648 let mut events_2 = node.node.get_and_clear_pending_msg_events();
649 assert_eq!(events_2.len(), 1);
650 check_added_monitors!(node, 1);
651 payment_event = SendEvent::from_event(events_2.remove(0));
652 assert_eq!(payment_event.msgs.len(), 1);
659 pub fn send_along_route<'a, 'b>(origin_node: &Node<'a, 'b>, route: Route, expected_route: &[&Node<'a, 'b>], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
660 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(origin_node);
661 send_along_route_with_hash(origin_node, route, expected_route, recv_value, our_payment_hash);
662 (our_payment_preimage, our_payment_hash)
665 pub fn claim_payment_along_route<'a, 'b>(origin_node: &Node<'a, 'b>, expected_route: &[&Node<'a, 'b>], skip_last: bool, our_payment_preimage: PaymentPreimage, expected_amount: u64) {
666 assert!(expected_route.last().unwrap().node.claim_funds(our_payment_preimage, expected_amount));
667 check_added_monitors!(expected_route.last().unwrap(), 1);
669 let mut next_msgs: Option<(msgs::UpdateFulfillHTLC, msgs::CommitmentSigned)> = None;
670 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
671 macro_rules! get_next_msgs {
674 let events = $node.node.get_and_clear_pending_msg_events();
675 assert_eq!(events.len(), 1);
677 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 } } => {
678 assert!(update_add_htlcs.is_empty());
679 assert_eq!(update_fulfill_htlcs.len(), 1);
680 assert!(update_fail_htlcs.is_empty());
681 assert!(update_fail_malformed_htlcs.is_empty());
682 assert!(update_fee.is_none());
683 expected_next_node = node_id.clone();
684 Some((update_fulfill_htlcs[0].clone(), commitment_signed.clone()))
686 _ => panic!("Unexpected event"),
692 macro_rules! last_update_fulfill_dance {
693 ($node: expr, $prev_node: expr) => {
695 $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0);
696 check_added_monitors!($node, 0);
697 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
698 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
702 macro_rules! mid_update_fulfill_dance {
703 ($node: expr, $prev_node: expr, $new_msgs: expr) => {
705 $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0);
706 check_added_monitors!($node, 1);
707 let new_next_msgs = if $new_msgs {
708 get_next_msgs!($node)
710 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
713 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
714 next_msgs = new_next_msgs;
719 let mut prev_node = expected_route.last().unwrap();
720 for (idx, node) in expected_route.iter().rev().enumerate() {
721 assert_eq!(expected_next_node, node.node.get_our_node_id());
722 let update_next_msgs = !skip_last || idx != expected_route.len() - 1;
723 if next_msgs.is_some() {
724 mid_update_fulfill_dance!(node, prev_node, update_next_msgs);
725 } else if update_next_msgs {
726 next_msgs = get_next_msgs!(node);
728 assert!(node.node.get_and_clear_pending_msg_events().is_empty());
730 if !skip_last && idx == expected_route.len() - 1 {
731 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
738 last_update_fulfill_dance!(origin_node, expected_route.first().unwrap());
739 expect_payment_sent!(origin_node, our_payment_preimage);
743 pub fn claim_payment<'a, 'b>(origin_node: &Node<'a, 'b>, expected_route: &[&Node<'a, 'b>], our_payment_preimage: PaymentPreimage, expected_amount: u64) {
744 claim_payment_along_route(origin_node, expected_route, false, our_payment_preimage, expected_amount);
747 pub const TEST_FINAL_CLTV: u32 = 32;
749 pub fn route_payment<'a, 'b>(origin_node: &Node<'a, 'b>, expected_route: &[&Node<'a, 'b>], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
750 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();
751 assert_eq!(route.hops.len(), expected_route.len());
752 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
753 assert_eq!(hop.pubkey, node.node.get_our_node_id());
756 send_along_route(origin_node, route, expected_route, recv_value)
759 pub fn route_over_limit<'a, 'b>(origin_node: &Node<'a, 'b>, expected_route: &[&Node<'a, 'b>], recv_value: u64) {
760 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();
761 assert_eq!(route.hops.len(), expected_route.len());
762 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
763 assert_eq!(hop.pubkey, node.node.get_our_node_id());
766 let (_, our_payment_hash) = get_payment_preimage_hash!(origin_node);
768 let err = origin_node.node.send_payment(route, our_payment_hash).err().unwrap();
770 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over the max HTLC value in flight our peer will accept"),
771 _ => panic!("Unknown error variants"),
775 pub fn send_payment<'a, 'b>(origin: &Node<'a, 'b>, expected_route: &[&Node<'a, 'b>], recv_value: u64, expected_value: u64) {
776 let our_payment_preimage = route_payment(&origin, expected_route, recv_value).0;
777 claim_payment(&origin, expected_route, our_payment_preimage, expected_value);
780 pub fn fail_payment_along_route<'a, 'b>(origin_node: &Node<'a, 'b>, expected_route: &[&Node<'a, 'b>], skip_last: bool, our_payment_hash: PaymentHash) {
781 assert!(expected_route.last().unwrap().node.fail_htlc_backwards(&our_payment_hash));
782 expect_pending_htlcs_forwardable!(expected_route.last().unwrap());
783 check_added_monitors!(expected_route.last().unwrap(), 1);
785 let mut next_msgs: Option<(msgs::UpdateFailHTLC, msgs::CommitmentSigned)> = None;
786 macro_rules! update_fail_dance {
787 ($node: expr, $prev_node: expr, $last_node: expr) => {
789 $node.node.handle_update_fail_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0);
790 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, !$last_node);
791 if skip_last && $last_node {
792 expect_pending_htlcs_forwardable!($node);
798 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
799 let mut prev_node = expected_route.last().unwrap();
800 for (idx, node) in expected_route.iter().rev().enumerate() {
801 assert_eq!(expected_next_node, node.node.get_our_node_id());
802 if next_msgs.is_some() {
803 // We may be the "last node" for the purpose of the commitment dance if we're
804 // skipping the last node (implying it is disconnected) and we're the
805 // second-to-last node!
806 update_fail_dance!(node, prev_node, skip_last && idx == expected_route.len() - 1);
809 let events = node.node.get_and_clear_pending_msg_events();
810 if !skip_last || idx != expected_route.len() - 1 {
811 assert_eq!(events.len(), 1);
813 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 } } => {
814 assert!(update_add_htlcs.is_empty());
815 assert!(update_fulfill_htlcs.is_empty());
816 assert_eq!(update_fail_htlcs.len(), 1);
817 assert!(update_fail_malformed_htlcs.is_empty());
818 assert!(update_fee.is_none());
819 expected_next_node = node_id.clone();
820 next_msgs = Some((update_fail_htlcs[0].clone(), commitment_signed.clone()));
822 _ => panic!("Unexpected event"),
825 assert!(events.is_empty());
827 if !skip_last && idx == expected_route.len() - 1 {
828 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
835 update_fail_dance!(origin_node, expected_route.first().unwrap(), true);
837 let events = origin_node.node.get_and_clear_pending_events();
838 assert_eq!(events.len(), 1);
840 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
841 assert_eq!(payment_hash, our_payment_hash);
842 assert!(rejected_by_dest);
844 _ => panic!("Unexpected event"),
849 pub fn fail_payment<'a, 'b>(origin_node: &Node<'a, 'b>, expected_route: &[&Node<'a, 'b>], our_payment_hash: PaymentHash) {
850 fail_payment_along_route(origin_node, expected_route, false, our_payment_hash);
853 pub fn create_node_cfgs(node_count: usize) -> Vec<NodeCfg> {
854 let mut nodes = Vec::new();
855 let mut rng = thread_rng();
857 for i in 0..node_count {
858 let logger = Arc::new(test_utils::TestLogger::with_id(format!("node {}", i)));
859 let fee_estimator = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 });
860 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, logger.clone() as Arc<Logger>));
861 let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new()), broadcasted_txn: Mutex::new(HashSet::new())});
862 let mut seed = [0; 32];
863 rng.fill_bytes(&mut seed);
864 let keys_manager = Arc::new(test_utils::TestKeysInterface::new(&seed, Network::Testnet, logger.clone() as Arc<Logger>));
865 let chan_monitor = test_utils::TestChannelMonitor::new(chain_monitor.clone(), tx_broadcaster.clone(), logger.clone(), fee_estimator.clone());
866 nodes.push(NodeCfg { chain_monitor, logger, tx_broadcaster, fee_estimator, chan_monitor, keys_manager, node_seed: seed });
872 pub fn create_node_chanmgrs<'a, 'b>(node_count: usize, cfgs: &'a Vec<NodeCfg>, node_config: &[Option<UserConfig>]) -> Vec<ChannelManager<EnforcingChannelKeys, &'a TestChannelMonitor>> {
873 let mut chanmgrs = Vec::new();
874 for i in 0..node_count {
875 let mut default_config = UserConfig::default();
876 default_config.channel_options.announced_channel = true;
877 default_config.peer_channel_config_limits.force_announced_channel_preference = false;
878 let node = ChannelManager::new(Network::Testnet, cfgs[i].fee_estimator.clone(), &cfgs[i].chan_monitor, cfgs[i].tx_broadcaster.clone(), cfgs[i].logger.clone(), cfgs[i].keys_manager.clone(), if node_config[i].is_some() { node_config[i].clone().unwrap() } else { default_config }, 0).unwrap();
885 pub fn create_network<'a, 'b>(node_count: usize, cfgs: &'a Vec<NodeCfg>, chan_mgrs: &'b Vec<ChannelManager<EnforcingChannelKeys, &'a TestChannelMonitor>>) -> Vec<Node<'a, 'b>> {
886 let secp_ctx = Secp256k1::new();
887 let mut nodes = Vec::new();
888 let chan_count = Rc::new(RefCell::new(0));
889 let payment_count = Rc::new(RefCell::new(0));
891 for i in 0..node_count {
892 let block_notifier = chaininterface::BlockNotifier::new(cfgs[i].chain_monitor.clone());
893 block_notifier.register_listener(&cfgs[i].chan_monitor.simple_monitor as &chaininterface::ChainListener);
894 block_notifier.register_listener(&chan_mgrs[i] as &chaininterface::ChainListener);
895 let router = Router::new(PublicKey::from_secret_key(&secp_ctx, &cfgs[i].keys_manager.get_node_secret()), cfgs[i].chain_monitor.clone(), cfgs[i].logger.clone() as Arc<Logger>);
896 nodes.push(Node{ chain_monitor: cfgs[i].chain_monitor.clone(), block_notifier,
897 tx_broadcaster: cfgs[i].tx_broadcaster.clone(), chan_monitor: &cfgs[i].chan_monitor,
898 keys_manager: cfgs[i].keys_manager.clone(), node: &chan_mgrs[i], router,
899 node_seed: cfgs[i].node_seed, network_chan_count: chan_count.clone(),
900 network_payment_count: payment_count.clone(), logger: cfgs[i].logger.clone(),
907 pub const ACCEPTED_HTLC_SCRIPT_WEIGHT: usize = 138; //Here we have a diff due to HTLC CLTV expiry being < 2^15 in test
908 pub const OFFERED_HTLC_SCRIPT_WEIGHT: usize = 133;
911 pub enum HTLCType { NONE, TIMEOUT, SUCCESS }
912 /// Tests that the given node has broadcast transactions for the given Channel
914 /// First checks that the latest local commitment tx has been broadcast, unless an explicit
915 /// commitment_tx is provided, which may be used to test that a remote commitment tx was
916 /// broadcast and the revoked outputs were claimed.
918 /// Next tests that there is (or is not) a transaction that spends the commitment transaction
919 /// that appears to be the type of HTLC transaction specified in has_htlc_tx.
921 /// All broadcast transactions must be accounted for in one of the above three types of we'll
923 pub fn test_txn_broadcast<'a, 'b>(node: &Node<'a, 'b>, chan: &(msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction), commitment_tx: Option<Transaction>, has_htlc_tx: HTLCType) -> Vec<Transaction> {
924 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
925 assert!(node_txn.len() >= if commitment_tx.is_some() { 0 } else { 1 } + if has_htlc_tx == HTLCType::NONE { 0 } else { 1 });
927 let mut res = Vec::with_capacity(2);
928 node_txn.retain(|tx| {
929 if tx.input.len() == 1 && tx.input[0].previous_output.txid == chan.3.txid() {
930 check_spends!(tx, chan.3.clone());
931 if commitment_tx.is_none() {
932 res.push(tx.clone());
937 if let Some(explicit_tx) = commitment_tx {
938 res.push(explicit_tx.clone());
941 assert_eq!(res.len(), 1);
943 if has_htlc_tx != HTLCType::NONE {
944 node_txn.retain(|tx| {
945 if tx.input.len() == 1 && tx.input[0].previous_output.txid == res[0].txid() {
946 check_spends!(tx, res[0].clone());
947 if has_htlc_tx == HTLCType::TIMEOUT {
948 assert!(tx.lock_time != 0);
950 assert!(tx.lock_time == 0);
952 res.push(tx.clone());
956 assert!(res.len() == 2 || res.len() == 3);
958 assert_eq!(res[1], res[2]);
962 assert!(node_txn.is_empty());
966 /// Tests that the given node has broadcast a claim transaction against the provided revoked
967 /// HTLC transaction.
968 pub fn test_revoked_htlc_claim_txn_broadcast<'a, 'b>(node: &Node<'a, 'b>, revoked_tx: Transaction, commitment_revoked_tx: Transaction) {
969 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
970 // We should issue a 2nd transaction if one htlc is dropped from initial claiming tx
971 // but sometimes not as feerate is too-low
972 if node_txn.len() != 1 && node_txn.len() != 2 { assert!(false); }
973 node_txn.retain(|tx| {
974 if tx.input.len() == 1 && tx.input[0].previous_output.txid == revoked_tx.txid() {
975 check_spends!(tx, revoked_tx);
979 node_txn.retain(|tx| {
980 check_spends!(tx, commitment_revoked_tx);
983 assert!(node_txn.is_empty());
986 pub fn check_preimage_claim<'a, 'b>(node: &Node<'a, 'b>, prev_txn: &Vec<Transaction>) -> Vec<Transaction> {
987 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
989 assert!(node_txn.len() >= 1);
990 assert_eq!(node_txn[0].input.len(), 1);
991 let mut found_prev = false;
994 if node_txn[0].input[0].previous_output.txid == tx.txid() {
995 check_spends!(node_txn[0], tx.clone());
996 assert!(node_txn[0].input[0].witness[2].len() > 106); // must spend an htlc output
997 assert_eq!(tx.input.len(), 1); // must spend a commitment tx
1003 assert!(found_prev);
1005 let mut res = Vec::new();
1006 mem::swap(&mut *node_txn, &mut res);
1010 pub fn get_announce_close_broadcast_events<'a, 'b>(nodes: &Vec<Node<'a, 'b>>, a: usize, b: usize) {
1011 let events_1 = nodes[a].node.get_and_clear_pending_msg_events();
1012 assert_eq!(events_1.len(), 1);
1013 let as_update = match events_1[0] {
1014 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
1017 _ => panic!("Unexpected event"),
1020 let events_2 = nodes[b].node.get_and_clear_pending_msg_events();
1021 assert_eq!(events_2.len(), 1);
1022 let bs_update = match events_2[0] {
1023 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
1026 _ => panic!("Unexpected event"),
1030 node.router.handle_channel_update(&as_update).unwrap();
1031 node.router.handle_channel_update(&bs_update).unwrap();
1035 macro_rules! get_channel_value_stat {
1036 ($node: expr, $channel_id: expr) => {{
1037 let chan_lock = $node.node.channel_state.lock().unwrap();
1038 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
1039 chan.get_value_stat()
1043 macro_rules! get_chan_reestablish_msgs {
1044 ($src_node: expr, $dst_node: expr) => {
1046 let mut res = Vec::with_capacity(1);
1047 for msg in $src_node.node.get_and_clear_pending_msg_events() {
1048 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
1049 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
1050 res.push(msg.clone());
1052 panic!("Unexpected event")
1060 macro_rules! handle_chan_reestablish_msgs {
1061 ($src_node: expr, $dst_node: expr) => {
1063 let msg_events = $src_node.node.get_and_clear_pending_msg_events();
1065 let funding_locked = if let Some(&MessageSendEvent::SendFundingLocked { ref node_id, ref msg }) = msg_events.get(0) {
1067 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
1073 let mut revoke_and_ack = None;
1074 let mut commitment_update = None;
1075 let order = if let Some(ev) = msg_events.get(idx) {
1078 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
1079 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
1080 revoke_and_ack = Some(msg.clone());
1081 RAACommitmentOrder::RevokeAndACKFirst
1083 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
1084 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
1085 commitment_update = Some(updates.clone());
1086 RAACommitmentOrder::CommitmentFirst
1088 _ => panic!("Unexpected event"),
1091 RAACommitmentOrder::CommitmentFirst
1094 if let Some(ev) = msg_events.get(idx) {
1096 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
1097 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
1098 assert!(revoke_and_ack.is_none());
1099 revoke_and_ack = Some(msg.clone());
1101 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
1102 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
1103 assert!(commitment_update.is_none());
1104 commitment_update = Some(updates.clone());
1106 _ => panic!("Unexpected event"),
1110 (funding_locked, revoke_and_ack, commitment_update, order)
1115 /// pending_htlc_adds includes both the holding cell and in-flight update_add_htlcs, whereas
1116 /// for claims/fails they are separated out.
1117 pub fn reconnect_nodes<'a, 'b>(node_a: &Node<'a, 'b>, node_b: &Node<'a, 'b>, 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)) {
1118 node_a.node.peer_connected(&node_b.node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1119 let reestablish_1 = get_chan_reestablish_msgs!(node_a, node_b);
1120 node_b.node.peer_connected(&node_a.node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1121 let reestablish_2 = get_chan_reestablish_msgs!(node_b, node_a);
1123 if send_funding_locked.0 {
1124 // If a expects a funding_locked, it better not think it has received a revoke_and_ack
1126 for reestablish in reestablish_1.iter() {
1127 assert_eq!(reestablish.next_remote_commitment_number, 0);
1130 if send_funding_locked.1 {
1131 // If b expects a funding_locked, it better not think it has received a revoke_and_ack
1133 for reestablish in reestablish_2.iter() {
1134 assert_eq!(reestablish.next_remote_commitment_number, 0);
1137 if send_funding_locked.0 || send_funding_locked.1 {
1138 // If we expect any funding_locked's, both sides better have set
1139 // next_local_commitment_number to 1
1140 for reestablish in reestablish_1.iter() {
1141 assert_eq!(reestablish.next_local_commitment_number, 1);
1143 for reestablish in reestablish_2.iter() {
1144 assert_eq!(reestablish.next_local_commitment_number, 1);
1148 let mut resp_1 = Vec::new();
1149 for msg in reestablish_1 {
1150 node_b.node.handle_channel_reestablish(&node_a.node.get_our_node_id(), &msg);
1151 resp_1.push(handle_chan_reestablish_msgs!(node_b, node_a));
1153 if pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
1154 check_added_monitors!(node_b, 1);
1156 check_added_monitors!(node_b, 0);
1159 let mut resp_2 = Vec::new();
1160 for msg in reestablish_2 {
1161 node_a.node.handle_channel_reestablish(&node_b.node.get_our_node_id(), &msg);
1162 resp_2.push(handle_chan_reestablish_msgs!(node_a, node_b));
1164 if pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
1165 check_added_monitors!(node_a, 1);
1167 check_added_monitors!(node_a, 0);
1170 // We don't yet support both needing updates, as that would require a different commitment dance:
1171 assert!((pending_htlc_adds.0 == 0 && pending_htlc_claims.0 == 0 && pending_cell_htlc_claims.0 == 0 && pending_cell_htlc_fails.0 == 0) ||
1172 (pending_htlc_adds.1 == 0 && pending_htlc_claims.1 == 0 && pending_cell_htlc_claims.1 == 0 && pending_cell_htlc_fails.1 == 0));
1174 for chan_msgs in resp_1.drain(..) {
1175 if send_funding_locked.0 {
1176 node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), &chan_msgs.0.unwrap());
1177 let announcement_event = node_a.node.get_and_clear_pending_msg_events();
1178 if !announcement_event.is_empty() {
1179 assert_eq!(announcement_event.len(), 1);
1180 if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
1181 //TODO: Test announcement_sigs re-sending
1182 } else { panic!("Unexpected event!"); }
1185 assert!(chan_msgs.0.is_none());
1188 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
1189 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap());
1190 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
1191 check_added_monitors!(node_a, 1);
1193 assert!(chan_msgs.1.is_none());
1195 if pending_htlc_adds.0 != 0 || pending_htlc_claims.0 != 0 || pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
1196 let commitment_update = chan_msgs.2.unwrap();
1197 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
1198 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.0 as usize);
1200 assert!(commitment_update.update_add_htlcs.is_empty());
1202 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
1203 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
1204 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
1205 for update_add in commitment_update.update_add_htlcs {
1206 node_a.node.handle_update_add_htlc(&node_b.node.get_our_node_id(), &update_add);
1208 for update_fulfill in commitment_update.update_fulfill_htlcs {
1209 node_a.node.handle_update_fulfill_htlc(&node_b.node.get_our_node_id(), &update_fulfill);
1211 for update_fail in commitment_update.update_fail_htlcs {
1212 node_a.node.handle_update_fail_htlc(&node_b.node.get_our_node_id(), &update_fail);
1215 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
1216 commitment_signed_dance!(node_a, node_b, commitment_update.commitment_signed, false);
1218 node_a.node.handle_commitment_signed(&node_b.node.get_our_node_id(), &commitment_update.commitment_signed);
1219 check_added_monitors!(node_a, 1);
1220 let as_revoke_and_ack = get_event_msg!(node_a, MessageSendEvent::SendRevokeAndACK, node_b.node.get_our_node_id());
1221 // No commitment_signed so get_event_msg's assert(len == 1) passes
1222 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &as_revoke_and_ack);
1223 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
1224 check_added_monitors!(node_b, 1);
1227 assert!(chan_msgs.2.is_none());
1231 for chan_msgs in resp_2.drain(..) {
1232 if send_funding_locked.1 {
1233 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &chan_msgs.0.unwrap());
1234 let announcement_event = node_b.node.get_and_clear_pending_msg_events();
1235 if !announcement_event.is_empty() {
1236 assert_eq!(announcement_event.len(), 1);
1237 if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
1238 //TODO: Test announcement_sigs re-sending
1239 } else { panic!("Unexpected event!"); }
1242 assert!(chan_msgs.0.is_none());
1245 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
1246 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap());
1247 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
1248 check_added_monitors!(node_b, 1);
1250 assert!(chan_msgs.1.is_none());
1252 if pending_htlc_adds.1 != 0 || pending_htlc_claims.1 != 0 || pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
1253 let commitment_update = chan_msgs.2.unwrap();
1254 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
1255 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.1 as usize);
1257 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
1258 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
1259 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
1260 for update_add in commitment_update.update_add_htlcs {
1261 node_b.node.handle_update_add_htlc(&node_a.node.get_our_node_id(), &update_add);
1263 for update_fulfill in commitment_update.update_fulfill_htlcs {
1264 node_b.node.handle_update_fulfill_htlc(&node_a.node.get_our_node_id(), &update_fulfill);
1266 for update_fail in commitment_update.update_fail_htlcs {
1267 node_b.node.handle_update_fail_htlc(&node_a.node.get_our_node_id(), &update_fail);
1270 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
1271 commitment_signed_dance!(node_b, node_a, commitment_update.commitment_signed, false);
1273 node_b.node.handle_commitment_signed(&node_a.node.get_our_node_id(), &commitment_update.commitment_signed);
1274 check_added_monitors!(node_b, 1);
1275 let bs_revoke_and_ack = get_event_msg!(node_b, MessageSendEvent::SendRevokeAndACK, node_a.node.get_our_node_id());
1276 // No commitment_signed so get_event_msg's assert(len == 1) passes
1277 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &bs_revoke_and_ack);
1278 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
1279 check_added_monitors!(node_a, 1);
1282 assert!(chan_msgs.2.is_none());