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, PaymentSendFailure};
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};
39 pub const CHAN_CONFIRM_DEPTH: u32 = 100;
40 pub fn confirm_transaction<'a, 'b: 'a>(notifier: &'a chaininterface::BlockNotifierRef<'b>, chain: &chaininterface::ChainWatchInterfaceUtil, tx: &Transaction, chan_id: u32) {
41 assert!(chain.does_match_tx(tx));
42 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
43 notifier.block_connected_checked(&header, 1, &[tx; 1], &[chan_id; 1]);
44 for i in 2..CHAN_CONFIRM_DEPTH {
45 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
46 notifier.block_connected_checked(&header, i, &vec![], &[0; 0]);
50 pub fn connect_blocks<'a, 'b>(notifier: &'a chaininterface::BlockNotifierRef<'b>, depth: u32, height: u32, parent: bool, prev_blockhash: Sha256d) -> Sha256d {
51 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 };
52 notifier.block_connected_checked(&header, height + 1, &Vec::new(), &Vec::new());
53 for i in 2..depth + 1 {
54 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
55 notifier.block_connected_checked(&header, height + i, &Vec::new(), &Vec::new());
61 pub chain_monitor: Arc<chaininterface::ChainWatchInterfaceUtil>,
62 pub tx_broadcaster: Arc<test_utils::TestBroadcaster>,
63 pub fee_estimator: Arc<test_utils::TestFeeEstimator>,
64 pub chan_monitor: test_utils::TestChannelMonitor,
65 pub keys_manager: Arc<test_utils::TestKeysInterface>,
66 pub logger: Arc<test_utils::TestLogger>,
67 pub node_seed: [u8; 32],
70 pub struct Node<'a, 'b: 'a> {
71 pub block_notifier: chaininterface::BlockNotifierRef<'b>,
72 pub chain_monitor: Arc<chaininterface::ChainWatchInterfaceUtil>,
73 pub tx_broadcaster: Arc<test_utils::TestBroadcaster>,
74 pub chan_monitor: &'b test_utils::TestChannelMonitor,
75 pub keys_manager: Arc<test_utils::TestKeysInterface>,
76 pub node: &'a ChannelManager<EnforcingChannelKeys, &'b TestChannelMonitor>,
78 pub node_seed: [u8; 32],
79 pub network_payment_count: Rc<RefCell<u8>>,
80 pub network_chan_count: Rc<RefCell<u32>>,
81 pub logger: Arc<test_utils::TestLogger>
84 impl<'a, 'b> Drop for Node<'a, 'b> {
86 if !::std::thread::panicking() {
87 // Check that we processed all pending events
88 assert!(self.node.get_and_clear_pending_msg_events().is_empty());
89 assert!(self.node.get_and_clear_pending_events().is_empty());
90 assert!(self.chan_monitor.added_monitors.lock().unwrap().is_empty());
95 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) {
96 create_chan_between_nodes_with_value(node_a, node_b, 100000, 10001, a_flags, b_flags)
99 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) {
100 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);
101 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(node_a, node_b, &funding_locked);
102 (announcement, as_update, bs_update, channel_id, tx)
105 macro_rules! get_revoke_commit_msgs {
106 ($node: expr, $node_id: expr) => {
108 let events = $node.node.get_and_clear_pending_msg_events();
109 assert_eq!(events.len(), 2);
111 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
112 assert_eq!(*node_id, $node_id);
115 _ => panic!("Unexpected event"),
117 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
118 assert_eq!(*node_id, $node_id);
119 assert!(updates.update_add_htlcs.is_empty());
120 assert!(updates.update_fulfill_htlcs.is_empty());
121 assert!(updates.update_fail_htlcs.is_empty());
122 assert!(updates.update_fail_malformed_htlcs.is_empty());
123 assert!(updates.update_fee.is_none());
124 updates.commitment_signed.clone()
126 _ => panic!("Unexpected event"),
132 macro_rules! get_event_msg {
133 ($node: expr, $event_type: path, $node_id: expr) => {
135 let events = $node.node.get_and_clear_pending_msg_events();
136 assert_eq!(events.len(), 1);
138 $event_type { ref node_id, ref msg } => {
139 assert_eq!(*node_id, $node_id);
142 _ => panic!("Unexpected event"),
148 macro_rules! get_htlc_update_msgs {
149 ($node: expr, $node_id: expr) => {
151 let events = $node.node.get_and_clear_pending_msg_events();
152 assert_eq!(events.len(), 1);
154 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
155 assert_eq!(*node_id, $node_id);
158 _ => panic!("Unexpected event"),
164 macro_rules! get_feerate {
165 ($node: expr, $channel_id: expr) => {
167 let chan_lock = $node.node.channel_state.lock().unwrap();
168 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
174 macro_rules! unwrap_send_err {
175 ($res: expr, $all_failed: expr, $type: pat, $check: expr) => {
177 &Err(PaymentSendFailure::AllFailedRetrySafe(ref fails)) if $all_failed => {
178 assert_eq!(fails.len(), 1);
184 &Err(PaymentSendFailure::PartialFailure(ref fails)) if !$all_failed => {
185 assert_eq!(fails.len(), 1);
187 Err($type) => { $check },
196 pub fn create_funding_transaction<'a, 'b>(node: &Node<'a, 'b>, expected_chan_value: u64, expected_user_chan_id: u64) -> ([u8; 32], Transaction, OutPoint) {
197 let chan_id = *node.network_chan_count.borrow();
199 let events = node.node.get_and_clear_pending_events();
200 assert_eq!(events.len(), 1);
202 Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
203 assert_eq!(*channel_value_satoshis, expected_chan_value);
204 assert_eq!(user_channel_id, expected_user_chan_id);
206 let tx = Transaction { version: chan_id as u32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
207 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
209 let funding_outpoint = OutPoint::new(tx.txid(), 0);
210 (*temporary_channel_id, tx, funding_outpoint)
212 _ => panic!("Unexpected event"),
216 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 {
217 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42).unwrap();
218 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()));
219 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()));
221 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(node_a, channel_value, 42);
224 node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
225 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
226 assert_eq!(added_monitors.len(), 1);
227 assert_eq!(added_monitors[0].0, funding_output);
228 added_monitors.clear();
231 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()));
233 let mut added_monitors = node_b.chan_monitor.added_monitors.lock().unwrap();
234 assert_eq!(added_monitors.len(), 1);
235 assert_eq!(added_monitors[0].0, funding_output);
236 added_monitors.clear();
239 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()));
241 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
242 assert_eq!(added_monitors.len(), 1);
243 assert_eq!(added_monitors[0].0, funding_output);
244 added_monitors.clear();
247 let events_4 = node_a.node.get_and_clear_pending_events();
248 assert_eq!(events_4.len(), 1);
250 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
251 assert_eq!(user_channel_id, 42);
252 assert_eq!(*funding_txo, funding_output);
254 _ => panic!("Unexpected event"),
260 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) {
261 confirm_transaction(&node_conf.block_notifier, &node_conf.chain_monitor, &tx, tx.version);
262 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()));
265 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]) {
267 let events_6 = node_conf.node.get_and_clear_pending_msg_events();
268 assert_eq!(events_6.len(), 2);
269 ((match events_6[0] {
270 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
271 channel_id = msg.channel_id.clone();
272 assert_eq!(*node_id, node_recv.node.get_our_node_id());
275 _ => panic!("Unexpected event"),
276 }, match events_6[1] {
277 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
278 assert_eq!(*node_id, node_recv.node.get_our_node_id());
281 _ => panic!("Unexpected event"),
285 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]) {
286 create_chan_between_nodes_with_value_confirm_first(node_a, node_b, tx);
287 confirm_transaction(&node_a.block_notifier, &node_a.chain_monitor, &tx, tx.version);
288 create_chan_between_nodes_with_value_confirm_second(node_b, node_a)
291 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) {
292 let tx = create_chan_between_nodes_with_value_init(node_a, node_b, channel_value, push_msat, a_flags, b_flags);
293 let (msgs, chan_id) = create_chan_between_nodes_with_value_confirm(node_a, node_b, &tx);
297 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) {
298 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &as_funding_msgs.0);
299 let bs_announcement_sigs = get_event_msg!(node_b, MessageSendEvent::SendAnnouncementSignatures, node_a.node.get_our_node_id());
300 node_b.node.handle_announcement_signatures(&node_a.node.get_our_node_id(), &as_funding_msgs.1);
302 let events_7 = node_b.node.get_and_clear_pending_msg_events();
303 assert_eq!(events_7.len(), 1);
304 let (announcement, bs_update) = match events_7[0] {
305 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
308 _ => panic!("Unexpected event"),
311 node_a.node.handle_announcement_signatures(&node_b.node.get_our_node_id(), &bs_announcement_sigs);
312 let events_8 = node_a.node.get_and_clear_pending_msg_events();
313 assert_eq!(events_8.len(), 1);
314 let as_update = match events_8[0] {
315 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
316 assert!(*announcement == *msg);
317 assert_eq!(update_msg.contents.short_channel_id, announcement.contents.short_channel_id);
318 assert_eq!(update_msg.contents.short_channel_id, bs_update.contents.short_channel_id);
321 _ => panic!("Unexpected event"),
324 *node_a.network_chan_count.borrow_mut() += 1;
326 ((*announcement).clone(), (*as_update).clone(), (*bs_update).clone())
329 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) {
330 create_announced_chan_between_nodes_with_value(nodes, a, b, 100000, 10001, a_flags, b_flags)
333 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) {
334 let chan_announcement = create_chan_between_nodes_with_value(&nodes[a], &nodes[b], channel_value, push_msat, a_flags, b_flags);
336 nodes[a].node.broadcast_node_announcement([0, 0, 0], [0; 32], msgs::NetAddressSet::new());
337 let a_events = nodes[a].node.get_and_clear_pending_msg_events();
338 assert_eq!(a_events.len(), 1);
339 let a_node_announcement = match a_events[0] {
340 MessageSendEvent::BroadcastNodeAnnouncement { ref msg } => {
343 _ => panic!("Unexpected event"),
346 nodes[b].node.broadcast_node_announcement([1, 1, 1], [1; 32], msgs::NetAddressSet::new());
347 let b_events = nodes[b].node.get_and_clear_pending_msg_events();
348 assert_eq!(b_events.len(), 1);
349 let b_node_announcement = match b_events[0] {
350 MessageSendEvent::BroadcastNodeAnnouncement { ref msg } => {
353 _ => panic!("Unexpected event"),
357 assert!(node.router.handle_channel_announcement(&chan_announcement.0).unwrap());
358 node.router.handle_channel_update(&chan_announcement.1).unwrap();
359 node.router.handle_channel_update(&chan_announcement.2).unwrap();
360 node.router.handle_node_announcement(&a_node_announcement).unwrap();
361 node.router.handle_node_announcement(&b_node_announcement).unwrap();
363 (chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
366 macro_rules! check_spends {
367 ($tx: expr, $spends_tx: expr) => {
369 $tx.verify(|out_point| {
370 if out_point.txid == $spends_tx.txid() {
371 $spends_tx.output.get(out_point.vout as usize).cloned()
380 macro_rules! get_closing_signed_broadcast {
381 ($node: expr, $dest_pubkey: expr) => {
383 let events = $node.get_and_clear_pending_msg_events();
384 assert!(events.len() == 1 || events.len() == 2);
385 (match events[events.len() - 1] {
386 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
387 assert_eq!(msg.contents.flags & 2, 2);
390 _ => panic!("Unexpected event"),
391 }, if events.len() == 2 {
393 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
394 assert_eq!(*node_id, $dest_pubkey);
397 _ => panic!("Unexpected event"),
404 macro_rules! check_closed_broadcast {
405 ($node: expr, $with_error_msg: expr) => {{
406 let events = $node.node.get_and_clear_pending_msg_events();
407 assert_eq!(events.len(), if $with_error_msg { 2 } else { 1 });
409 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
410 assert_eq!(msg.contents.flags & 2, 2);
412 _ => panic!("Unexpected event"),
416 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
417 // TODO: Check node_id
420 _ => panic!("Unexpected event"),
426 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) {
427 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) };
428 let (node_b, broadcaster_b) = if close_inbound_first { (&outbound_node.node, &outbound_node.tx_broadcaster) } else { (&inbound_node.node, &inbound_node.tx_broadcaster) };
431 node_a.close_channel(channel_id).unwrap();
432 node_b.handle_shutdown(&node_a.get_our_node_id(), &get_event_msg!(struct_a, MessageSendEvent::SendShutdown, node_b.get_our_node_id()));
434 let events_1 = node_b.get_and_clear_pending_msg_events();
435 assert!(events_1.len() >= 1);
436 let shutdown_b = match events_1[0] {
437 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
438 assert_eq!(node_id, &node_a.get_our_node_id());
441 _ => panic!("Unexpected event"),
444 let closing_signed_b = if !close_inbound_first {
445 assert_eq!(events_1.len(), 1);
448 Some(match events_1[1] {
449 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
450 assert_eq!(node_id, &node_a.get_our_node_id());
453 _ => panic!("Unexpected event"),
457 node_a.handle_shutdown(&node_b.get_our_node_id(), &shutdown_b);
458 let (as_update, bs_update) = if close_inbound_first {
459 assert!(node_a.get_and_clear_pending_msg_events().is_empty());
460 node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap());
461 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
462 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
463 let (as_update, closing_signed_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
465 node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap());
466 let (bs_update, none_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
467 assert!(none_b.is_none());
468 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
469 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
470 (as_update, bs_update)
472 let closing_signed_a = get_event_msg!(struct_a, MessageSendEvent::SendClosingSigned, node_b.get_our_node_id());
474 node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a);
475 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
476 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
477 let (bs_update, closing_signed_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
479 node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap());
480 let (as_update, none_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
481 assert!(none_a.is_none());
482 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
483 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
484 (as_update, bs_update)
486 assert_eq!(tx_a, tx_b);
487 check_spends!(tx_a, funding_tx);
489 (as_update, bs_update, tx_a)
492 pub struct SendEvent {
493 pub node_id: PublicKey,
494 pub msgs: Vec<msgs::UpdateAddHTLC>,
495 pub commitment_msg: msgs::CommitmentSigned,
498 pub fn from_commitment_update(node_id: PublicKey, updates: msgs::CommitmentUpdate) -> SendEvent {
499 assert!(updates.update_fulfill_htlcs.is_empty());
500 assert!(updates.update_fail_htlcs.is_empty());
501 assert!(updates.update_fail_malformed_htlcs.is_empty());
502 assert!(updates.update_fee.is_none());
503 SendEvent { node_id: node_id, msgs: updates.update_add_htlcs, commitment_msg: updates.commitment_signed }
506 pub fn from_event(event: MessageSendEvent) -> SendEvent {
508 MessageSendEvent::UpdateHTLCs { node_id, updates } => SendEvent::from_commitment_update(node_id, updates),
509 _ => panic!("Unexpected event type!"),
513 pub fn from_node<'a, 'b>(node: &Node<'a, 'b>) -> SendEvent {
514 let mut events = node.node.get_and_clear_pending_msg_events();
515 assert_eq!(events.len(), 1);
516 SendEvent::from_event(events.pop().unwrap())
520 macro_rules! check_added_monitors {
521 ($node: expr, $count: expr) => {
523 let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
524 assert_eq!(added_monitors.len(), $count);
525 added_monitors.clear();
530 macro_rules! commitment_signed_dance {
531 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */) => {
533 check_added_monitors!($node_a, 0);
534 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
535 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed);
536 check_added_monitors!($node_a, 1);
537 commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, false);
540 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */, true /* return last RAA */) => {
542 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!($node_a, $node_b.node.get_our_node_id());
543 check_added_monitors!($node_b, 0);
544 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
545 $node_b.node.handle_revoke_and_ack(&$node_a.node.get_our_node_id(), &as_revoke_and_ack);
546 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
547 check_added_monitors!($node_b, 1);
548 $node_b.node.handle_commitment_signed(&$node_a.node.get_our_node_id(), &as_commitment_signed);
549 let (bs_revoke_and_ack, extra_msg_option) = {
550 let events = $node_b.node.get_and_clear_pending_msg_events();
551 assert!(events.len() <= 2);
553 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
554 assert_eq!(*node_id, $node_a.node.get_our_node_id());
557 _ => panic!("Unexpected event"),
558 }, events.get(1).map(|e| e.clone()))
560 check_added_monitors!($node_b, 1);
562 assert!($node_a.node.get_and_clear_pending_events().is_empty());
563 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
565 (extra_msg_option, bs_revoke_and_ack)
568 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */, false /* return extra message */, true /* return last RAA */) => {
570 check_added_monitors!($node_a, 0);
571 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
572 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed);
573 check_added_monitors!($node_a, 1);
574 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
575 assert!(extra_msg_option.is_none());
579 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */) => {
581 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
582 $node_a.node.handle_revoke_and_ack(&$node_b.node.get_our_node_id(), &bs_revoke_and_ack);
583 check_added_monitors!($node_a, 1);
587 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, false /* no extra message */) => {
589 assert!(commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true).is_none());
592 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr) => {
594 commitment_signed_dance!($node_a, $node_b, $commitment_signed, $fail_backwards, true);
596 expect_pending_htlcs_forwardable!($node_a);
597 check_added_monitors!($node_a, 1);
599 let channel_state = $node_a.node.channel_state.lock().unwrap();
600 assert_eq!(channel_state.pending_msg_events.len(), 1);
601 if let MessageSendEvent::UpdateHTLCs { ref node_id, .. } = channel_state.pending_msg_events[0] {
602 assert_ne!(*node_id, $node_b.node.get_our_node_id());
603 } else { panic!("Unexpected event"); }
605 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
611 macro_rules! get_payment_preimage_hash {
614 let payment_preimage = PaymentPreimage([*$node.network_payment_count.borrow(); 32]);
615 *$node.network_payment_count.borrow_mut() += 1;
616 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner());
617 (payment_preimage, payment_hash)
622 macro_rules! expect_pending_htlcs_forwardable {
624 let events = $node.node.get_and_clear_pending_events();
625 assert_eq!(events.len(), 1);
627 Event::PendingHTLCsForwardable { .. } => { },
628 _ => panic!("Unexpected event"),
630 $node.node.process_pending_htlc_forwards();
634 macro_rules! expect_payment_received {
635 ($node: expr, $expected_payment_hash: expr, $expected_recv_value: expr) => {
636 let events = $node.node.get_and_clear_pending_events();
637 assert_eq!(events.len(), 1);
639 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
640 assert_eq!($expected_payment_hash, *payment_hash);
641 assert_eq!(*payment_secret, None);
642 assert_eq!($expected_recv_value, amt);
644 _ => panic!("Unexpected event"),
649 macro_rules! expect_payment_sent {
650 ($node: expr, $expected_payment_preimage: expr) => {
651 let events = $node.node.get_and_clear_pending_events();
652 assert_eq!(events.len(), 1);
654 Event::PaymentSent { ref payment_preimage } => {
655 assert_eq!($expected_payment_preimage, *payment_preimage);
657 _ => panic!("Unexpected event"),
662 pub fn send_along_route_with_secret<'a, 'b>(origin_node: &Node<'a, 'b>, route: Route, expected_paths: &[&[&Node<'a, 'b>]], recv_value: u64, our_payment_hash: PaymentHash, our_payment_secret: Option<[u8; 32]>) {
663 origin_node.node.send_payment(route, our_payment_hash, our_payment_secret.as_ref()).unwrap();
664 check_added_monitors!(origin_node, expected_paths.len());
666 let mut events = origin_node.node.get_and_clear_pending_msg_events();
667 assert_eq!(events.len(), expected_paths.len());
668 for (path_idx, (ev, expected_route)) in events.drain(..).zip(expected_paths.iter()).enumerate() {
669 let mut payment_event = SendEvent::from_event(ev);
670 let mut prev_node = origin_node;
672 for (idx, &node) in expected_route.iter().enumerate() {
673 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
675 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
676 check_added_monitors!(node, 0);
677 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
679 expect_pending_htlcs_forwardable!(node);
681 if idx == expected_route.len() - 1 {
682 let events_2 = node.node.get_and_clear_pending_events();
683 if path_idx == expected_paths.len() - 1 {
684 assert_eq!(events_2.len(), 1);
686 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
687 assert_eq!(our_payment_hash, *payment_hash);
688 assert_eq!(our_payment_secret, *payment_secret);
689 assert_eq!(amt, recv_value);
691 _ => panic!("Unexpected event"),
694 assert!(events_2.is_empty());
697 let mut events_2 = node.node.get_and_clear_pending_msg_events();
698 assert_eq!(events_2.len(), 1);
699 check_added_monitors!(node, 1);
700 payment_event = SendEvent::from_event(events_2.remove(0));
701 assert_eq!(payment_event.msgs.len(), 1);
709 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) {
710 send_along_route_with_secret(origin_node, route, &[expected_route], recv_value, our_payment_hash, None);
713 pub fn send_along_route<'a, 'b>(origin_node: &Node<'a, 'b>, route: Route, expected_route: &[&Node<'a, 'b>], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
714 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(origin_node);
715 send_along_route_with_hash(origin_node, route, expected_route, recv_value, our_payment_hash);
716 (our_payment_preimage, our_payment_hash)
719 pub fn claim_payment_along_route_with_secret<'a, 'b>(origin_node: &Node<'a, 'b>, expected_paths: &[&[&Node<'a, 'b>]], skip_last: bool, our_payment_preimage: PaymentPreimage, our_payment_secret: Option<[u8; 32]>, expected_amount: u64) {
720 for path in expected_paths.iter() {
721 assert_eq!(path.last().unwrap().node.get_our_node_id(), expected_paths[0].last().unwrap().node.get_our_node_id());
723 assert!(expected_paths[0].last().unwrap().node.claim_funds(our_payment_preimage, &our_payment_secret, expected_amount));
724 check_added_monitors!(expected_paths[0].last().unwrap(), expected_paths.len());
726 macro_rules! msgs_from_ev {
729 &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 } } => {
730 assert!(update_add_htlcs.is_empty());
731 assert_eq!(update_fulfill_htlcs.len(), 1);
732 assert!(update_fail_htlcs.is_empty());
733 assert!(update_fail_malformed_htlcs.is_empty());
734 assert!(update_fee.is_none());
735 ((update_fulfill_htlcs[0].clone(), commitment_signed.clone()), node_id.clone())
737 _ => panic!("Unexpected event"),
741 let mut per_path_msgs: Vec<((msgs::UpdateFulfillHTLC, msgs::CommitmentSigned), PublicKey)> = Vec::with_capacity(expected_paths.len());
742 let events = expected_paths[0].last().unwrap().node.get_and_clear_pending_msg_events();
743 assert_eq!(events.len(), expected_paths.len());
744 for ev in events.iter() {
745 per_path_msgs.push(msgs_from_ev!(ev));
748 for (expected_route, (path_msgs, next_hop)) in expected_paths.iter().zip(per_path_msgs.drain(..)) {
749 let mut next_msgs = Some(path_msgs);
750 let mut expected_next_node = next_hop;
752 macro_rules! last_update_fulfill_dance {
753 ($node: expr, $prev_node: expr) => {
755 $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0);
756 check_added_monitors!($node, 0);
757 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
758 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
762 macro_rules! mid_update_fulfill_dance {
763 ($node: expr, $prev_node: expr, $new_msgs: expr) => {
765 $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0);
766 check_added_monitors!($node, 1);
767 let new_next_msgs = if $new_msgs {
768 let events = $node.node.get_and_clear_pending_msg_events();
769 assert_eq!(events.len(), 1);
770 let (res, nexthop) = msgs_from_ev!(&events[0]);
771 expected_next_node = nexthop;
774 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
777 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
778 next_msgs = new_next_msgs;
783 let mut prev_node = expected_route.last().unwrap();
784 for (idx, node) in expected_route.iter().rev().enumerate().skip(1) {
785 assert_eq!(expected_next_node, node.node.get_our_node_id());
786 let update_next_msgs = !skip_last || idx != expected_route.len() - 1;
787 if next_msgs.is_some() {
788 mid_update_fulfill_dance!(node, prev_node, update_next_msgs);
790 assert!(!update_next_msgs);
791 assert!(node.node.get_and_clear_pending_msg_events().is_empty());
793 if !skip_last && idx == expected_route.len() - 1 {
794 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
801 last_update_fulfill_dance!(origin_node, expected_route.first().unwrap());
802 expect_payment_sent!(origin_node, our_payment_preimage);
807 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) {
808 claim_payment_along_route_with_secret(origin_node, &[expected_route], skip_last, our_payment_preimage, None, expected_amount);
811 pub fn claim_payment<'a, 'b>(origin_node: &Node<'a, 'b>, expected_route: &[&Node<'a, 'b>], our_payment_preimage: PaymentPreimage, expected_amount: u64) {
812 claim_payment_along_route(origin_node, expected_route, false, our_payment_preimage, expected_amount);
815 pub const TEST_FINAL_CLTV: u32 = 32;
817 pub fn route_payment<'a, 'b>(origin_node: &Node<'a, 'b>, expected_route: &[&Node<'a, 'b>], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
818 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();
819 assert_eq!(route.paths.len(), 1);
820 assert_eq!(route.paths[0].len(), expected_route.len());
821 for (node, hop) in expected_route.iter().zip(route.paths[0].iter()) {
822 assert_eq!(hop.pubkey, node.node.get_our_node_id());
825 send_along_route(origin_node, route, expected_route, recv_value)
828 pub fn route_over_limit<'a, 'b>(origin_node: &Node<'a, 'b>, expected_route: &[&Node<'a, 'b>], recv_value: u64) {
829 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();
830 assert_eq!(route.paths.len(), 1);
831 assert_eq!(route.paths[0].len(), expected_route.len());
832 for (node, hop) in expected_route.iter().zip(route.paths[0].iter()) {
833 assert_eq!(hop.pubkey, node.node.get_our_node_id());
836 let (_, our_payment_hash) = get_payment_preimage_hash!(origin_node);
837 unwrap_send_err!(origin_node.node.send_payment(route, our_payment_hash, None), true, APIError::ChannelUnavailable { err },
838 assert_eq!(err, "Cannot send value that would put us over the max HTLC value in flight our peer will accept"));
841 pub fn send_payment<'a, 'b>(origin: &Node<'a, 'b>, expected_route: &[&Node<'a, 'b>], recv_value: u64, expected_value: u64) {
842 let our_payment_preimage = route_payment(&origin, expected_route, recv_value).0;
843 claim_payment(&origin, expected_route, our_payment_preimage, expected_value);
846 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) {
847 assert!(expected_route.last().unwrap().node.fail_htlc_backwards(&our_payment_hash, &None));
848 expect_pending_htlcs_forwardable!(expected_route.last().unwrap());
849 check_added_monitors!(expected_route.last().unwrap(), 1);
851 let mut next_msgs: Option<(msgs::UpdateFailHTLC, msgs::CommitmentSigned)> = None;
852 macro_rules! update_fail_dance {
853 ($node: expr, $prev_node: expr, $last_node: expr) => {
855 $node.node.handle_update_fail_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0);
856 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, !$last_node);
857 if skip_last && $last_node {
858 expect_pending_htlcs_forwardable!($node);
864 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
865 let mut prev_node = expected_route.last().unwrap();
866 for (idx, node) in expected_route.iter().rev().enumerate() {
867 assert_eq!(expected_next_node, node.node.get_our_node_id());
868 if next_msgs.is_some() {
869 // We may be the "last node" for the purpose of the commitment dance if we're
870 // skipping the last node (implying it is disconnected) and we're the
871 // second-to-last node!
872 update_fail_dance!(node, prev_node, skip_last && idx == expected_route.len() - 1);
875 let events = node.node.get_and_clear_pending_msg_events();
876 if !skip_last || idx != expected_route.len() - 1 {
877 assert_eq!(events.len(), 1);
879 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 } } => {
880 assert!(update_add_htlcs.is_empty());
881 assert!(update_fulfill_htlcs.is_empty());
882 assert_eq!(update_fail_htlcs.len(), 1);
883 assert!(update_fail_malformed_htlcs.is_empty());
884 assert!(update_fee.is_none());
885 expected_next_node = node_id.clone();
886 next_msgs = Some((update_fail_htlcs[0].clone(), commitment_signed.clone()));
888 _ => panic!("Unexpected event"),
891 assert!(events.is_empty());
893 if !skip_last && idx == expected_route.len() - 1 {
894 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
901 update_fail_dance!(origin_node, expected_route.first().unwrap(), true);
903 let events = origin_node.node.get_and_clear_pending_events();
904 assert_eq!(events.len(), 1);
906 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
907 assert_eq!(payment_hash, our_payment_hash);
908 assert!(rejected_by_dest);
910 _ => panic!("Unexpected event"),
915 pub fn fail_payment<'a, 'b>(origin_node: &Node<'a, 'b>, expected_route: &[&Node<'a, 'b>], our_payment_hash: PaymentHash) {
916 fail_payment_along_route(origin_node, expected_route, false, our_payment_hash);
919 pub fn create_node_cfgs(node_count: usize) -> Vec<NodeCfg> {
920 let mut nodes = Vec::new();
921 let mut rng = thread_rng();
923 for i in 0..node_count {
924 let logger = Arc::new(test_utils::TestLogger::with_id(format!("node {}", i)));
925 let fee_estimator = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 });
926 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, logger.clone() as Arc<Logger>));
927 let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())});
928 let mut seed = [0; 32];
929 rng.fill_bytes(&mut seed);
930 let keys_manager = Arc::new(test_utils::TestKeysInterface::new(&seed, Network::Testnet, logger.clone() as Arc<Logger>));
931 let chan_monitor = test_utils::TestChannelMonitor::new(chain_monitor.clone(), tx_broadcaster.clone(), logger.clone(), fee_estimator.clone());
932 nodes.push(NodeCfg { chain_monitor, logger, tx_broadcaster, fee_estimator, chan_monitor, keys_manager, node_seed: seed });
938 pub fn create_node_chanmgrs<'a, 'b>(node_count: usize, cfgs: &'a Vec<NodeCfg>, node_config: &[Option<UserConfig>]) -> Vec<ChannelManager<EnforcingChannelKeys, &'a TestChannelMonitor>> {
939 let mut chanmgrs = Vec::new();
940 for i in 0..node_count {
941 let mut default_config = UserConfig::default();
942 default_config.channel_options.announced_channel = true;
943 default_config.peer_channel_config_limits.force_announced_channel_preference = false;
944 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();
951 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>> {
952 let secp_ctx = Secp256k1::new();
953 let mut nodes = Vec::new();
954 let chan_count = Rc::new(RefCell::new(0));
955 let payment_count = Rc::new(RefCell::new(0));
957 for i in 0..node_count {
958 let block_notifier = chaininterface::BlockNotifier::new(cfgs[i].chain_monitor.clone());
959 block_notifier.register_listener(&cfgs[i].chan_monitor.simple_monitor as &chaininterface::ChainListener);
960 block_notifier.register_listener(&chan_mgrs[i] as &chaininterface::ChainListener);
961 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>);
962 nodes.push(Node{ chain_monitor: cfgs[i].chain_monitor.clone(), block_notifier,
963 tx_broadcaster: cfgs[i].tx_broadcaster.clone(), chan_monitor: &cfgs[i].chan_monitor,
964 keys_manager: cfgs[i].keys_manager.clone(), node: &chan_mgrs[i], router,
965 node_seed: cfgs[i].node_seed, network_chan_count: chan_count.clone(),
966 network_payment_count: payment_count.clone(), logger: cfgs[i].logger.clone(),
973 pub const ACCEPTED_HTLC_SCRIPT_WEIGHT: usize = 138; //Here we have a diff due to HTLC CLTV expiry being < 2^15 in test
974 pub const OFFERED_HTLC_SCRIPT_WEIGHT: usize = 133;
977 pub enum HTLCType { NONE, TIMEOUT, SUCCESS }
978 /// Tests that the given node has broadcast transactions for the given Channel
980 /// First checks that the latest local commitment tx has been broadcast, unless an explicit
981 /// commitment_tx is provided, which may be used to test that a remote commitment tx was
982 /// broadcast and the revoked outputs were claimed.
984 /// Next tests that there is (or is not) a transaction that spends the commitment transaction
985 /// that appears to be the type of HTLC transaction specified in has_htlc_tx.
987 /// All broadcast transactions must be accounted for in one of the above three types of we'll
989 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> {
990 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
991 assert!(node_txn.len() >= if commitment_tx.is_some() { 0 } else { 1 } + if has_htlc_tx == HTLCType::NONE { 0 } else { 1 });
993 let mut res = Vec::with_capacity(2);
994 node_txn.retain(|tx| {
995 if tx.input.len() == 1 && tx.input[0].previous_output.txid == chan.3.txid() {
996 check_spends!(tx, chan.3.clone());
997 if commitment_tx.is_none() {
998 res.push(tx.clone());
1003 if let Some(explicit_tx) = commitment_tx {
1004 res.push(explicit_tx.clone());
1007 assert_eq!(res.len(), 1);
1009 if has_htlc_tx != HTLCType::NONE {
1010 node_txn.retain(|tx| {
1011 if tx.input.len() == 1 && tx.input[0].previous_output.txid == res[0].txid() {
1012 check_spends!(tx, res[0].clone());
1013 if has_htlc_tx == HTLCType::TIMEOUT {
1014 assert!(tx.lock_time != 0);
1016 assert!(tx.lock_time == 0);
1018 res.push(tx.clone());
1022 assert!(res.len() == 2 || res.len() == 3);
1024 assert_eq!(res[1], res[2]);
1028 assert!(node_txn.is_empty());
1032 /// Tests that the given node has broadcast a claim transaction against the provided revoked
1033 /// HTLC transaction.
1034 pub fn test_revoked_htlc_claim_txn_broadcast<'a, 'b>(node: &Node<'a, 'b>, revoked_tx: Transaction, commitment_revoked_tx: Transaction) {
1035 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
1036 // We should issue a 2nd transaction if one htlc is dropped from initial claiming tx
1037 // but sometimes not as feerate is too-low
1038 if node_txn.len() != 1 && node_txn.len() != 2 { assert!(false); }
1039 node_txn.retain(|tx| {
1040 if tx.input.len() == 1 && tx.input[0].previous_output.txid == revoked_tx.txid() {
1041 check_spends!(tx, revoked_tx);
1045 node_txn.retain(|tx| {
1046 check_spends!(tx, commitment_revoked_tx);
1049 assert!(node_txn.is_empty());
1052 pub fn check_preimage_claim<'a, 'b>(node: &Node<'a, 'b>, prev_txn: &Vec<Transaction>) -> Vec<Transaction> {
1053 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
1055 assert!(node_txn.len() >= 1);
1056 assert_eq!(node_txn[0].input.len(), 1);
1057 let mut found_prev = false;
1059 for tx in prev_txn {
1060 if node_txn[0].input[0].previous_output.txid == tx.txid() {
1061 check_spends!(node_txn[0], tx.clone());
1062 assert!(node_txn[0].input[0].witness[2].len() > 106); // must spend an htlc output
1063 assert_eq!(tx.input.len(), 1); // must spend a commitment tx
1069 assert!(found_prev);
1071 let mut res = Vec::new();
1072 mem::swap(&mut *node_txn, &mut res);
1076 pub fn get_announce_close_broadcast_events<'a, 'b>(nodes: &Vec<Node<'a, 'b>>, a: usize, b: usize) {
1077 let events_1 = nodes[a].node.get_and_clear_pending_msg_events();
1078 assert_eq!(events_1.len(), 1);
1079 let as_update = match events_1[0] {
1080 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
1083 _ => panic!("Unexpected event"),
1086 let events_2 = nodes[b].node.get_and_clear_pending_msg_events();
1087 assert_eq!(events_2.len(), 1);
1088 let bs_update = match events_2[0] {
1089 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
1092 _ => panic!("Unexpected event"),
1096 node.router.handle_channel_update(&as_update).unwrap();
1097 node.router.handle_channel_update(&bs_update).unwrap();
1101 macro_rules! get_channel_value_stat {
1102 ($node: expr, $channel_id: expr) => {{
1103 let chan_lock = $node.node.channel_state.lock().unwrap();
1104 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
1105 chan.get_value_stat()
1109 macro_rules! get_chan_reestablish_msgs {
1110 ($src_node: expr, $dst_node: expr) => {
1112 let mut res = Vec::with_capacity(1);
1113 for msg in $src_node.node.get_and_clear_pending_msg_events() {
1114 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
1115 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
1116 res.push(msg.clone());
1118 panic!("Unexpected event")
1126 macro_rules! handle_chan_reestablish_msgs {
1127 ($src_node: expr, $dst_node: expr) => {
1129 let msg_events = $src_node.node.get_and_clear_pending_msg_events();
1131 let funding_locked = if let Some(&MessageSendEvent::SendFundingLocked { ref node_id, ref msg }) = msg_events.get(0) {
1133 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
1139 let mut revoke_and_ack = None;
1140 let mut commitment_update = None;
1141 let order = if let Some(ev) = msg_events.get(idx) {
1144 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
1145 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
1146 revoke_and_ack = Some(msg.clone());
1147 RAACommitmentOrder::RevokeAndACKFirst
1149 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
1150 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
1151 commitment_update = Some(updates.clone());
1152 RAACommitmentOrder::CommitmentFirst
1154 _ => panic!("Unexpected event"),
1157 RAACommitmentOrder::CommitmentFirst
1160 if let Some(ev) = msg_events.get(idx) {
1162 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
1163 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
1164 assert!(revoke_and_ack.is_none());
1165 revoke_and_ack = Some(msg.clone());
1167 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
1168 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
1169 assert!(commitment_update.is_none());
1170 commitment_update = Some(updates.clone());
1172 _ => panic!("Unexpected event"),
1176 (funding_locked, revoke_and_ack, commitment_update, order)
1181 /// pending_htlc_adds includes both the holding cell and in-flight update_add_htlcs, whereas
1182 /// for claims/fails they are separated out.
1183 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)) {
1184 node_a.node.peer_connected(&node_b.node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1185 let reestablish_1 = get_chan_reestablish_msgs!(node_a, node_b);
1186 node_b.node.peer_connected(&node_a.node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1187 let reestablish_2 = get_chan_reestablish_msgs!(node_b, node_a);
1189 if send_funding_locked.0 {
1190 // If a expects a funding_locked, it better not think it has received a revoke_and_ack
1192 for reestablish in reestablish_1.iter() {
1193 assert_eq!(reestablish.next_remote_commitment_number, 0);
1196 if send_funding_locked.1 {
1197 // If b expects a funding_locked, it better not think it has received a revoke_and_ack
1199 for reestablish in reestablish_2.iter() {
1200 assert_eq!(reestablish.next_remote_commitment_number, 0);
1203 if send_funding_locked.0 || send_funding_locked.1 {
1204 // If we expect any funding_locked's, both sides better have set
1205 // next_local_commitment_number to 1
1206 for reestablish in reestablish_1.iter() {
1207 assert_eq!(reestablish.next_local_commitment_number, 1);
1209 for reestablish in reestablish_2.iter() {
1210 assert_eq!(reestablish.next_local_commitment_number, 1);
1214 let mut resp_1 = Vec::new();
1215 for msg in reestablish_1 {
1216 node_b.node.handle_channel_reestablish(&node_a.node.get_our_node_id(), &msg);
1217 resp_1.push(handle_chan_reestablish_msgs!(node_b, node_a));
1219 if pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
1220 check_added_monitors!(node_b, 1);
1222 check_added_monitors!(node_b, 0);
1225 let mut resp_2 = Vec::new();
1226 for msg in reestablish_2 {
1227 node_a.node.handle_channel_reestablish(&node_b.node.get_our_node_id(), &msg);
1228 resp_2.push(handle_chan_reestablish_msgs!(node_a, node_b));
1230 if pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
1231 check_added_monitors!(node_a, 1);
1233 check_added_monitors!(node_a, 0);
1236 // We don't yet support both needing updates, as that would require a different commitment dance:
1237 assert!((pending_htlc_adds.0 == 0 && pending_htlc_claims.0 == 0 && pending_cell_htlc_claims.0 == 0 && pending_cell_htlc_fails.0 == 0) ||
1238 (pending_htlc_adds.1 == 0 && pending_htlc_claims.1 == 0 && pending_cell_htlc_claims.1 == 0 && pending_cell_htlc_fails.1 == 0));
1240 for chan_msgs in resp_1.drain(..) {
1241 if send_funding_locked.0 {
1242 node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), &chan_msgs.0.unwrap());
1243 let announcement_event = node_a.node.get_and_clear_pending_msg_events();
1244 if !announcement_event.is_empty() {
1245 assert_eq!(announcement_event.len(), 1);
1246 if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
1247 //TODO: Test announcement_sigs re-sending
1248 } else { panic!("Unexpected event!"); }
1251 assert!(chan_msgs.0.is_none());
1254 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
1255 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap());
1256 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
1257 check_added_monitors!(node_a, 1);
1259 assert!(chan_msgs.1.is_none());
1261 if pending_htlc_adds.0 != 0 || pending_htlc_claims.0 != 0 || pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
1262 let commitment_update = chan_msgs.2.unwrap();
1263 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
1264 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.0 as usize);
1266 assert!(commitment_update.update_add_htlcs.is_empty());
1268 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
1269 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
1270 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
1271 for update_add in commitment_update.update_add_htlcs {
1272 node_a.node.handle_update_add_htlc(&node_b.node.get_our_node_id(), &update_add);
1274 for update_fulfill in commitment_update.update_fulfill_htlcs {
1275 node_a.node.handle_update_fulfill_htlc(&node_b.node.get_our_node_id(), &update_fulfill);
1277 for update_fail in commitment_update.update_fail_htlcs {
1278 node_a.node.handle_update_fail_htlc(&node_b.node.get_our_node_id(), &update_fail);
1281 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
1282 commitment_signed_dance!(node_a, node_b, commitment_update.commitment_signed, false);
1284 node_a.node.handle_commitment_signed(&node_b.node.get_our_node_id(), &commitment_update.commitment_signed);
1285 check_added_monitors!(node_a, 1);
1286 let as_revoke_and_ack = get_event_msg!(node_a, MessageSendEvent::SendRevokeAndACK, node_b.node.get_our_node_id());
1287 // No commitment_signed so get_event_msg's assert(len == 1) passes
1288 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &as_revoke_and_ack);
1289 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
1290 check_added_monitors!(node_b, 1);
1293 assert!(chan_msgs.2.is_none());
1297 for chan_msgs in resp_2.drain(..) {
1298 if send_funding_locked.1 {
1299 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &chan_msgs.0.unwrap());
1300 let announcement_event = node_b.node.get_and_clear_pending_msg_events();
1301 if !announcement_event.is_empty() {
1302 assert_eq!(announcement_event.len(), 1);
1303 if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
1304 //TODO: Test announcement_sigs re-sending
1305 } else { panic!("Unexpected event!"); }
1308 assert!(chan_msgs.0.is_none());
1311 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
1312 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap());
1313 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
1314 check_added_monitors!(node_b, 1);
1316 assert!(chan_msgs.1.is_none());
1318 if pending_htlc_adds.1 != 0 || pending_htlc_claims.1 != 0 || pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
1319 let commitment_update = chan_msgs.2.unwrap();
1320 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
1321 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.1 as usize);
1323 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
1324 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
1325 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
1326 for update_add in commitment_update.update_add_htlcs {
1327 node_b.node.handle_update_add_htlc(&node_a.node.get_our_node_id(), &update_add);
1329 for update_fulfill in commitment_update.update_fulfill_htlcs {
1330 node_b.node.handle_update_fulfill_htlc(&node_a.node.get_our_node_id(), &update_fulfill);
1332 for update_fail in commitment_update.update_fail_htlcs {
1333 node_b.node.handle_update_fail_htlc(&node_a.node.get_our_node_id(), &update_fail);
1336 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
1337 commitment_signed_dance!(node_b, node_a, commitment_update.commitment_signed, false);
1339 node_b.node.handle_commitment_signed(&node_a.node.get_our_node_id(), &commitment_update.commitment_signed);
1340 check_added_monitors!(node_b, 1);
1341 let bs_revoke_and_ack = get_event_msg!(node_b, MessageSendEvent::SendRevokeAndACK, node_a.node.get_our_node_id());
1342 // No commitment_signed so get_event_msg's assert(len == 1) passes
1343 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &bs_revoke_and_ack);
1344 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
1345 check_added_monitors!(node_a, 1);
1348 assert!(chan_msgs.2.is_none());