1 //! A bunch of useful utilities for building networks of nodes and exchanging messages between
2 //! nodes for functional tests.
4 use chain::chaininterface;
5 use chain::transaction::OutPoint;
6 use chain::keysinterface::KeysInterface;
7 use ln::channelmanager::{ChannelManager,RAACommitmentOrder, PaymentPreimage, PaymentHash};
8 use ln::router::{Route, Router};
10 use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler};
12 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
13 use util::errors::APIError;
14 use util::logger::Logger;
15 use util::config::UserConfig;
17 use bitcoin::util::hash::BitcoinHash;
18 use bitcoin::blockdata::block::BlockHeader;
19 use bitcoin::blockdata::transaction::{Transaction, TxOut};
20 use bitcoin::network::constants::Network;
22 use bitcoin_hashes::sha256::Hash as Sha256;
23 use bitcoin_hashes::Hash;
25 use secp256k1::Secp256k1;
26 use secp256k1::key::PublicKey;
28 use rand::{thread_rng,Rng};
30 use std::cell::RefCell;
31 use std::collections::HashMap;
32 use std::default::Default;
34 use std::sync::{Arc, Mutex};
35 use std::time::Instant;
38 pub const CHAN_CONFIRM_DEPTH: u32 = 100;
39 pub fn confirm_transaction(chain: &chaininterface::ChainWatchInterfaceUtil, tx: &Transaction, chan_id: u32) {
40 assert!(chain.does_match_tx(tx));
41 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
42 chain.block_connected_checked(&header, 1, &[tx; 1], &[chan_id; 1]);
43 for i in 2..CHAN_CONFIRM_DEPTH {
44 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
45 chain.block_connected_checked(&header, i, &[tx; 0], &[0; 0]);
50 pub chain_monitor: Arc<chaininterface::ChainWatchInterfaceUtil>,
51 pub tx_broadcaster: Arc<test_utils::TestBroadcaster>,
52 pub chan_monitor: Arc<test_utils::TestChannelMonitor>,
53 pub keys_manager: Arc<test_utils::TestKeysInterface>,
54 pub node: Arc<ChannelManager>,
56 pub node_seed: [u8; 32],
57 pub network_payment_count: Rc<RefCell<u8>>,
58 pub network_chan_count: Rc<RefCell<u32>>,
62 if !::std::thread::panicking() {
63 // Check that we processed all pending events
64 assert!(self.node.get_and_clear_pending_msg_events().is_empty());
65 assert!(self.node.get_and_clear_pending_events().is_empty());
66 assert!(self.chan_monitor.added_monitors.lock().unwrap().is_empty());
71 pub fn create_chan_between_nodes(node_a: &Node, node_b: &Node) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
72 create_chan_between_nodes_with_value(node_a, node_b, 100000, 10001)
75 pub fn create_chan_between_nodes_with_value(node_a: &Node, node_b: &Node, channel_value: u64, push_msat: u64) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
76 let (funding_locked, channel_id, tx) = create_chan_between_nodes_with_value_a(node_a, node_b, channel_value, push_msat);
77 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(node_a, node_b, &funding_locked);
78 (announcement, as_update, bs_update, channel_id, tx)
81 macro_rules! get_revoke_commit_msgs {
82 ($node: expr, $node_id: expr) => {
84 let events = $node.node.get_and_clear_pending_msg_events();
85 assert_eq!(events.len(), 2);
87 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
88 assert_eq!(*node_id, $node_id);
91 _ => panic!("Unexpected event"),
93 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
94 assert_eq!(*node_id, $node_id);
95 assert!(updates.update_add_htlcs.is_empty());
96 assert!(updates.update_fulfill_htlcs.is_empty());
97 assert!(updates.update_fail_htlcs.is_empty());
98 assert!(updates.update_fail_malformed_htlcs.is_empty());
99 assert!(updates.update_fee.is_none());
100 updates.commitment_signed.clone()
102 _ => panic!("Unexpected event"),
108 macro_rules! get_event_msg {
109 ($node: expr, $event_type: path, $node_id: expr) => {
111 let events = $node.node.get_and_clear_pending_msg_events();
112 assert_eq!(events.len(), 1);
114 $event_type { ref node_id, ref msg } => {
115 assert_eq!(*node_id, $node_id);
118 _ => panic!("Unexpected event"),
124 macro_rules! get_htlc_update_msgs {
125 ($node: expr, $node_id: expr) => {
127 let events = $node.node.get_and_clear_pending_msg_events();
128 assert_eq!(events.len(), 1);
130 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
131 assert_eq!(*node_id, $node_id);
134 _ => panic!("Unexpected event"),
140 macro_rules! get_feerate {
141 ($node: expr, $channel_id: expr) => {
143 let chan_lock = $node.node.channel_state.lock().unwrap();
144 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
151 pub fn create_chan_between_nodes_with_value_init(node_a: &Node, node_b: &Node, channel_value: u64, push_msat: u64) -> Transaction {
152 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42).unwrap();
153 node_b.node.handle_open_channel(&node_a.node.get_our_node_id(), &get_event_msg!(node_a, MessageSendEvent::SendOpenChannel, node_b.node.get_our_node_id())).unwrap();
154 node_a.node.handle_accept_channel(&node_b.node.get_our_node_id(), &get_event_msg!(node_b, MessageSendEvent::SendAcceptChannel, node_a.node.get_our_node_id())).unwrap();
156 let chan_id = *node_a.network_chan_count.borrow();
160 let events_2 = node_a.node.get_and_clear_pending_events();
161 assert_eq!(events_2.len(), 1);
163 Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
164 assert_eq!(*channel_value_satoshis, channel_value);
165 assert_eq!(user_channel_id, 42);
167 tx = Transaction { version: chan_id as u32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
168 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
170 funding_output = OutPoint::new(tx.txid(), 0);
172 node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
173 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
174 assert_eq!(added_monitors.len(), 1);
175 assert_eq!(added_monitors[0].0, funding_output);
176 added_monitors.clear();
178 _ => panic!("Unexpected event"),
181 node_b.node.handle_funding_created(&node_a.node.get_our_node_id(), &get_event_msg!(node_a, MessageSendEvent::SendFundingCreated, node_b.node.get_our_node_id())).unwrap();
183 let mut added_monitors = node_b.chan_monitor.added_monitors.lock().unwrap();
184 assert_eq!(added_monitors.len(), 1);
185 assert_eq!(added_monitors[0].0, funding_output);
186 added_monitors.clear();
189 node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id())).unwrap();
191 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
192 assert_eq!(added_monitors.len(), 1);
193 assert_eq!(added_monitors[0].0, funding_output);
194 added_monitors.clear();
197 let events_4 = node_a.node.get_and_clear_pending_events();
198 assert_eq!(events_4.len(), 1);
200 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
201 assert_eq!(user_channel_id, 42);
202 assert_eq!(*funding_txo, funding_output);
204 _ => panic!("Unexpected event"),
210 pub fn create_chan_between_nodes_with_value_confirm(node_a: &Node, node_b: &Node, tx: &Transaction) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32]) {
211 confirm_transaction(&node_b.chain_monitor, &tx, tx.version);
212 node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), &get_event_msg!(node_b, MessageSendEvent::SendFundingLocked, node_a.node.get_our_node_id())).unwrap();
216 confirm_transaction(&node_a.chain_monitor, &tx, tx.version);
217 let events_6 = node_a.node.get_and_clear_pending_msg_events();
218 assert_eq!(events_6.len(), 2);
219 ((match events_6[0] {
220 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
221 channel_id = msg.channel_id.clone();
222 assert_eq!(*node_id, node_b.node.get_our_node_id());
225 _ => panic!("Unexpected event"),
226 }, match events_6[1] {
227 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
228 assert_eq!(*node_id, node_b.node.get_our_node_id());
231 _ => panic!("Unexpected event"),
235 pub fn create_chan_between_nodes_with_value_a(node_a: &Node, node_b: &Node, channel_value: u64, push_msat: u64) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32], Transaction) {
236 let tx = create_chan_between_nodes_with_value_init(node_a, node_b, channel_value, push_msat);
237 let (msgs, chan_id) = create_chan_between_nodes_with_value_confirm(node_a, node_b, &tx);
241 pub fn create_chan_between_nodes_with_value_b(node_a: &Node, node_b: &Node, as_funding_msgs: &(msgs::FundingLocked, msgs::AnnouncementSignatures)) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate) {
242 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &as_funding_msgs.0).unwrap();
243 let bs_announcement_sigs = get_event_msg!(node_b, MessageSendEvent::SendAnnouncementSignatures, node_a.node.get_our_node_id());
244 node_b.node.handle_announcement_signatures(&node_a.node.get_our_node_id(), &as_funding_msgs.1).unwrap();
246 let events_7 = node_b.node.get_and_clear_pending_msg_events();
247 assert_eq!(events_7.len(), 1);
248 let (announcement, bs_update) = match events_7[0] {
249 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
252 _ => panic!("Unexpected event"),
255 node_a.node.handle_announcement_signatures(&node_b.node.get_our_node_id(), &bs_announcement_sigs).unwrap();
256 let events_8 = node_a.node.get_and_clear_pending_msg_events();
257 assert_eq!(events_8.len(), 1);
258 let as_update = match events_8[0] {
259 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
260 assert!(*announcement == *msg);
261 assert_eq!(update_msg.contents.short_channel_id, announcement.contents.short_channel_id);
262 assert_eq!(update_msg.contents.short_channel_id, bs_update.contents.short_channel_id);
265 _ => panic!("Unexpected event"),
268 *node_a.network_chan_count.borrow_mut() += 1;
270 ((*announcement).clone(), (*as_update).clone(), (*bs_update).clone())
273 pub fn create_announced_chan_between_nodes(nodes: &Vec<Node>, a: usize, b: usize) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
274 create_announced_chan_between_nodes_with_value(nodes, a, b, 100000, 10001)
277 pub fn create_announced_chan_between_nodes_with_value(nodes: &Vec<Node>, a: usize, b: usize, channel_value: u64, push_msat: u64) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
278 let chan_announcement = create_chan_between_nodes_with_value(&nodes[a], &nodes[b], channel_value, push_msat);
280 assert!(node.router.handle_channel_announcement(&chan_announcement.0).unwrap());
281 node.router.handle_channel_update(&chan_announcement.1).unwrap();
282 node.router.handle_channel_update(&chan_announcement.2).unwrap();
284 (chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
287 macro_rules! check_spends {
288 ($tx: expr, $spends_tx: expr) => {
290 let mut funding_tx_map = HashMap::new();
291 let spends_tx = $spends_tx;
292 funding_tx_map.insert(spends_tx.txid(), spends_tx);
293 $tx.verify(&funding_tx_map).unwrap();
298 macro_rules! get_closing_signed_broadcast {
299 ($node: expr, $dest_pubkey: expr) => {
301 let events = $node.get_and_clear_pending_msg_events();
302 assert!(events.len() == 1 || events.len() == 2);
303 (match events[events.len() - 1] {
304 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
305 assert_eq!(msg.contents.flags & 2, 2);
308 _ => panic!("Unexpected event"),
309 }, if events.len() == 2 {
311 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
312 assert_eq!(*node_id, $dest_pubkey);
315 _ => panic!("Unexpected event"),
322 macro_rules! check_closed_broadcast {
324 let events = $node.node.get_and_clear_pending_msg_events();
325 assert_eq!(events.len(), 1);
327 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
328 assert_eq!(msg.contents.flags & 2, 2);
330 _ => panic!("Unexpected event"),
335 pub fn close_channel(outbound_node: &Node, inbound_node: &Node, channel_id: &[u8; 32], funding_tx: Transaction, close_inbound_first: bool) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, Transaction) {
336 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) };
337 let (node_b, broadcaster_b) = if close_inbound_first { (&outbound_node.node, &outbound_node.tx_broadcaster) } else { (&inbound_node.node, &inbound_node.tx_broadcaster) };
340 node_a.close_channel(channel_id).unwrap();
341 node_b.handle_shutdown(&node_a.get_our_node_id(), &get_event_msg!(struct_a, MessageSendEvent::SendShutdown, node_b.get_our_node_id())).unwrap();
343 let events_1 = node_b.get_and_clear_pending_msg_events();
344 assert!(events_1.len() >= 1);
345 let shutdown_b = match events_1[0] {
346 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
347 assert_eq!(node_id, &node_a.get_our_node_id());
350 _ => panic!("Unexpected event"),
353 let closing_signed_b = if !close_inbound_first {
354 assert_eq!(events_1.len(), 1);
357 Some(match events_1[1] {
358 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
359 assert_eq!(node_id, &node_a.get_our_node_id());
362 _ => panic!("Unexpected event"),
366 node_a.handle_shutdown(&node_b.get_our_node_id(), &shutdown_b).unwrap();
367 let (as_update, bs_update) = if close_inbound_first {
368 assert!(node_a.get_and_clear_pending_msg_events().is_empty());
369 node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
370 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
371 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
372 let (as_update, closing_signed_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
374 node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap()).unwrap();
375 let (bs_update, none_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
376 assert!(none_b.is_none());
377 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
378 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
379 (as_update, bs_update)
381 let closing_signed_a = get_event_msg!(struct_a, MessageSendEvent::SendClosingSigned, node_b.get_our_node_id());
383 node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a).unwrap();
384 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
385 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
386 let (bs_update, closing_signed_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
388 node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
389 let (as_update, none_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
390 assert!(none_a.is_none());
391 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
392 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
393 (as_update, bs_update)
395 assert_eq!(tx_a, tx_b);
396 check_spends!(tx_a, funding_tx);
398 (as_update, bs_update, tx_a)
401 pub struct SendEvent {
402 pub node_id: PublicKey,
403 pub msgs: Vec<msgs::UpdateAddHTLC>,
404 pub commitment_msg: msgs::CommitmentSigned,
407 pub fn from_commitment_update(node_id: PublicKey, updates: msgs::CommitmentUpdate) -> SendEvent {
408 assert!(updates.update_fulfill_htlcs.is_empty());
409 assert!(updates.update_fail_htlcs.is_empty());
410 assert!(updates.update_fail_malformed_htlcs.is_empty());
411 assert!(updates.update_fee.is_none());
412 SendEvent { node_id: node_id, msgs: updates.update_add_htlcs, commitment_msg: updates.commitment_signed }
415 pub fn from_event(event: MessageSendEvent) -> SendEvent {
417 MessageSendEvent::UpdateHTLCs { node_id, updates } => SendEvent::from_commitment_update(node_id, updates),
418 _ => panic!("Unexpected event type!"),
422 pub fn from_node(node: &Node) -> SendEvent {
423 let mut events = node.node.get_and_clear_pending_msg_events();
424 assert_eq!(events.len(), 1);
425 SendEvent::from_event(events.pop().unwrap())
429 macro_rules! check_added_monitors {
430 ($node: expr, $count: expr) => {
432 let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
433 assert_eq!(added_monitors.len(), $count);
434 added_monitors.clear();
439 macro_rules! commitment_signed_dance {
440 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */) => {
442 check_added_monitors!($node_a, 0);
443 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
444 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
445 check_added_monitors!($node_a, 1);
446 commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, false);
449 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */, true /* return last RAA */) => {
451 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!($node_a, $node_b.node.get_our_node_id());
452 check_added_monitors!($node_b, 0);
453 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
454 $node_b.node.handle_revoke_and_ack(&$node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
455 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
456 check_added_monitors!($node_b, 1);
457 $node_b.node.handle_commitment_signed(&$node_a.node.get_our_node_id(), &as_commitment_signed).unwrap();
458 let (bs_revoke_and_ack, extra_msg_option) = {
459 let events = $node_b.node.get_and_clear_pending_msg_events();
460 assert!(events.len() <= 2);
462 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
463 assert_eq!(*node_id, $node_a.node.get_our_node_id());
466 _ => panic!("Unexpected event"),
467 }, events.get(1).map(|e| e.clone()))
469 check_added_monitors!($node_b, 1);
471 assert!($node_a.node.get_and_clear_pending_events().is_empty());
472 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
474 (extra_msg_option, bs_revoke_and_ack)
477 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */, false /* return extra message */, true /* return last RAA */) => {
479 check_added_monitors!($node_a, 0);
480 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
481 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
482 check_added_monitors!($node_a, 1);
483 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
484 assert!(extra_msg_option.is_none());
488 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */) => {
490 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
491 $node_a.node.handle_revoke_and_ack(&$node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
492 check_added_monitors!($node_a, 1);
496 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, false /* no extra message */) => {
498 assert!(commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true).is_none());
501 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr) => {
503 commitment_signed_dance!($node_a, $node_b, $commitment_signed, $fail_backwards, true);
505 expect_pending_htlcs_forwardable!($node_a);
506 check_added_monitors!($node_a, 1);
508 let channel_state = $node_a.node.channel_state.lock().unwrap();
509 assert_eq!(channel_state.pending_msg_events.len(), 1);
510 if let MessageSendEvent::UpdateHTLCs { ref node_id, .. } = channel_state.pending_msg_events[0] {
511 assert_ne!(*node_id, $node_b.node.get_our_node_id());
512 } else { panic!("Unexpected event"); }
514 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
520 macro_rules! get_payment_preimage_hash {
523 let payment_preimage = PaymentPreimage([*$node.network_payment_count.borrow(); 32]);
524 *$node.network_payment_count.borrow_mut() += 1;
525 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner());
526 (payment_preimage, payment_hash)
531 macro_rules! expect_pending_htlcs_forwardable {
533 let events = $node.node.get_and_clear_pending_events();
534 assert_eq!(events.len(), 1);
536 Event::PendingHTLCsForwardable { .. } => { },
537 _ => panic!("Unexpected event"),
539 let node_ref: &Node = &$node;
540 node_ref.node.channel_state.lock().unwrap().next_forward = Instant::now();
541 $node.node.process_pending_htlc_forwards();
545 macro_rules! expect_payment_received {
546 ($node: expr, $expected_payment_hash: expr, $expected_recv_value: expr) => {
547 let events = $node.node.get_and_clear_pending_events();
548 assert_eq!(events.len(), 1);
550 Event::PaymentReceived { ref payment_hash, amt } => {
551 assert_eq!($expected_payment_hash, *payment_hash);
552 assert_eq!($expected_recv_value, amt);
554 _ => panic!("Unexpected event"),
559 macro_rules! expect_payment_sent {
560 ($node: expr, $expected_payment_preimage: expr) => {
561 let events = $node.node.get_and_clear_pending_events();
562 assert_eq!(events.len(), 1);
564 Event::PaymentSent { ref payment_preimage } => {
565 assert_eq!($expected_payment_preimage, *payment_preimage);
567 _ => panic!("Unexpected event"),
572 pub fn send_along_route_with_hash(origin_node: &Node, route: Route, expected_route: &[&Node], recv_value: u64, our_payment_hash: PaymentHash) {
573 let mut payment_event = {
574 origin_node.node.send_payment(route, our_payment_hash).unwrap();
575 check_added_monitors!(origin_node, 1);
577 let mut events = origin_node.node.get_and_clear_pending_msg_events();
578 assert_eq!(events.len(), 1);
579 SendEvent::from_event(events.remove(0))
581 let mut prev_node = origin_node;
583 for (idx, &node) in expected_route.iter().enumerate() {
584 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
586 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
587 check_added_monitors!(node, 0);
588 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
590 expect_pending_htlcs_forwardable!(node);
592 if idx == expected_route.len() - 1 {
593 let events_2 = node.node.get_and_clear_pending_events();
594 assert_eq!(events_2.len(), 1);
596 Event::PaymentReceived { ref payment_hash, amt } => {
597 assert_eq!(our_payment_hash, *payment_hash);
598 assert_eq!(amt, recv_value);
600 _ => panic!("Unexpected event"),
603 let mut events_2 = node.node.get_and_clear_pending_msg_events();
604 assert_eq!(events_2.len(), 1);
605 check_added_monitors!(node, 1);
606 payment_event = SendEvent::from_event(events_2.remove(0));
607 assert_eq!(payment_event.msgs.len(), 1);
614 pub fn send_along_route(origin_node: &Node, route: Route, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
615 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(origin_node);
616 send_along_route_with_hash(origin_node, route, expected_route, recv_value, our_payment_hash);
617 (our_payment_preimage, our_payment_hash)
620 pub fn claim_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_preimage: PaymentPreimage) {
621 assert!(expected_route.last().unwrap().node.claim_funds(our_payment_preimage));
622 check_added_monitors!(expected_route.last().unwrap(), 1);
624 let mut next_msgs: Option<(msgs::UpdateFulfillHTLC, msgs::CommitmentSigned)> = None;
625 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
626 macro_rules! get_next_msgs {
629 let events = $node.node.get_and_clear_pending_msg_events();
630 assert_eq!(events.len(), 1);
632 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 } } => {
633 assert!(update_add_htlcs.is_empty());
634 assert_eq!(update_fulfill_htlcs.len(), 1);
635 assert!(update_fail_htlcs.is_empty());
636 assert!(update_fail_malformed_htlcs.is_empty());
637 assert!(update_fee.is_none());
638 expected_next_node = node_id.clone();
639 Some((update_fulfill_htlcs[0].clone(), commitment_signed.clone()))
641 _ => panic!("Unexpected event"),
647 macro_rules! last_update_fulfill_dance {
648 ($node: expr, $prev_node: expr) => {
650 $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
651 check_added_monitors!($node, 0);
652 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
653 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
657 macro_rules! mid_update_fulfill_dance {
658 ($node: expr, $prev_node: expr, $new_msgs: expr) => {
660 $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
661 check_added_monitors!($node, 1);
662 let new_next_msgs = if $new_msgs {
663 get_next_msgs!($node)
665 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
668 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
669 next_msgs = new_next_msgs;
674 let mut prev_node = expected_route.last().unwrap();
675 for (idx, node) in expected_route.iter().rev().enumerate() {
676 assert_eq!(expected_next_node, node.node.get_our_node_id());
677 let update_next_msgs = !skip_last || idx != expected_route.len() - 1;
678 if next_msgs.is_some() {
679 mid_update_fulfill_dance!(node, prev_node, update_next_msgs);
680 } else if update_next_msgs {
681 next_msgs = get_next_msgs!(node);
683 assert!(node.node.get_and_clear_pending_msg_events().is_empty());
685 if !skip_last && idx == expected_route.len() - 1 {
686 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
693 last_update_fulfill_dance!(origin_node, expected_route.first().unwrap());
694 expect_payment_sent!(origin_node, our_payment_preimage);
698 pub fn claim_payment(origin_node: &Node, expected_route: &[&Node], our_payment_preimage: PaymentPreimage) {
699 claim_payment_along_route(origin_node, expected_route, false, our_payment_preimage);
702 pub const TEST_FINAL_CLTV: u32 = 32;
704 pub fn route_payment(origin_node: &Node, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
705 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();
706 assert_eq!(route.hops.len(), expected_route.len());
707 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
708 assert_eq!(hop.pubkey, node.node.get_our_node_id());
711 send_along_route(origin_node, route, expected_route, recv_value)
714 pub fn route_over_limit(origin_node: &Node, expected_route: &[&Node], recv_value: u64) {
715 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();
716 assert_eq!(route.hops.len(), expected_route.len());
717 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
718 assert_eq!(hop.pubkey, node.node.get_our_node_id());
721 let (_, our_payment_hash) = get_payment_preimage_hash!(origin_node);
723 let err = origin_node.node.send_payment(route, our_payment_hash).err().unwrap();
725 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over the max HTLC value in flight"),
726 _ => panic!("Unknown error variants"),
730 pub fn send_payment(origin: &Node, expected_route: &[&Node], recv_value: u64) {
731 let our_payment_preimage = route_payment(&origin, expected_route, recv_value).0;
732 claim_payment(&origin, expected_route, our_payment_preimage);
735 pub fn fail_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_hash: PaymentHash) {
736 assert!(expected_route.last().unwrap().node.fail_htlc_backwards(&our_payment_hash));
737 expect_pending_htlcs_forwardable!(expected_route.last().unwrap());
738 check_added_monitors!(expected_route.last().unwrap(), 1);
740 let mut next_msgs: Option<(msgs::UpdateFailHTLC, msgs::CommitmentSigned)> = None;
741 macro_rules! update_fail_dance {
742 ($node: expr, $prev_node: expr, $last_node: expr) => {
744 $node.node.handle_update_fail_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
745 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, !$last_node);
746 if skip_last && $last_node {
747 expect_pending_htlcs_forwardable!($node);
753 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
754 let mut prev_node = expected_route.last().unwrap();
755 for (idx, node) in expected_route.iter().rev().enumerate() {
756 assert_eq!(expected_next_node, node.node.get_our_node_id());
757 if next_msgs.is_some() {
758 // We may be the "last node" for the purpose of the commitment dance if we're
759 // skipping the last node (implying it is disconnected) and we're the
760 // second-to-last node!
761 update_fail_dance!(node, prev_node, skip_last && idx == expected_route.len() - 1);
764 let events = node.node.get_and_clear_pending_msg_events();
765 if !skip_last || idx != expected_route.len() - 1 {
766 assert_eq!(events.len(), 1);
768 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 } } => {
769 assert!(update_add_htlcs.is_empty());
770 assert!(update_fulfill_htlcs.is_empty());
771 assert_eq!(update_fail_htlcs.len(), 1);
772 assert!(update_fail_malformed_htlcs.is_empty());
773 assert!(update_fee.is_none());
774 expected_next_node = node_id.clone();
775 next_msgs = Some((update_fail_htlcs[0].clone(), commitment_signed.clone()));
777 _ => panic!("Unexpected event"),
780 assert!(events.is_empty());
782 if !skip_last && idx == expected_route.len() - 1 {
783 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
790 update_fail_dance!(origin_node, expected_route.first().unwrap(), true);
792 let events = origin_node.node.get_and_clear_pending_events();
793 assert_eq!(events.len(), 1);
795 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
796 assert_eq!(payment_hash, our_payment_hash);
797 assert!(rejected_by_dest);
799 _ => panic!("Unexpected event"),
804 pub fn fail_payment(origin_node: &Node, expected_route: &[&Node], our_payment_hash: PaymentHash) {
805 fail_payment_along_route(origin_node, expected_route, false, our_payment_hash);
808 pub fn create_network(node_count: usize) -> Vec<Node> {
809 let mut nodes = Vec::new();
810 let mut rng = thread_rng();
811 let secp_ctx = Secp256k1::new();
813 let chan_count = Rc::new(RefCell::new(0));
814 let payment_count = Rc::new(RefCell::new(0));
816 for i in 0..node_count {
817 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::with_id(format!("node {}", i)));
818 let feeest = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 });
819 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
820 let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())});
821 let mut seed = [0; 32];
822 rng.fill_bytes(&mut seed);
823 let keys_manager = Arc::new(test_utils::TestKeysInterface::new(&seed, Network::Testnet, Arc::clone(&logger)));
824 let chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(chain_monitor.clone(), tx_broadcaster.clone(), logger.clone(), feeest.clone()));
825 let mut config = UserConfig::new();
826 config.channel_options.announced_channel = true;
827 config.channel_limits.force_announced_channel_preference = false;
828 let node = ChannelManager::new(Network::Testnet, feeest.clone(), chan_monitor.clone(), chain_monitor.clone(), tx_broadcaster.clone(), Arc::clone(&logger), keys_manager.clone(), config).unwrap();
829 let router = Router::new(PublicKey::from_secret_key(&secp_ctx, &keys_manager.get_node_secret()), chain_monitor.clone(), Arc::clone(&logger));
830 nodes.push(Node { chain_monitor, tx_broadcaster, chan_monitor, node, router, keys_manager, node_seed: seed,
831 network_payment_count: payment_count.clone(),
832 network_chan_count: chan_count.clone(),
840 pub enum HTLCType { NONE, TIMEOUT, SUCCESS }
841 /// Tests that the given node has broadcast transactions for the given Channel
843 /// First checks that the latest local commitment tx has been broadcast, unless an explicit
844 /// commitment_tx is provided, which may be used to test that a remote commitment tx was
845 /// broadcast and the revoked outputs were claimed.
847 /// Next tests that there is (or is not) a transaction that spends the commitment transaction
848 /// that appears to be the type of HTLC transaction specified in has_htlc_tx.
850 /// All broadcast transactions must be accounted for in one of the above three types of we'll
852 pub fn test_txn_broadcast(node: &Node, chan: &(msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction), commitment_tx: Option<Transaction>, has_htlc_tx: HTLCType) -> Vec<Transaction> {
853 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
854 assert!(node_txn.len() >= if commitment_tx.is_some() { 0 } else { 1 } + if has_htlc_tx == HTLCType::NONE { 0 } else { 1 });
856 let mut res = Vec::with_capacity(2);
857 node_txn.retain(|tx| {
858 if tx.input.len() == 1 && tx.input[0].previous_output.txid == chan.3.txid() {
859 check_spends!(tx, chan.3.clone());
860 if commitment_tx.is_none() {
861 res.push(tx.clone());
866 if let Some(explicit_tx) = commitment_tx {
867 res.push(explicit_tx.clone());
870 assert_eq!(res.len(), 1);
872 if has_htlc_tx != HTLCType::NONE {
873 node_txn.retain(|tx| {
874 if tx.input.len() == 1 && tx.input[0].previous_output.txid == res[0].txid() {
875 check_spends!(tx, res[0].clone());
876 if has_htlc_tx == HTLCType::TIMEOUT {
877 assert!(tx.lock_time != 0);
879 assert!(tx.lock_time == 0);
881 res.push(tx.clone());
885 assert!(res.len() == 2 || res.len() == 3);
887 assert_eq!(res[1], res[2]);
891 assert!(node_txn.is_empty());
895 /// Tests that the given node has broadcast a claim transaction against the provided revoked
896 /// HTLC transaction.
897 pub fn test_revoked_htlc_claim_txn_broadcast(node: &Node, revoked_tx: Transaction) {
898 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
899 assert_eq!(node_txn.len(), 1);
900 node_txn.retain(|tx| {
901 if tx.input.len() == 1 && tx.input[0].previous_output.txid == revoked_tx.txid() {
902 check_spends!(tx, revoked_tx.clone());
906 assert!(node_txn.is_empty());
909 pub fn check_preimage_claim(node: &Node, prev_txn: &Vec<Transaction>) -> Vec<Transaction> {
910 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
912 assert!(node_txn.len() >= 1);
913 assert_eq!(node_txn[0].input.len(), 1);
914 let mut found_prev = false;
917 if node_txn[0].input[0].previous_output.txid == tx.txid() {
918 check_spends!(node_txn[0], tx.clone());
919 assert!(node_txn[0].input[0].witness[2].len() > 106); // must spend an htlc output
920 assert_eq!(tx.input.len(), 1); // must spend a commitment tx
928 let mut res = Vec::new();
929 mem::swap(&mut *node_txn, &mut res);
933 pub fn get_announce_close_broadcast_events(nodes: &Vec<Node>, a: usize, b: usize) {
934 let events_1 = nodes[a].node.get_and_clear_pending_msg_events();
935 assert_eq!(events_1.len(), 1);
936 let as_update = match events_1[0] {
937 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
940 _ => panic!("Unexpected event"),
943 let events_2 = nodes[b].node.get_and_clear_pending_msg_events();
944 assert_eq!(events_2.len(), 1);
945 let bs_update = match events_2[0] {
946 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
949 _ => panic!("Unexpected event"),
953 node.router.handle_channel_update(&as_update).unwrap();
954 node.router.handle_channel_update(&bs_update).unwrap();
958 macro_rules! get_channel_value_stat {
959 ($node: expr, $channel_id: expr) => {{
960 let chan_lock = $node.node.channel_state.lock().unwrap();
961 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
962 chan.get_value_stat()
966 macro_rules! get_chan_reestablish_msgs {
967 ($src_node: expr, $dst_node: expr) => {
969 let mut res = Vec::with_capacity(1);
970 for msg in $src_node.node.get_and_clear_pending_msg_events() {
971 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
972 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
973 res.push(msg.clone());
975 panic!("Unexpected event")
983 macro_rules! handle_chan_reestablish_msgs {
984 ($src_node: expr, $dst_node: expr) => {
986 let msg_events = $src_node.node.get_and_clear_pending_msg_events();
988 let funding_locked = if let Some(&MessageSendEvent::SendFundingLocked { ref node_id, ref msg }) = msg_events.get(0) {
990 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
996 let mut revoke_and_ack = None;
997 let mut commitment_update = None;
998 let order = if let Some(ev) = msg_events.get(idx) {
1001 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
1002 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
1003 revoke_and_ack = Some(msg.clone());
1004 RAACommitmentOrder::RevokeAndACKFirst
1006 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
1007 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
1008 commitment_update = Some(updates.clone());
1009 RAACommitmentOrder::CommitmentFirst
1011 _ => panic!("Unexpected event"),
1014 RAACommitmentOrder::CommitmentFirst
1017 if let Some(ev) = msg_events.get(idx) {
1019 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
1020 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
1021 assert!(revoke_and_ack.is_none());
1022 revoke_and_ack = Some(msg.clone());
1024 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
1025 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
1026 assert!(commitment_update.is_none());
1027 commitment_update = Some(updates.clone());
1029 _ => panic!("Unexpected event"),
1033 (funding_locked, revoke_and_ack, commitment_update, order)
1038 /// pending_htlc_adds includes both the holding cell and in-flight update_add_htlcs, whereas
1039 /// for claims/fails they are separated out.
1040 pub fn reconnect_nodes(node_a: &Node, node_b: &Node, send_funding_locked: (bool, bool), pending_htlc_adds: (i64, i64), pending_htlc_claims: (usize, usize), pending_cell_htlc_claims: (usize, usize), pending_cell_htlc_fails: (usize, usize), pending_raa: (bool, bool)) {
1041 node_a.node.peer_connected(&node_b.node.get_our_node_id());
1042 let reestablish_1 = get_chan_reestablish_msgs!(node_a, node_b);
1043 node_b.node.peer_connected(&node_a.node.get_our_node_id());
1044 let reestablish_2 = get_chan_reestablish_msgs!(node_b, node_a);
1046 if send_funding_locked.0 {
1047 // If a expects a funding_locked, it better not think it has received a revoke_and_ack
1049 for reestablish in reestablish_1.iter() {
1050 assert_eq!(reestablish.next_remote_commitment_number, 0);
1053 if send_funding_locked.1 {
1054 // If b expects a funding_locked, it better not think it has received a revoke_and_ack
1056 for reestablish in reestablish_2.iter() {
1057 assert_eq!(reestablish.next_remote_commitment_number, 0);
1060 if send_funding_locked.0 || send_funding_locked.1 {
1061 // If we expect any funding_locked's, both sides better have set
1062 // next_local_commitment_number to 1
1063 for reestablish in reestablish_1.iter() {
1064 assert_eq!(reestablish.next_local_commitment_number, 1);
1066 for reestablish in reestablish_2.iter() {
1067 assert_eq!(reestablish.next_local_commitment_number, 1);
1071 let mut resp_1 = Vec::new();
1072 for msg in reestablish_1 {
1073 node_b.node.handle_channel_reestablish(&node_a.node.get_our_node_id(), &msg).unwrap();
1074 resp_1.push(handle_chan_reestablish_msgs!(node_b, node_a));
1076 if pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
1077 check_added_monitors!(node_b, 1);
1079 check_added_monitors!(node_b, 0);
1082 let mut resp_2 = Vec::new();
1083 for msg in reestablish_2 {
1084 node_a.node.handle_channel_reestablish(&node_b.node.get_our_node_id(), &msg).unwrap();
1085 resp_2.push(handle_chan_reestablish_msgs!(node_a, node_b));
1087 if pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
1088 check_added_monitors!(node_a, 1);
1090 check_added_monitors!(node_a, 0);
1093 // We don't yet support both needing updates, as that would require a different commitment dance:
1094 assert!((pending_htlc_adds.0 == 0 && pending_htlc_claims.0 == 0 && pending_cell_htlc_claims.0 == 0 && pending_cell_htlc_fails.0 == 0) ||
1095 (pending_htlc_adds.1 == 0 && pending_htlc_claims.1 == 0 && pending_cell_htlc_claims.1 == 0 && pending_cell_htlc_fails.1 == 0));
1097 for chan_msgs in resp_1.drain(..) {
1098 if send_funding_locked.0 {
1099 node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
1100 let announcement_event = node_a.node.get_and_clear_pending_msg_events();
1101 if !announcement_event.is_empty() {
1102 assert_eq!(announcement_event.len(), 1);
1103 if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
1104 //TODO: Test announcement_sigs re-sending
1105 } else { panic!("Unexpected event!"); }
1108 assert!(chan_msgs.0.is_none());
1111 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
1112 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
1113 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
1114 check_added_monitors!(node_a, 1);
1116 assert!(chan_msgs.1.is_none());
1118 if pending_htlc_adds.0 != 0 || pending_htlc_claims.0 != 0 || pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
1119 let commitment_update = chan_msgs.2.unwrap();
1120 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
1121 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.0 as usize);
1123 assert!(commitment_update.update_add_htlcs.is_empty());
1125 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
1126 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
1127 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
1128 for update_add in commitment_update.update_add_htlcs {
1129 node_a.node.handle_update_add_htlc(&node_b.node.get_our_node_id(), &update_add).unwrap();
1131 for update_fulfill in commitment_update.update_fulfill_htlcs {
1132 node_a.node.handle_update_fulfill_htlc(&node_b.node.get_our_node_id(), &update_fulfill).unwrap();
1134 for update_fail in commitment_update.update_fail_htlcs {
1135 node_a.node.handle_update_fail_htlc(&node_b.node.get_our_node_id(), &update_fail).unwrap();
1138 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
1139 commitment_signed_dance!(node_a, node_b, commitment_update.commitment_signed, false);
1141 node_a.node.handle_commitment_signed(&node_b.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
1142 check_added_monitors!(node_a, 1);
1143 let as_revoke_and_ack = get_event_msg!(node_a, MessageSendEvent::SendRevokeAndACK, node_b.node.get_our_node_id());
1144 // No commitment_signed so get_event_msg's assert(len == 1) passes
1145 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
1146 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
1147 check_added_monitors!(node_b, 1);
1150 assert!(chan_msgs.2.is_none());
1154 for chan_msgs in resp_2.drain(..) {
1155 if send_funding_locked.1 {
1156 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
1157 let announcement_event = node_b.node.get_and_clear_pending_msg_events();
1158 if !announcement_event.is_empty() {
1159 assert_eq!(announcement_event.len(), 1);
1160 if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
1161 //TODO: Test announcement_sigs re-sending
1162 } else { panic!("Unexpected event!"); }
1165 assert!(chan_msgs.0.is_none());
1168 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
1169 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
1170 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
1171 check_added_monitors!(node_b, 1);
1173 assert!(chan_msgs.1.is_none());
1175 if pending_htlc_adds.1 != 0 || pending_htlc_claims.1 != 0 || pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
1176 let commitment_update = chan_msgs.2.unwrap();
1177 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
1178 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.1 as usize);
1180 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
1181 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
1182 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
1183 for update_add in commitment_update.update_add_htlcs {
1184 node_b.node.handle_update_add_htlc(&node_a.node.get_our_node_id(), &update_add).unwrap();
1186 for update_fulfill in commitment_update.update_fulfill_htlcs {
1187 node_b.node.handle_update_fulfill_htlc(&node_a.node.get_our_node_id(), &update_fulfill).unwrap();
1189 for update_fail in commitment_update.update_fail_htlcs {
1190 node_b.node.handle_update_fail_htlc(&node_a.node.get_our_node_id(), &update_fail).unwrap();
1193 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
1194 commitment_signed_dance!(node_b, node_a, commitment_update.commitment_signed, false);
1196 node_b.node.handle_commitment_signed(&node_a.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
1197 check_added_monitors!(node_b, 1);
1198 let bs_revoke_and_ack = get_event_msg!(node_b, MessageSendEvent::SendRevokeAndACK, node_a.node.get_our_node_id());
1199 // No commitment_signed so get_event_msg's assert(len == 1) passes
1200 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
1201 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
1202 check_added_monitors!(node_a, 1);
1205 assert!(chan_msgs.2.is_none());