1 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
2 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
3 //! claim outputs on-chain.
5 use chain::chaininterface;
6 use chain::transaction::OutPoint;
7 use chain::chaininterface::{ChainListener, ChainWatchInterface};
8 use chain::keysinterface::{KeysInterface, SpendableOutputDescriptor};
9 use chain::keysinterface;
10 use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
11 use ln::channelmanager::{ChannelManager,ChannelManagerReadArgs,HTLCForwardInfo,RAACommitmentOrder, PaymentPreimage, PaymentHash};
12 use ln::channelmonitor::{ChannelMonitor, ChannelMonitorUpdateErr, CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS, ManyChannelMonitor};
13 use ln::channel::{ACCEPTED_HTLC_SCRIPT_WEIGHT, OFFERED_HTLC_SCRIPT_WEIGHT};
15 use ln::router::{Route, RouteHop, Router};
17 use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler,HTLCFailChannelUpdate};
19 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
20 use util::errors::APIError;
21 use util::logger::Logger;
22 use util::ser::{Writeable, Writer, ReadableArgs};
23 use util::config::UserConfig;
25 use bitcoin::util::hash::{BitcoinHash, Sha256dHash};
26 use bitcoin::util::bip143;
27 use bitcoin::util::address::Address;
28 use bitcoin::util::bip32::{ChildNumber, ExtendedPubKey, ExtendedPrivKey};
29 use bitcoin::blockdata::block::{Block, BlockHeader};
30 use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType};
31 use bitcoin::blockdata::script::{Builder, Script};
32 use bitcoin::blockdata::opcodes;
33 use bitcoin::blockdata::constants::genesis_block;
34 use bitcoin::network::constants::Network;
36 use bitcoin_hashes::sha256::Hash as Sha256;
37 use bitcoin_hashes::Hash;
39 use secp256k1::{Secp256k1, Message};
40 use secp256k1::key::{PublicKey,SecretKey};
42 use rand::{thread_rng,Rng};
44 use std::cell::RefCell;
45 use std::collections::{BTreeSet, HashMap, HashSet};
46 use std::default::Default;
48 use std::sync::{Arc, Mutex};
49 use std::sync::atomic::Ordering;
50 use std::time::Instant;
53 const CHAN_CONFIRM_DEPTH: u32 = 100;
54 fn confirm_transaction(chain: &chaininterface::ChainWatchInterfaceUtil, tx: &Transaction, chan_id: u32) {
55 assert!(chain.does_match_tx(tx));
56 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
57 chain.block_connected_checked(&header, 1, &[tx; 1], &[chan_id; 1]);
58 for i in 2..CHAN_CONFIRM_DEPTH {
59 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
60 chain.block_connected_checked(&header, i, &[tx; 0], &[0; 0]);
65 chain_monitor: Arc<chaininterface::ChainWatchInterfaceUtil>,
66 tx_broadcaster: Arc<test_utils::TestBroadcaster>,
67 chan_monitor: Arc<test_utils::TestChannelMonitor>,
68 keys_manager: Arc<test_utils::TestKeysInterface>,
69 node: Arc<ChannelManager>,
72 network_payment_count: Rc<RefCell<u8>>,
73 network_chan_count: Rc<RefCell<u32>>,
77 if !::std::thread::panicking() {
78 // Check that we processed all pending events
79 assert!(self.node.get_and_clear_pending_msg_events().is_empty());
80 assert!(self.node.get_and_clear_pending_events().is_empty());
81 assert!(self.chan_monitor.added_monitors.lock().unwrap().is_empty());
86 fn create_chan_between_nodes(node_a: &Node, node_b: &Node) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
87 create_chan_between_nodes_with_value(node_a, node_b, 100000, 10001)
90 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) {
91 let (funding_locked, channel_id, tx) = create_chan_between_nodes_with_value_a(node_a, node_b, channel_value, push_msat);
92 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(node_a, node_b, &funding_locked);
93 (announcement, as_update, bs_update, channel_id, tx)
96 macro_rules! get_revoke_commit_msgs {
97 ($node: expr, $node_id: expr) => {
99 let events = $node.node.get_and_clear_pending_msg_events();
100 assert_eq!(events.len(), 2);
102 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
103 assert_eq!(*node_id, $node_id);
106 _ => panic!("Unexpected event"),
108 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
109 assert_eq!(*node_id, $node_id);
110 assert!(updates.update_add_htlcs.is_empty());
111 assert!(updates.update_fulfill_htlcs.is_empty());
112 assert!(updates.update_fail_htlcs.is_empty());
113 assert!(updates.update_fail_malformed_htlcs.is_empty());
114 assert!(updates.update_fee.is_none());
115 updates.commitment_signed.clone()
117 _ => panic!("Unexpected event"),
123 macro_rules! get_event_msg {
124 ($node: expr, $event_type: path, $node_id: expr) => {
126 let events = $node.node.get_and_clear_pending_msg_events();
127 assert_eq!(events.len(), 1);
129 $event_type { ref node_id, ref msg } => {
130 assert_eq!(*node_id, $node_id);
133 _ => panic!("Unexpected event"),
139 macro_rules! get_htlc_update_msgs {
140 ($node: expr, $node_id: expr) => {
142 let events = $node.node.get_and_clear_pending_msg_events();
143 assert_eq!(events.len(), 1);
145 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
146 assert_eq!(*node_id, $node_id);
149 _ => panic!("Unexpected event"),
155 macro_rules! get_feerate {
156 ($node: expr, $channel_id: expr) => {
158 let chan_lock = $node.node.channel_state.lock().unwrap();
159 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
166 fn create_chan_between_nodes_with_value_init(node_a: &Node, node_b: &Node, channel_value: u64, push_msat: u64) -> Transaction {
167 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42).unwrap();
168 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();
169 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();
171 let chan_id = *node_a.network_chan_count.borrow();
175 let events_2 = node_a.node.get_and_clear_pending_events();
176 assert_eq!(events_2.len(), 1);
178 Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
179 assert_eq!(*channel_value_satoshis, channel_value);
180 assert_eq!(user_channel_id, 42);
182 tx = Transaction { version: chan_id as u32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
183 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
185 funding_output = OutPoint::new(tx.txid(), 0);
187 node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
188 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
189 assert_eq!(added_monitors.len(), 1);
190 assert_eq!(added_monitors[0].0, funding_output);
191 added_monitors.clear();
193 _ => panic!("Unexpected event"),
196 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();
198 let mut added_monitors = node_b.chan_monitor.added_monitors.lock().unwrap();
199 assert_eq!(added_monitors.len(), 1);
200 assert_eq!(added_monitors[0].0, funding_output);
201 added_monitors.clear();
204 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();
206 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
207 assert_eq!(added_monitors.len(), 1);
208 assert_eq!(added_monitors[0].0, funding_output);
209 added_monitors.clear();
212 let events_4 = node_a.node.get_and_clear_pending_events();
213 assert_eq!(events_4.len(), 1);
215 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
216 assert_eq!(user_channel_id, 42);
217 assert_eq!(*funding_txo, funding_output);
219 _ => panic!("Unexpected event"),
225 fn create_chan_between_nodes_with_value_confirm(node_a: &Node, node_b: &Node, tx: &Transaction) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32]) {
226 confirm_transaction(&node_b.chain_monitor, &tx, tx.version);
227 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();
231 confirm_transaction(&node_a.chain_monitor, &tx, tx.version);
232 let events_6 = node_a.node.get_and_clear_pending_msg_events();
233 assert_eq!(events_6.len(), 2);
234 ((match events_6[0] {
235 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
236 channel_id = msg.channel_id.clone();
237 assert_eq!(*node_id, node_b.node.get_our_node_id());
240 _ => panic!("Unexpected event"),
241 }, match events_6[1] {
242 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
243 assert_eq!(*node_id, node_b.node.get_our_node_id());
246 _ => panic!("Unexpected event"),
250 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) {
251 let tx = create_chan_between_nodes_with_value_init(node_a, node_b, channel_value, push_msat);
252 let (msgs, chan_id) = create_chan_between_nodes_with_value_confirm(node_a, node_b, &tx);
256 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) {
257 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &as_funding_msgs.0).unwrap();
258 let bs_announcement_sigs = get_event_msg!(node_b, MessageSendEvent::SendAnnouncementSignatures, node_a.node.get_our_node_id());
259 node_b.node.handle_announcement_signatures(&node_a.node.get_our_node_id(), &as_funding_msgs.1).unwrap();
261 let events_7 = node_b.node.get_and_clear_pending_msg_events();
262 assert_eq!(events_7.len(), 1);
263 let (announcement, bs_update) = match events_7[0] {
264 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
267 _ => panic!("Unexpected event"),
270 node_a.node.handle_announcement_signatures(&node_b.node.get_our_node_id(), &bs_announcement_sigs).unwrap();
271 let events_8 = node_a.node.get_and_clear_pending_msg_events();
272 assert_eq!(events_8.len(), 1);
273 let as_update = match events_8[0] {
274 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
275 assert!(*announcement == *msg);
276 assert_eq!(update_msg.contents.short_channel_id, announcement.contents.short_channel_id);
277 assert_eq!(update_msg.contents.short_channel_id, bs_update.contents.short_channel_id);
280 _ => panic!("Unexpected event"),
283 *node_a.network_chan_count.borrow_mut() += 1;
285 ((*announcement).clone(), (*as_update).clone(), (*bs_update).clone())
288 fn create_announced_chan_between_nodes(nodes: &Vec<Node>, a: usize, b: usize) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
289 create_announced_chan_between_nodes_with_value(nodes, a, b, 100000, 10001)
292 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) {
293 let chan_announcement = create_chan_between_nodes_with_value(&nodes[a], &nodes[b], channel_value, push_msat);
295 assert!(node.router.handle_channel_announcement(&chan_announcement.0).unwrap());
296 node.router.handle_channel_update(&chan_announcement.1).unwrap();
297 node.router.handle_channel_update(&chan_announcement.2).unwrap();
299 (chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
302 macro_rules! check_spends {
303 ($tx: expr, $spends_tx: expr) => {
305 let mut funding_tx_map = HashMap::new();
306 let spends_tx = $spends_tx;
307 funding_tx_map.insert(spends_tx.txid(), spends_tx);
308 $tx.verify(&funding_tx_map).unwrap();
313 macro_rules! get_closing_signed_broadcast {
314 ($node: expr, $dest_pubkey: expr) => {
316 let events = $node.get_and_clear_pending_msg_events();
317 assert!(events.len() == 1 || events.len() == 2);
318 (match events[events.len() - 1] {
319 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
320 assert_eq!(msg.contents.flags & 2, 2);
323 _ => panic!("Unexpected event"),
324 }, if events.len() == 2 {
326 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
327 assert_eq!(*node_id, $dest_pubkey);
330 _ => panic!("Unexpected event"),
337 macro_rules! check_closed_broadcast {
339 let events = $node.node.get_and_clear_pending_msg_events();
340 assert_eq!(events.len(), 1);
342 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
343 assert_eq!(msg.contents.flags & 2, 2);
345 _ => panic!("Unexpected event"),
350 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) {
351 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) };
352 let (node_b, broadcaster_b) = if close_inbound_first { (&outbound_node.node, &outbound_node.tx_broadcaster) } else { (&inbound_node.node, &inbound_node.tx_broadcaster) };
355 node_a.close_channel(channel_id).unwrap();
356 node_b.handle_shutdown(&node_a.get_our_node_id(), &get_event_msg!(struct_a, MessageSendEvent::SendShutdown, node_b.get_our_node_id())).unwrap();
358 let events_1 = node_b.get_and_clear_pending_msg_events();
359 assert!(events_1.len() >= 1);
360 let shutdown_b = match events_1[0] {
361 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
362 assert_eq!(node_id, &node_a.get_our_node_id());
365 _ => panic!("Unexpected event"),
368 let closing_signed_b = if !close_inbound_first {
369 assert_eq!(events_1.len(), 1);
372 Some(match events_1[1] {
373 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
374 assert_eq!(node_id, &node_a.get_our_node_id());
377 _ => panic!("Unexpected event"),
381 node_a.handle_shutdown(&node_b.get_our_node_id(), &shutdown_b).unwrap();
382 let (as_update, bs_update) = if close_inbound_first {
383 assert!(node_a.get_and_clear_pending_msg_events().is_empty());
384 node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
385 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
386 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
387 let (as_update, closing_signed_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
389 node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap()).unwrap();
390 let (bs_update, none_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
391 assert!(none_b.is_none());
392 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
393 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
394 (as_update, bs_update)
396 let closing_signed_a = get_event_msg!(struct_a, MessageSendEvent::SendClosingSigned, node_b.get_our_node_id());
398 node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a).unwrap();
399 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
400 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
401 let (bs_update, closing_signed_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
403 node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
404 let (as_update, none_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
405 assert!(none_a.is_none());
406 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
407 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
408 (as_update, bs_update)
410 assert_eq!(tx_a, tx_b);
411 check_spends!(tx_a, funding_tx);
413 (as_update, bs_update, tx_a)
418 msgs: Vec<msgs::UpdateAddHTLC>,
419 commitment_msg: msgs::CommitmentSigned,
422 fn from_commitment_update(node_id: PublicKey, updates: msgs::CommitmentUpdate) -> SendEvent {
423 assert!(updates.update_fulfill_htlcs.is_empty());
424 assert!(updates.update_fail_htlcs.is_empty());
425 assert!(updates.update_fail_malformed_htlcs.is_empty());
426 assert!(updates.update_fee.is_none());
427 SendEvent { node_id: node_id, msgs: updates.update_add_htlcs, commitment_msg: updates.commitment_signed }
430 fn from_event(event: MessageSendEvent) -> SendEvent {
432 MessageSendEvent::UpdateHTLCs { node_id, updates } => SendEvent::from_commitment_update(node_id, updates),
433 _ => panic!("Unexpected event type!"),
437 fn from_node(node: &Node) -> SendEvent {
438 let mut events = node.node.get_and_clear_pending_msg_events();
439 assert_eq!(events.len(), 1);
440 SendEvent::from_event(events.pop().unwrap())
444 macro_rules! check_added_monitors {
445 ($node: expr, $count: expr) => {
447 let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
448 assert_eq!(added_monitors.len(), $count);
449 added_monitors.clear();
454 macro_rules! commitment_signed_dance {
455 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */) => {
457 check_added_monitors!($node_a, 0);
458 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
459 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
460 check_added_monitors!($node_a, 1);
461 commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, false);
464 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */, true /* return last RAA */) => {
466 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!($node_a, $node_b.node.get_our_node_id());
467 check_added_monitors!($node_b, 0);
468 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
469 $node_b.node.handle_revoke_and_ack(&$node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
470 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
471 check_added_monitors!($node_b, 1);
472 $node_b.node.handle_commitment_signed(&$node_a.node.get_our_node_id(), &as_commitment_signed).unwrap();
473 let (bs_revoke_and_ack, extra_msg_option) = {
474 let events = $node_b.node.get_and_clear_pending_msg_events();
475 assert!(events.len() <= 2);
477 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
478 assert_eq!(*node_id, $node_a.node.get_our_node_id());
481 _ => panic!("Unexpected event"),
482 }, events.get(1).map(|e| e.clone()))
484 check_added_monitors!($node_b, 1);
486 assert!($node_a.node.get_and_clear_pending_events().is_empty());
487 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
489 (extra_msg_option, bs_revoke_and_ack)
492 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */, false /* return extra message */, true /* return last RAA */) => {
494 check_added_monitors!($node_a, 0);
495 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
496 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
497 check_added_monitors!($node_a, 1);
498 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
499 assert!(extra_msg_option.is_none());
503 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */) => {
505 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
506 $node_a.node.handle_revoke_and_ack(&$node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
507 check_added_monitors!($node_a, 1);
511 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, false /* no extra message */) => {
513 assert!(commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true).is_none());
516 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr) => {
518 commitment_signed_dance!($node_a, $node_b, $commitment_signed, $fail_backwards, true);
520 expect_pending_htlcs_forwardable!($node_a);
521 check_added_monitors!($node_a, 1);
523 let channel_state = $node_a.node.channel_state.lock().unwrap();
524 assert_eq!(channel_state.pending_msg_events.len(), 1);
525 if let MessageSendEvent::UpdateHTLCs { ref node_id, .. } = channel_state.pending_msg_events[0] {
526 assert_ne!(*node_id, $node_b.node.get_our_node_id());
527 } else { panic!("Unexpected event"); }
529 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
535 macro_rules! get_payment_preimage_hash {
538 let payment_preimage = PaymentPreimage([*$node.network_payment_count.borrow(); 32]);
539 *$node.network_payment_count.borrow_mut() += 1;
540 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner());
541 (payment_preimage, payment_hash)
546 macro_rules! expect_pending_htlcs_forwardable {
548 let events = $node.node.get_and_clear_pending_events();
549 assert_eq!(events.len(), 1);
551 Event::PendingHTLCsForwardable { .. } => { },
552 _ => panic!("Unexpected event"),
554 let node_ref: &Node = &$node;
555 node_ref.node.channel_state.lock().unwrap().next_forward = Instant::now();
556 $node.node.process_pending_htlc_forwards();
560 fn send_along_route_with_hash(origin_node: &Node, route: Route, expected_route: &[&Node], recv_value: u64, our_payment_hash: PaymentHash) {
561 let mut payment_event = {
562 origin_node.node.send_payment(route, our_payment_hash).unwrap();
563 check_added_monitors!(origin_node, 1);
565 let mut events = origin_node.node.get_and_clear_pending_msg_events();
566 assert_eq!(events.len(), 1);
567 SendEvent::from_event(events.remove(0))
569 let mut prev_node = origin_node;
571 for (idx, &node) in expected_route.iter().enumerate() {
572 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
574 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
575 check_added_monitors!(node, 0);
576 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
578 expect_pending_htlcs_forwardable!(node);
580 if idx == expected_route.len() - 1 {
581 let events_2 = node.node.get_and_clear_pending_events();
582 assert_eq!(events_2.len(), 1);
584 Event::PaymentReceived { ref payment_hash, amt } => {
585 assert_eq!(our_payment_hash, *payment_hash);
586 assert_eq!(amt, recv_value);
588 _ => panic!("Unexpected event"),
591 let mut events_2 = node.node.get_and_clear_pending_msg_events();
592 assert_eq!(events_2.len(), 1);
593 check_added_monitors!(node, 1);
594 payment_event = SendEvent::from_event(events_2.remove(0));
595 assert_eq!(payment_event.msgs.len(), 1);
602 fn send_along_route(origin_node: &Node, route: Route, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
603 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(origin_node);
604 send_along_route_with_hash(origin_node, route, expected_route, recv_value, our_payment_hash);
605 (our_payment_preimage, our_payment_hash)
608 fn claim_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_preimage: PaymentPreimage) {
609 assert!(expected_route.last().unwrap().node.claim_funds(our_payment_preimage));
610 check_added_monitors!(expected_route.last().unwrap(), 1);
612 let mut next_msgs: Option<(msgs::UpdateFulfillHTLC, msgs::CommitmentSigned)> = None;
613 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
614 macro_rules! get_next_msgs {
617 let events = $node.node.get_and_clear_pending_msg_events();
618 assert_eq!(events.len(), 1);
620 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 } } => {
621 assert!(update_add_htlcs.is_empty());
622 assert_eq!(update_fulfill_htlcs.len(), 1);
623 assert!(update_fail_htlcs.is_empty());
624 assert!(update_fail_malformed_htlcs.is_empty());
625 assert!(update_fee.is_none());
626 expected_next_node = node_id.clone();
627 Some((update_fulfill_htlcs[0].clone(), commitment_signed.clone()))
629 _ => panic!("Unexpected event"),
635 macro_rules! last_update_fulfill_dance {
636 ($node: expr, $prev_node: expr) => {
638 $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
639 check_added_monitors!($node, 0);
640 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
641 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
645 macro_rules! mid_update_fulfill_dance {
646 ($node: expr, $prev_node: expr, $new_msgs: expr) => {
648 $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
649 check_added_monitors!($node, 1);
650 let new_next_msgs = if $new_msgs {
651 get_next_msgs!($node)
653 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
656 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
657 next_msgs = new_next_msgs;
662 let mut prev_node = expected_route.last().unwrap();
663 for (idx, node) in expected_route.iter().rev().enumerate() {
664 assert_eq!(expected_next_node, node.node.get_our_node_id());
665 let update_next_msgs = !skip_last || idx != expected_route.len() - 1;
666 if next_msgs.is_some() {
667 mid_update_fulfill_dance!(node, prev_node, update_next_msgs);
668 } else if update_next_msgs {
669 next_msgs = get_next_msgs!(node);
671 assert!(node.node.get_and_clear_pending_msg_events().is_empty());
673 if !skip_last && idx == expected_route.len() - 1 {
674 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
681 last_update_fulfill_dance!(origin_node, expected_route.first().unwrap());
682 let events = origin_node.node.get_and_clear_pending_events();
683 assert_eq!(events.len(), 1);
685 Event::PaymentSent { payment_preimage } => {
686 assert_eq!(payment_preimage, our_payment_preimage);
688 _ => panic!("Unexpected event"),
693 fn claim_payment(origin_node: &Node, expected_route: &[&Node], our_payment_preimage: PaymentPreimage) {
694 claim_payment_along_route(origin_node, expected_route, false, our_payment_preimage);
697 const TEST_FINAL_CLTV: u32 = 32;
699 fn route_payment(origin_node: &Node, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
700 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();
701 assert_eq!(route.hops.len(), expected_route.len());
702 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
703 assert_eq!(hop.pubkey, node.node.get_our_node_id());
706 send_along_route(origin_node, route, expected_route, recv_value)
709 fn route_over_limit(origin_node: &Node, expected_route: &[&Node], recv_value: u64) {
710 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();
711 assert_eq!(route.hops.len(), expected_route.len());
712 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
713 assert_eq!(hop.pubkey, node.node.get_our_node_id());
716 let (_, our_payment_hash) = get_payment_preimage_hash!(origin_node);
718 let err = origin_node.node.send_payment(route, our_payment_hash).err().unwrap();
720 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
721 _ => panic!("Unknown error variants"),
725 fn send_payment(origin: &Node, expected_route: &[&Node], recv_value: u64) {
726 let our_payment_preimage = route_payment(&origin, expected_route, recv_value).0;
727 claim_payment(&origin, expected_route, our_payment_preimage);
730 fn fail_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_hash: PaymentHash) {
731 assert!(expected_route.last().unwrap().node.fail_htlc_backwards(&our_payment_hash, 0));
732 expect_pending_htlcs_forwardable!(expected_route.last().unwrap());
733 check_added_monitors!(expected_route.last().unwrap(), 1);
735 let mut next_msgs: Option<(msgs::UpdateFailHTLC, msgs::CommitmentSigned)> = None;
736 macro_rules! update_fail_dance {
737 ($node: expr, $prev_node: expr, $last_node: expr) => {
739 $node.node.handle_update_fail_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
740 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, !$last_node);
741 if skip_last && $last_node {
742 expect_pending_htlcs_forwardable!($node);
748 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
749 let mut prev_node = expected_route.last().unwrap();
750 for (idx, node) in expected_route.iter().rev().enumerate() {
751 assert_eq!(expected_next_node, node.node.get_our_node_id());
752 if next_msgs.is_some() {
753 // We may be the "last node" for the purpose of the commitment dance if we're
754 // skipping the last node (implying it is disconnected) and we're the
755 // second-to-last node!
756 update_fail_dance!(node, prev_node, skip_last && idx == expected_route.len() - 1);
759 let events = node.node.get_and_clear_pending_msg_events();
760 if !skip_last || idx != expected_route.len() - 1 {
761 assert_eq!(events.len(), 1);
763 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 } } => {
764 assert!(update_add_htlcs.is_empty());
765 assert!(update_fulfill_htlcs.is_empty());
766 assert_eq!(update_fail_htlcs.len(), 1);
767 assert!(update_fail_malformed_htlcs.is_empty());
768 assert!(update_fee.is_none());
769 expected_next_node = node_id.clone();
770 next_msgs = Some((update_fail_htlcs[0].clone(), commitment_signed.clone()));
772 _ => panic!("Unexpected event"),
775 assert!(events.is_empty());
777 if !skip_last && idx == expected_route.len() - 1 {
778 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
785 update_fail_dance!(origin_node, expected_route.first().unwrap(), true);
787 let events = origin_node.node.get_and_clear_pending_events();
788 assert_eq!(events.len(), 1);
790 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
791 assert_eq!(payment_hash, our_payment_hash);
792 assert!(rejected_by_dest);
794 _ => panic!("Unexpected event"),
799 fn fail_payment(origin_node: &Node, expected_route: &[&Node], our_payment_hash: PaymentHash) {
800 fail_payment_along_route(origin_node, expected_route, false, our_payment_hash);
803 fn create_network(node_count: usize) -> Vec<Node> {
804 let mut nodes = Vec::new();
805 let mut rng = thread_rng();
806 let secp_ctx = Secp256k1::new();
808 let chan_count = Rc::new(RefCell::new(0));
809 let payment_count = Rc::new(RefCell::new(0));
811 for i in 0..node_count {
812 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::with_id(format!("node {}", i)));
813 let feeest = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 });
814 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
815 let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())});
816 let mut seed = [0; 32];
817 rng.fill_bytes(&mut seed);
818 let keys_manager = Arc::new(test_utils::TestKeysInterface::new(&seed, Network::Testnet, Arc::clone(&logger)));
819 let chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(chain_monitor.clone(), tx_broadcaster.clone(), logger.clone()));
820 let mut config = UserConfig::new();
821 config.channel_options.announced_channel = true;
822 config.channel_limits.force_announced_channel_preference = false;
823 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();
824 let router = Router::new(PublicKey::from_secret_key(&secp_ctx, &keys_manager.get_node_secret()), chain_monitor.clone(), Arc::clone(&logger));
825 nodes.push(Node { chain_monitor, tx_broadcaster, chan_monitor, node, router, keys_manager, node_seed: seed,
826 network_payment_count: payment_count.clone(),
827 network_chan_count: chan_count.clone(),
835 fn test_async_inbound_update_fee() {
836 let mut nodes = create_network(2);
837 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
838 let channel_id = chan.2;
841 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
845 // send (1) commitment_signed -.
846 // <- update_add_htlc/commitment_signed
847 // send (2) RAA (awaiting remote revoke) -.
848 // (1) commitment_signed is delivered ->
849 // .- send (3) RAA (awaiting remote revoke)
850 // (2) RAA is delivered ->
851 // .- send (4) commitment_signed
852 // <- (3) RAA is delivered
853 // send (5) commitment_signed -.
854 // <- (4) commitment_signed is delivered
856 // (5) commitment_signed is delivered ->
858 // (6) RAA is delivered ->
860 // First nodes[0] generates an update_fee
861 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
862 check_added_monitors!(nodes[0], 1);
864 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
865 assert_eq!(events_0.len(), 1);
866 let (update_msg, commitment_signed) = match events_0[0] { // (1)
867 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
868 (update_fee.as_ref(), commitment_signed)
870 _ => panic!("Unexpected event"),
873 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
875 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
876 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
877 nodes[1].node.send_payment(nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV).unwrap(), our_payment_hash).unwrap();
878 check_added_monitors!(nodes[1], 1);
880 let payment_event = {
881 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
882 assert_eq!(events_1.len(), 1);
883 SendEvent::from_event(events_1.remove(0))
885 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
886 assert_eq!(payment_event.msgs.len(), 1);
888 // ...now when the messages get delivered everyone should be happy
889 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
890 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
891 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
892 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
893 check_added_monitors!(nodes[0], 1);
895 // deliver(1), generate (3):
896 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
897 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
898 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
899 check_added_monitors!(nodes[1], 1);
901 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap(); // deliver (2)
902 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
903 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
904 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
905 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
906 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
907 assert!(bs_update.update_fee.is_none()); // (4)
908 check_added_monitors!(nodes[1], 1);
910 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap(); // deliver (3)
911 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
912 assert!(as_update.update_add_htlcs.is_empty()); // (5)
913 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
914 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
915 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
916 assert!(as_update.update_fee.is_none()); // (5)
917 check_added_monitors!(nodes[0], 1);
919 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed).unwrap(); // deliver (4)
920 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
921 // only (6) so get_event_msg's assert(len == 1) passes
922 check_added_monitors!(nodes[0], 1);
924 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed).unwrap(); // deliver (5)
925 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
926 check_added_monitors!(nodes[1], 1);
928 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
929 check_added_monitors!(nodes[0], 1);
931 let events_2 = nodes[0].node.get_and_clear_pending_events();
932 assert_eq!(events_2.len(), 1);
934 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
935 _ => panic!("Unexpected event"),
938 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap(); // deliver (6)
939 check_added_monitors!(nodes[1], 1);
943 fn test_update_fee_unordered_raa() {
944 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
945 // crash in an earlier version of the update_fee patch)
946 let mut nodes = create_network(2);
947 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
948 let channel_id = chan.2;
951 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
953 // First nodes[0] generates an update_fee
954 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
955 check_added_monitors!(nodes[0], 1);
957 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
958 assert_eq!(events_0.len(), 1);
959 let update_msg = match events_0[0] { // (1)
960 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
963 _ => panic!("Unexpected event"),
966 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
968 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
969 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
970 nodes[1].node.send_payment(nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV).unwrap(), our_payment_hash).unwrap();
971 check_added_monitors!(nodes[1], 1);
973 let payment_event = {
974 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
975 assert_eq!(events_1.len(), 1);
976 SendEvent::from_event(events_1.remove(0))
978 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
979 assert_eq!(payment_event.msgs.len(), 1);
981 // ...now when the messages get delivered everyone should be happy
982 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
983 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
984 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
985 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
986 check_added_monitors!(nodes[0], 1);
988 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap(); // deliver (2)
989 check_added_monitors!(nodes[1], 1);
991 // We can't continue, sadly, because our (1) now has a bogus signature
995 fn test_multi_flight_update_fee() {
996 let nodes = create_network(2);
997 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
998 let channel_id = chan.2;
1001 // update_fee/commitment_signed ->
1002 // .- send (1) RAA and (2) commitment_signed
1003 // update_fee (never committed) ->
1004 // (3) update_fee ->
1005 // We have to manually generate the above update_fee, it is allowed by the protocol but we
1006 // don't track which updates correspond to which revoke_and_ack responses so we're in
1007 // AwaitingRAA mode and will not generate the update_fee yet.
1008 // <- (1) RAA delivered
1009 // (3) is generated and send (4) CS -.
1010 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
1011 // know the per_commitment_point to use for it.
1012 // <- (2) commitment_signed delivered
1013 // revoke_and_ack ->
1014 // B should send no response here
1015 // (4) commitment_signed delivered ->
1016 // <- RAA/commitment_signed delivered
1017 // revoke_and_ack ->
1019 // First nodes[0] generates an update_fee
1020 let initial_feerate = get_feerate!(nodes[0], channel_id);
1021 nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
1022 check_added_monitors!(nodes[0], 1);
1024 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
1025 assert_eq!(events_0.len(), 1);
1026 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
1027 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
1028 (update_fee.as_ref().unwrap(), commitment_signed)
1030 _ => panic!("Unexpected event"),
1033 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
1034 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1).unwrap();
1035 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1).unwrap();
1036 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1037 check_added_monitors!(nodes[1], 1);
1039 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
1041 nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
1042 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1043 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1045 // Create the (3) update_fee message that nodes[0] will generate before it does...
1046 let mut update_msg_2 = msgs::UpdateFee {
1047 channel_id: update_msg_1.channel_id.clone(),
1048 feerate_per_kw: (initial_feerate + 30) as u32,
1051 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
1053 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
1055 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
1057 // Deliver (1), generating (3) and (4)
1058 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg).unwrap();
1059 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1060 check_added_monitors!(nodes[0], 1);
1061 assert!(as_second_update.update_add_htlcs.is_empty());
1062 assert!(as_second_update.update_fulfill_htlcs.is_empty());
1063 assert!(as_second_update.update_fail_htlcs.is_empty());
1064 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
1065 // Check that the update_fee newly generated matches what we delivered:
1066 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
1067 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
1069 // Deliver (2) commitment_signed
1070 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
1071 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1072 check_added_monitors!(nodes[0], 1);
1073 // No commitment_signed so get_event_msg's assert(len == 1) passes
1075 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap();
1076 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1077 check_added_monitors!(nodes[1], 1);
1080 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed).unwrap();
1081 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1082 check_added_monitors!(nodes[1], 1);
1084 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
1085 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1086 check_added_monitors!(nodes[0], 1);
1088 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment).unwrap();
1089 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1090 // No commitment_signed so get_event_msg's assert(len == 1) passes
1091 check_added_monitors!(nodes[0], 1);
1093 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap();
1094 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1095 check_added_monitors!(nodes[1], 1);
1099 fn test_update_fee_vanilla() {
1100 let nodes = create_network(2);
1101 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
1102 let channel_id = chan.2;
1104 let feerate = get_feerate!(nodes[0], channel_id);
1105 nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
1106 check_added_monitors!(nodes[0], 1);
1108 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
1109 assert_eq!(events_0.len(), 1);
1110 let (update_msg, commitment_signed) = match events_0[0] {
1111 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
1112 (update_fee.as_ref(), commitment_signed)
1114 _ => panic!("Unexpected event"),
1116 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
1118 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
1119 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1120 check_added_monitors!(nodes[1], 1);
1122 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
1123 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1124 check_added_monitors!(nodes[0], 1);
1126 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
1127 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1128 // No commitment_signed so get_event_msg's assert(len == 1) passes
1129 check_added_monitors!(nodes[0], 1);
1131 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
1132 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1133 check_added_monitors!(nodes[1], 1);
1137 fn test_update_fee_that_funder_cannot_afford() {
1138 let nodes = create_network(2);
1139 let channel_value = 1888;
1140 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000);
1141 let channel_id = chan.2;
1144 nodes[0].node.update_fee(channel_id, feerate).unwrap();
1145 check_added_monitors!(nodes[0], 1);
1146 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1148 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap()).unwrap();
1150 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
1152 //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
1153 //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
1155 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1156 let chan = chan_lock.by_id.get(&channel_id).unwrap();
1158 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
1159 let num_htlcs = chan.last_local_commitment_txn[0].output.len() - 2;
1160 let total_fee: u64 = feerate * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
1161 let mut actual_fee = chan.last_local_commitment_txn[0].output.iter().fold(0, |acc, output| acc + output.value);
1162 actual_fee = channel_value - actual_fee;
1163 assert_eq!(total_fee, actual_fee);
1166 //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
1167 //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
1168 nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
1169 check_added_monitors!(nodes[0], 1);
1171 let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1173 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap()).unwrap();
1175 //While producing the commitment_signed response after handling a received update_fee request the
1176 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
1177 //Should produce and error.
1178 let err = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed).unwrap_err();
1180 assert!(match err.err {
1181 "Funding remote cannot afford proposed new fee" => true,
1185 //clear the message we could not handle
1186 nodes[1].node.get_and_clear_pending_msg_events();
1190 fn test_update_fee_with_fundee_update_add_htlc() {
1191 let mut nodes = create_network(2);
1192 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
1193 let channel_id = chan.2;
1196 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1198 let feerate = get_feerate!(nodes[0], channel_id);
1199 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
1200 check_added_monitors!(nodes[0], 1);
1202 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
1203 assert_eq!(events_0.len(), 1);
1204 let (update_msg, commitment_signed) = match events_0[0] {
1205 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
1206 (update_fee.as_ref(), commitment_signed)
1208 _ => panic!("Unexpected event"),
1210 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
1211 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
1212 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1213 check_added_monitors!(nodes[1], 1);
1215 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 800000, TEST_FINAL_CLTV).unwrap();
1217 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
1219 // nothing happens since node[1] is in AwaitingRemoteRevoke
1220 nodes[1].node.send_payment(route, our_payment_hash).unwrap();
1222 let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
1223 assert_eq!(added_monitors.len(), 0);
1224 added_monitors.clear();
1226 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1227 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1228 // node[1] has nothing to do
1230 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
1231 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1232 check_added_monitors!(nodes[0], 1);
1234 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
1235 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1236 // No commitment_signed so get_event_msg's assert(len == 1) passes
1237 check_added_monitors!(nodes[0], 1);
1238 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
1239 check_added_monitors!(nodes[1], 1);
1240 // AwaitingRemoteRevoke ends here
1242 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1243 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
1244 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
1245 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
1246 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
1247 assert_eq!(commitment_update.update_fee.is_none(), true);
1249 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]).unwrap();
1250 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
1251 check_added_monitors!(nodes[0], 1);
1252 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1254 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke).unwrap();
1255 check_added_monitors!(nodes[1], 1);
1256 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1258 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed).unwrap();
1259 check_added_monitors!(nodes[1], 1);
1260 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1261 // No commitment_signed so get_event_msg's assert(len == 1) passes
1263 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke).unwrap();
1264 check_added_monitors!(nodes[0], 1);
1265 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1267 expect_pending_htlcs_forwardable!(nodes[0]);
1269 let events = nodes[0].node.get_and_clear_pending_events();
1270 assert_eq!(events.len(), 1);
1272 Event::PaymentReceived { .. } => { },
1273 _ => panic!("Unexpected event"),
1276 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
1278 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
1279 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
1280 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
1284 fn test_update_fee() {
1285 let nodes = create_network(2);
1286 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
1287 let channel_id = chan.2;
1290 // (1) update_fee/commitment_signed ->
1291 // <- (2) revoke_and_ack
1292 // .- send (3) commitment_signed
1293 // (4) update_fee/commitment_signed ->
1294 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
1295 // <- (3) commitment_signed delivered
1296 // send (6) revoke_and_ack -.
1297 // <- (5) deliver revoke_and_ack
1298 // (6) deliver revoke_and_ack ->
1299 // .- send (7) commitment_signed in response to (4)
1300 // <- (7) deliver commitment_signed
1301 // revoke_and_ack ->
1303 // Create and deliver (1)...
1304 let feerate = get_feerate!(nodes[0], channel_id);
1305 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
1306 check_added_monitors!(nodes[0], 1);
1308 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
1309 assert_eq!(events_0.len(), 1);
1310 let (update_msg, commitment_signed) = match events_0[0] {
1311 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
1312 (update_fee.as_ref(), commitment_signed)
1314 _ => panic!("Unexpected event"),
1316 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
1318 // Generate (2) and (3):
1319 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
1320 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1321 check_added_monitors!(nodes[1], 1);
1324 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
1325 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1326 check_added_monitors!(nodes[0], 1);
1328 // Create and deliver (4)...
1329 nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
1330 check_added_monitors!(nodes[0], 1);
1331 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
1332 assert_eq!(events_0.len(), 1);
1333 let (update_msg, commitment_signed) = match events_0[0] {
1334 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
1335 (update_fee.as_ref(), commitment_signed)
1337 _ => panic!("Unexpected event"),
1340 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
1341 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
1342 check_added_monitors!(nodes[1], 1);
1344 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1345 // No commitment_signed so get_event_msg's assert(len == 1) passes
1347 // Handle (3), creating (6):
1348 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0).unwrap();
1349 check_added_monitors!(nodes[0], 1);
1350 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1351 // No commitment_signed so get_event_msg's assert(len == 1) passes
1354 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
1355 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1356 check_added_monitors!(nodes[0], 1);
1358 // Deliver (6), creating (7):
1359 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0).unwrap();
1360 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1361 assert!(commitment_update.update_add_htlcs.is_empty());
1362 assert!(commitment_update.update_fulfill_htlcs.is_empty());
1363 assert!(commitment_update.update_fail_htlcs.is_empty());
1364 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
1365 assert!(commitment_update.update_fee.is_none());
1366 check_added_monitors!(nodes[1], 1);
1369 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
1370 check_added_monitors!(nodes[0], 1);
1371 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1372 // No commitment_signed so get_event_msg's assert(len == 1) passes
1374 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
1375 check_added_monitors!(nodes[1], 1);
1376 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1378 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
1379 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
1380 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
1384 fn pre_funding_lock_shutdown_test() {
1385 // Test sending a shutdown prior to funding_locked after funding generation
1386 let nodes = create_network(2);
1387 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0);
1388 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1389 nodes[0].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
1390 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
1392 nodes[0].node.close_channel(&OutPoint::new(tx.txid(), 0).to_channel_id()).unwrap();
1393 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1394 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
1395 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1396 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
1398 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1399 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
1400 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1401 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
1402 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1403 assert!(node_0_none.is_none());
1405 assert!(nodes[0].node.list_channels().is_empty());
1406 assert!(nodes[1].node.list_channels().is_empty());
1410 fn updates_shutdown_wait() {
1411 // Test sending a shutdown with outstanding updates pending
1412 let mut nodes = create_network(3);
1413 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1414 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1415 let route_1 = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
1416 let route_2 = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
1418 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
1420 nodes[0].node.close_channel(&chan_1.2).unwrap();
1421 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1422 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
1423 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1424 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
1426 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1427 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1429 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1430 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route_1, payment_hash) {}
1431 else { panic!("New sends should fail!") };
1432 if let Err(APIError::ChannelUnavailable {..}) = nodes[1].node.send_payment(route_2, payment_hash) {}
1433 else { panic!("New sends should fail!") };
1435 assert!(nodes[2].node.claim_funds(our_payment_preimage));
1436 check_added_monitors!(nodes[2], 1);
1437 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1438 assert!(updates.update_add_htlcs.is_empty());
1439 assert!(updates.update_fail_htlcs.is_empty());
1440 assert!(updates.update_fail_malformed_htlcs.is_empty());
1441 assert!(updates.update_fee.is_none());
1442 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
1443 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
1444 check_added_monitors!(nodes[1], 1);
1445 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1446 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
1448 assert!(updates_2.update_add_htlcs.is_empty());
1449 assert!(updates_2.update_fail_htlcs.is_empty());
1450 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
1451 assert!(updates_2.update_fee.is_none());
1452 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
1453 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
1454 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
1456 let events = nodes[0].node.get_and_clear_pending_events();
1457 assert_eq!(events.len(), 1);
1459 Event::PaymentSent { ref payment_preimage } => {
1460 assert_eq!(our_payment_preimage, *payment_preimage);
1462 _ => panic!("Unexpected event"),
1465 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1466 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
1467 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1468 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
1469 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1470 assert!(node_0_none.is_none());
1472 assert!(nodes[0].node.list_channels().is_empty());
1474 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1475 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1476 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1477 assert!(nodes[1].node.list_channels().is_empty());
1478 assert!(nodes[2].node.list_channels().is_empty());
1482 fn htlc_fail_async_shutdown() {
1483 // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
1484 let mut nodes = create_network(3);
1485 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1486 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1488 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
1489 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
1490 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
1491 check_added_monitors!(nodes[0], 1);
1492 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1493 assert_eq!(updates.update_add_htlcs.len(), 1);
1494 assert!(updates.update_fulfill_htlcs.is_empty());
1495 assert!(updates.update_fail_htlcs.is_empty());
1496 assert!(updates.update_fail_malformed_htlcs.is_empty());
1497 assert!(updates.update_fee.is_none());
1499 nodes[1].node.close_channel(&chan_1.2).unwrap();
1500 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1501 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
1502 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1504 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
1505 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed).unwrap();
1506 check_added_monitors!(nodes[1], 1);
1507 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
1508 commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
1510 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1511 assert!(updates_2.update_add_htlcs.is_empty());
1512 assert!(updates_2.update_fulfill_htlcs.is_empty());
1513 assert_eq!(updates_2.update_fail_htlcs.len(), 1);
1514 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
1515 assert!(updates_2.update_fee.is_none());
1517 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]).unwrap();
1518 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
1520 let events = nodes[0].node.get_and_clear_pending_events();
1521 assert_eq!(events.len(), 1);
1523 Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } => {
1524 assert_eq!(our_payment_hash, *payment_hash);
1525 assert!(!rejected_by_dest);
1527 _ => panic!("Unexpected event"),
1530 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1531 assert_eq!(msg_events.len(), 2);
1532 let node_0_closing_signed = match msg_events[0] {
1533 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
1534 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
1537 _ => panic!("Unexpected event"),
1539 match msg_events[1] {
1540 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
1541 assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
1543 _ => panic!("Unexpected event"),
1546 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1547 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
1548 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1549 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
1550 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1551 assert!(node_0_none.is_none());
1553 assert!(nodes[0].node.list_channels().is_empty());
1555 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1556 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1557 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1558 assert!(nodes[1].node.list_channels().is_empty());
1559 assert!(nodes[2].node.list_channels().is_empty());
1562 fn do_test_shutdown_rebroadcast(recv_count: u8) {
1563 // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
1564 // messages delivered prior to disconnect
1565 let nodes = create_network(3);
1566 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1567 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1569 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
1571 nodes[1].node.close_channel(&chan_1.2).unwrap();
1572 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1574 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
1575 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1577 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
1581 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1582 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1584 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
1585 let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1586 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
1587 let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1589 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish).unwrap();
1590 let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1591 assert!(node_1_shutdown == node_1_2nd_shutdown);
1593 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish).unwrap();
1594 let node_0_2nd_shutdown = if recv_count > 0 {
1595 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1596 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
1599 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1600 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
1601 get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
1603 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown).unwrap();
1605 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1606 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1608 assert!(nodes[2].node.claim_funds(our_payment_preimage));
1609 check_added_monitors!(nodes[2], 1);
1610 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1611 assert!(updates.update_add_htlcs.is_empty());
1612 assert!(updates.update_fail_htlcs.is_empty());
1613 assert!(updates.update_fail_malformed_htlcs.is_empty());
1614 assert!(updates.update_fee.is_none());
1615 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
1616 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
1617 check_added_monitors!(nodes[1], 1);
1618 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1619 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
1621 assert!(updates_2.update_add_htlcs.is_empty());
1622 assert!(updates_2.update_fail_htlcs.is_empty());
1623 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
1624 assert!(updates_2.update_fee.is_none());
1625 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
1626 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
1627 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
1629 let events = nodes[0].node.get_and_clear_pending_events();
1630 assert_eq!(events.len(), 1);
1632 Event::PaymentSent { ref payment_preimage } => {
1633 assert_eq!(our_payment_preimage, *payment_preimage);
1635 _ => panic!("Unexpected event"),
1638 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1640 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
1641 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1642 assert!(node_1_closing_signed.is_some());
1645 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1646 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1648 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
1649 let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1650 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
1651 if recv_count == 0 {
1652 // If all closing_signeds weren't delivered we can just resume where we left off...
1653 let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1655 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish).unwrap();
1656 let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1657 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
1659 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish).unwrap();
1660 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1661 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
1663 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown).unwrap();
1664 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1666 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown).unwrap();
1667 let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1668 assert!(node_0_closing_signed == node_0_2nd_closing_signed);
1670 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed).unwrap();
1671 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1672 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
1673 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1674 assert!(node_0_none.is_none());
1676 // If one node, however, received + responded with an identical closing_signed we end
1677 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
1678 // There isn't really anything better we can do simply, but in the future we might
1679 // explore storing a set of recently-closed channels that got disconnected during
1680 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
1681 // give our counterparty enough time to (potentially) broadcast a cooperative closing
1683 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1685 if let Err(msgs::HandleError{action: Some(msgs::ErrorAction::SendErrorMessage{msg}), ..}) =
1686 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish) {
1687 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
1688 let msgs::ErrorMessage {ref channel_id, ..} = msg;
1689 assert_eq!(*channel_id, chan_1.2);
1690 } else { panic!("Needed SendErrorMessage close"); }
1692 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
1693 // checks it, but in this case nodes[0] didn't ever get a chance to receive a
1694 // closing_signed so we do it ourselves
1695 check_closed_broadcast!(nodes[0]);
1698 assert!(nodes[0].node.list_channels().is_empty());
1700 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1701 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1702 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1703 assert!(nodes[1].node.list_channels().is_empty());
1704 assert!(nodes[2].node.list_channels().is_empty());
1708 fn test_shutdown_rebroadcast() {
1709 do_test_shutdown_rebroadcast(0);
1710 do_test_shutdown_rebroadcast(1);
1711 do_test_shutdown_rebroadcast(2);
1715 fn fake_network_test() {
1716 // Simple test which builds a network of ChannelManagers, connects them to each other, and
1717 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
1718 let nodes = create_network(4);
1720 // Create some initial channels
1721 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1722 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1723 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
1725 // Rebalance the network a bit by relaying one payment through all the channels...
1726 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1727 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1728 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1729 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1731 // Send some more payments
1732 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
1733 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
1734 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
1736 // Test failure packets
1737 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1738 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1740 // Add a new channel that skips 3
1741 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
1743 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
1744 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
1745 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1746 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1747 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1748 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1749 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1751 // Do some rebalance loop payments, simultaneously
1752 let mut hops = Vec::with_capacity(3);
1753 hops.push(RouteHop {
1754 pubkey: nodes[2].node.get_our_node_id(),
1755 short_channel_id: chan_2.0.contents.short_channel_id,
1757 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1759 hops.push(RouteHop {
1760 pubkey: nodes[3].node.get_our_node_id(),
1761 short_channel_id: chan_3.0.contents.short_channel_id,
1763 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1765 hops.push(RouteHop {
1766 pubkey: nodes[1].node.get_our_node_id(),
1767 short_channel_id: chan_4.0.contents.short_channel_id,
1769 cltv_expiry_delta: TEST_FINAL_CLTV,
1771 hops[1].fee_msat = chan_4.1.contents.fee_base_msat as u64 + chan_4.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1772 hops[0].fee_msat = chan_3.0.contents.fee_base_msat as u64 + chan_3.0.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1773 let payment_preimage_1 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1775 let mut hops = Vec::with_capacity(3);
1776 hops.push(RouteHop {
1777 pubkey: nodes[3].node.get_our_node_id(),
1778 short_channel_id: chan_4.0.contents.short_channel_id,
1780 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1782 hops.push(RouteHop {
1783 pubkey: nodes[2].node.get_our_node_id(),
1784 short_channel_id: chan_3.0.contents.short_channel_id,
1786 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1788 hops.push(RouteHop {
1789 pubkey: nodes[1].node.get_our_node_id(),
1790 short_channel_id: chan_2.0.contents.short_channel_id,
1792 cltv_expiry_delta: TEST_FINAL_CLTV,
1794 hops[1].fee_msat = chan_2.1.contents.fee_base_msat as u64 + chan_2.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1795 hops[0].fee_msat = chan_3.1.contents.fee_base_msat as u64 + chan_3.1.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1796 let payment_hash_2 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1798 // Claim the rebalances...
1799 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1800 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1802 // Add a duplicate new channel from 2 to 4
1803 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3);
1805 // Send some payments across both channels
1806 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1807 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1808 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1810 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1812 //TODO: Test that routes work again here as we've been notified that the channel is full
1814 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
1815 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
1816 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
1818 // Close down the channels...
1819 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1820 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1821 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1822 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1823 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1827 fn duplicate_htlc_test() {
1828 // Test that we accept duplicate payment_hash HTLCs across the network and that
1829 // claiming/failing them are all separate and don't effect each other
1830 let mut nodes = create_network(6);
1832 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1833 create_announced_chan_between_nodes(&nodes, 0, 3);
1834 create_announced_chan_between_nodes(&nodes, 1, 3);
1835 create_announced_chan_between_nodes(&nodes, 2, 3);
1836 create_announced_chan_between_nodes(&nodes, 3, 4);
1837 create_announced_chan_between_nodes(&nodes, 3, 5);
1839 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1841 *nodes[0].network_payment_count.borrow_mut() -= 1;
1842 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1844 *nodes[0].network_payment_count.borrow_mut() -= 1;
1845 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1847 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1848 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1849 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1852 #[derive(PartialEq)]
1853 enum HTLCType { NONE, TIMEOUT, SUCCESS }
1854 /// Tests that the given node has broadcast transactions for the given Channel
1856 /// First checks that the latest local commitment tx has been broadcast, unless an explicit
1857 /// commitment_tx is provided, which may be used to test that a remote commitment tx was
1858 /// broadcast and the revoked outputs were claimed.
1860 /// Next tests that there is (or is not) a transaction that spends the commitment transaction
1861 /// that appears to be the type of HTLC transaction specified in has_htlc_tx.
1863 /// All broadcast transactions must be accounted for in one of the above three types of we'll
1865 fn test_txn_broadcast(node: &Node, chan: &(msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction), commitment_tx: Option<Transaction>, has_htlc_tx: HTLCType) -> Vec<Transaction> {
1866 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
1867 assert!(node_txn.len() >= if commitment_tx.is_some() { 0 } else { 1 } + if has_htlc_tx == HTLCType::NONE { 0 } else { 1 });
1869 let mut res = Vec::with_capacity(2);
1870 node_txn.retain(|tx| {
1871 if tx.input.len() == 1 && tx.input[0].previous_output.txid == chan.3.txid() {
1872 check_spends!(tx, chan.3.clone());
1873 if commitment_tx.is_none() {
1874 res.push(tx.clone());
1879 if let Some(explicit_tx) = commitment_tx {
1880 res.push(explicit_tx.clone());
1883 assert_eq!(res.len(), 1);
1885 if has_htlc_tx != HTLCType::NONE {
1886 node_txn.retain(|tx| {
1887 if tx.input.len() == 1 && tx.input[0].previous_output.txid == res[0].txid() {
1888 check_spends!(tx, res[0].clone());
1889 if has_htlc_tx == HTLCType::TIMEOUT {
1890 assert!(tx.lock_time != 0);
1892 assert!(tx.lock_time == 0);
1894 res.push(tx.clone());
1898 assert!(res.len() == 2 || res.len() == 3);
1900 assert_eq!(res[1], res[2]);
1904 assert!(node_txn.is_empty());
1908 /// Tests that the given node has broadcast a claim transaction against the provided revoked
1909 /// HTLC transaction.
1910 fn test_revoked_htlc_claim_txn_broadcast(node: &Node, revoked_tx: Transaction) {
1911 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
1912 assert_eq!(node_txn.len(), 1);
1913 node_txn.retain(|tx| {
1914 if tx.input.len() == 1 && tx.input[0].previous_output.txid == revoked_tx.txid() {
1915 check_spends!(tx, revoked_tx.clone());
1919 assert!(node_txn.is_empty());
1922 fn check_preimage_claim(node: &Node, prev_txn: &Vec<Transaction>) -> Vec<Transaction> {
1923 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
1925 assert!(node_txn.len() >= 1);
1926 assert_eq!(node_txn[0].input.len(), 1);
1927 let mut found_prev = false;
1929 for tx in prev_txn {
1930 if node_txn[0].input[0].previous_output.txid == tx.txid() {
1931 check_spends!(node_txn[0], tx.clone());
1932 assert!(node_txn[0].input[0].witness[2].len() > 106); // must spend an htlc output
1933 assert_eq!(tx.input.len(), 1); // must spend a commitment tx
1939 assert!(found_prev);
1941 let mut res = Vec::new();
1942 mem::swap(&mut *node_txn, &mut res);
1946 fn get_announce_close_broadcast_events(nodes: &Vec<Node>, a: usize, b: usize) {
1947 let events_1 = nodes[a].node.get_and_clear_pending_msg_events();
1948 assert_eq!(events_1.len(), 1);
1949 let as_update = match events_1[0] {
1950 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
1953 _ => panic!("Unexpected event"),
1956 let events_2 = nodes[b].node.get_and_clear_pending_msg_events();
1957 assert_eq!(events_2.len(), 1);
1958 let bs_update = match events_2[0] {
1959 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
1962 _ => panic!("Unexpected event"),
1966 node.router.handle_channel_update(&as_update).unwrap();
1967 node.router.handle_channel_update(&bs_update).unwrap();
1971 macro_rules! expect_payment_received {
1972 ($node: expr, $expected_payment_hash: expr, $expected_recv_value: expr) => {
1973 let events = $node.node.get_and_clear_pending_events();
1974 assert_eq!(events.len(), 1);
1976 Event::PaymentReceived { ref payment_hash, amt } => {
1977 assert_eq!($expected_payment_hash, *payment_hash);
1978 assert_eq!($expected_recv_value, amt);
1980 _ => panic!("Unexpected event"),
1985 macro_rules! get_channel_value_stat {
1986 ($node: expr, $channel_id: expr) => {{
1987 let chan_lock = $node.node.channel_state.lock().unwrap();
1988 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
1989 chan.get_value_stat()
1993 fn do_channel_reserve_test(test_recv: bool) {
1995 use std::sync::atomic::Ordering;
1996 use ln::msgs::HandleError;
1998 let mut nodes = create_network(3);
1999 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1900, 1001);
2000 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1900, 1001);
2002 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
2003 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
2005 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
2006 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
2008 macro_rules! get_route_and_payment_hash {
2009 ($recv_value: expr) => {{
2010 let route = nodes[0].router.get_route(&nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV).unwrap();
2011 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
2012 (route, payment_hash, payment_preimage)
2016 macro_rules! expect_forward {
2018 let mut events = $node.node.get_and_clear_pending_msg_events();
2019 assert_eq!(events.len(), 1);
2020 check_added_monitors!($node, 1);
2021 let payment_event = SendEvent::from_event(events.remove(0));
2026 let feemsat = 239; // somehow we know?
2027 let total_fee_msat = (nodes.len() - 2) as u64 * 239;
2029 let recv_value_0 = stat01.their_max_htlc_value_in_flight_msat - total_fee_msat;
2031 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
2033 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
2034 assert!(route.hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
2035 let err = nodes[0].node.send_payment(route, our_payment_hash).err().unwrap();
2037 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
2038 _ => panic!("Unknown error variants"),
2042 let mut htlc_id = 0;
2043 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
2044 // nodes[0]'s wealth
2046 let amt_msat = recv_value_0 + total_fee_msat;
2047 if stat01.value_to_self_msat - amt_msat < stat01.channel_reserve_msat {
2050 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
2053 let (stat01_, stat11_, stat12_, stat22_) = (
2054 get_channel_value_stat!(nodes[0], chan_1.2),
2055 get_channel_value_stat!(nodes[1], chan_1.2),
2056 get_channel_value_stat!(nodes[1], chan_2.2),
2057 get_channel_value_stat!(nodes[2], chan_2.2),
2060 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
2061 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
2062 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
2063 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
2064 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
2068 let recv_value = stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat;
2069 // attempt to get channel_reserve violation
2070 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value + 1);
2071 let err = nodes[0].node.send_payment(route.clone(), our_payment_hash).err().unwrap();
2073 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
2074 _ => panic!("Unknown error variants"),
2078 // adding pending output
2079 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat)/2;
2080 let amt_msat_1 = recv_value_1 + total_fee_msat;
2082 let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
2083 let payment_event_1 = {
2084 nodes[0].node.send_payment(route_1, our_payment_hash_1).unwrap();
2085 check_added_monitors!(nodes[0], 1);
2087 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2088 assert_eq!(events.len(), 1);
2089 SendEvent::from_event(events.remove(0))
2091 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]).unwrap();
2093 // channel reserve test with htlc pending output > 0
2094 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat;
2096 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
2097 match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
2098 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
2099 _ => panic!("Unknown error variants"),
2104 // test channel_reserve test on nodes[1] side
2105 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
2107 // Need to manually create update_add_htlc message to go around the channel reserve check in send_htlc()
2108 let secp_ctx = Secp256k1::new();
2109 let session_priv = SecretKey::from_slice(&secp_ctx, &{
2110 let mut session_key = [0; 32];
2111 rng::fill_bytes(&mut session_key);
2113 }).expect("RNG is bad!");
2115 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
2116 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
2117 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
2118 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, &our_payment_hash);
2119 let msg = msgs::UpdateAddHTLC {
2120 channel_id: chan_1.2,
2122 amount_msat: htlc_msat,
2123 payment_hash: our_payment_hash,
2124 cltv_expiry: htlc_cltv,
2125 onion_routing_packet: onion_packet,
2129 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg).err().unwrap();
2131 HandleError{err, .. } => assert_eq!(err, "Remote HTLC add would put them over their reserve value"),
2133 // If we send a garbage message, the channel should get closed, making the rest of this test case fail.
2134 assert_eq!(nodes[1].node.list_channels().len(), 1);
2135 assert_eq!(nodes[1].node.list_channels().len(), 1);
2136 check_closed_broadcast!(nodes[1]);
2141 // split the rest to test holding cell
2142 let recv_value_21 = recv_value_2/2;
2143 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat;
2145 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
2146 assert_eq!(stat.value_to_self_msat - (stat.pending_outbound_htlcs_amount_msat + recv_value_21 + recv_value_22 + total_fee_msat + total_fee_msat), stat.channel_reserve_msat);
2149 // now see if they go through on both sides
2150 let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
2151 // but this will stuck in the holding cell
2152 nodes[0].node.send_payment(route_21, our_payment_hash_21).unwrap();
2153 check_added_monitors!(nodes[0], 0);
2154 let events = nodes[0].node.get_and_clear_pending_events();
2155 assert_eq!(events.len(), 0);
2157 // test with outbound holding cell amount > 0
2159 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
2160 match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
2161 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
2162 _ => panic!("Unknown error variants"),
2166 let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
2167 // this will also stuck in the holding cell
2168 nodes[0].node.send_payment(route_22, our_payment_hash_22).unwrap();
2169 check_added_monitors!(nodes[0], 0);
2170 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
2171 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2173 // flush the pending htlc
2174 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg).unwrap();
2175 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2176 check_added_monitors!(nodes[1], 1);
2178 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
2179 check_added_monitors!(nodes[0], 1);
2180 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2182 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed).unwrap();
2183 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2184 // No commitment_signed so get_event_msg's assert(len == 1) passes
2185 check_added_monitors!(nodes[0], 1);
2187 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
2188 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2189 check_added_monitors!(nodes[1], 1);
2191 expect_pending_htlcs_forwardable!(nodes[1]);
2193 let ref payment_event_11 = expect_forward!(nodes[1]);
2194 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]).unwrap();
2195 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
2197 expect_pending_htlcs_forwardable!(nodes[2]);
2198 expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
2200 // flush the htlcs in the holding cell
2201 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
2202 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]).unwrap();
2203 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]).unwrap();
2204 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
2205 expect_pending_htlcs_forwardable!(nodes[1]);
2207 let ref payment_event_3 = expect_forward!(nodes[1]);
2208 assert_eq!(payment_event_3.msgs.len(), 2);
2209 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]).unwrap();
2210 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]).unwrap();
2212 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2213 expect_pending_htlcs_forwardable!(nodes[2]);
2215 let events = nodes[2].node.get_and_clear_pending_events();
2216 assert_eq!(events.len(), 2);
2218 Event::PaymentReceived { ref payment_hash, amt } => {
2219 assert_eq!(our_payment_hash_21, *payment_hash);
2220 assert_eq!(recv_value_21, amt);
2222 _ => panic!("Unexpected event"),
2225 Event::PaymentReceived { ref payment_hash, amt } => {
2226 assert_eq!(our_payment_hash_22, *payment_hash);
2227 assert_eq!(recv_value_22, amt);
2229 _ => panic!("Unexpected event"),
2232 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2233 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2234 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2236 let expected_value_to_self = stat01.value_to_self_msat - (recv_value_1 + total_fee_msat) - (recv_value_21 + total_fee_msat) - (recv_value_22 + total_fee_msat);
2237 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
2238 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2239 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat);
2241 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2242 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22);
2246 fn channel_reserve_test() {
2247 do_channel_reserve_test(false);
2248 do_channel_reserve_test(true);
2252 fn channel_monitor_network_test() {
2253 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2254 // tests that ChannelMonitor is able to recover from various states.
2255 let nodes = create_network(5);
2257 // Create some initial channels
2258 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2259 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2260 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2261 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
2263 // Rebalance the network a bit by relaying one payment through all the channels...
2264 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2265 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2266 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2267 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2269 // Simple case with no pending HTLCs:
2270 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2272 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2273 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2274 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
2275 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2277 get_announce_close_broadcast_events(&nodes, 0, 1);
2278 assert_eq!(nodes[0].node.list_channels().len(), 0);
2279 assert_eq!(nodes[1].node.list_channels().len(), 1);
2281 // One pending HTLC is discarded by the force-close:
2282 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2284 // Simple case of one pending HTLC to HTLC-Timeout
2285 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2287 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2288 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2289 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
2290 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2292 get_announce_close_broadcast_events(&nodes, 1, 2);
2293 assert_eq!(nodes[1].node.list_channels().len(), 0);
2294 assert_eq!(nodes[2].node.list_channels().len(), 1);
2296 macro_rules! claim_funds {
2297 ($node: expr, $prev_node: expr, $preimage: expr) => {
2299 assert!($node.node.claim_funds($preimage));
2300 check_added_monitors!($node, 1);
2302 let events = $node.node.get_and_clear_pending_msg_events();
2303 assert_eq!(events.len(), 1);
2305 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2306 assert!(update_add_htlcs.is_empty());
2307 assert!(update_fail_htlcs.is_empty());
2308 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2310 _ => panic!("Unexpected event"),
2316 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2317 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2318 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2320 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2322 // Claim the payment on nodes[3], giving it knowledge of the preimage
2323 claim_funds!(nodes[3], nodes[2], payment_preimage_1);
2325 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2326 nodes[3].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 1);
2328 check_preimage_claim(&nodes[3], &node_txn);
2330 get_announce_close_broadcast_events(&nodes, 2, 3);
2331 assert_eq!(nodes[2].node.list_channels().len(), 0);
2332 assert_eq!(nodes[3].node.list_channels().len(), 1);
2334 { // Cheat and reset nodes[4]'s height to 1
2335 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2336 nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![] }, 1);
2339 assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
2340 assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
2341 // One pending HTLC to time out:
2342 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2343 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2347 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2348 nodes[3].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
2349 for i in 3..TEST_FINAL_CLTV + 2 + HTLC_FAIL_TIMEOUT_BLOCKS + 1 {
2350 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2351 nodes[3].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
2354 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2356 // Claim the payment on nodes[4], giving it knowledge of the preimage
2357 claim_funds!(nodes[4], nodes[3], payment_preimage_2);
2359 header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2360 nodes[4].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
2361 for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
2362 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2363 nodes[4].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
2366 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2368 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2369 nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, TEST_FINAL_CLTV - 5);
2371 check_preimage_claim(&nodes[4], &node_txn);
2373 get_announce_close_broadcast_events(&nodes, 3, 4);
2374 assert_eq!(nodes[3].node.list_channels().len(), 0);
2375 assert_eq!(nodes[4].node.list_channels().len(), 0);
2379 fn test_justice_tx() {
2380 // Test justice txn built on revoked HTLC-Success tx, against both sides
2382 let nodes = create_network(2);
2383 // Create some new channels:
2384 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
2386 // A pending HTLC which will be revoked:
2387 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2388 // Get the will-be-revoked local txn from nodes[0]
2389 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
2390 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2391 assert_eq!(revoked_local_txn[0].input.len(), 1);
2392 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2393 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2394 assert_eq!(revoked_local_txn[1].input.len(), 1);
2395 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2396 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2397 // Revoke the old state
2398 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2401 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2402 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2404 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2405 assert_eq!(node_txn.len(), 3);
2406 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
2407 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2409 check_spends!(node_txn[0], revoked_local_txn[0].clone());
2410 node_txn.swap_remove(0);
2412 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2414 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2415 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2416 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2417 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2418 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone());
2420 get_announce_close_broadcast_events(&nodes, 0, 1);
2422 assert_eq!(nodes[0].node.list_channels().len(), 0);
2423 assert_eq!(nodes[1].node.list_channels().len(), 0);
2425 // We test justice_tx build by A on B's revoked HTLC-Success tx
2426 // Create some new channels:
2427 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
2429 // A pending HTLC which will be revoked:
2430 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2431 // Get the will-be-revoked local txn from B
2432 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
2433 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2434 assert_eq!(revoked_local_txn[0].input.len(), 1);
2435 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2436 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2437 // Revoke the old state
2438 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2440 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2441 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2443 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2444 assert_eq!(node_txn.len(), 3);
2445 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
2446 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2448 check_spends!(node_txn[0], revoked_local_txn[0].clone());
2449 node_txn.swap_remove(0);
2451 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2453 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2454 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2455 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2456 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2457 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone());
2459 get_announce_close_broadcast_events(&nodes, 0, 1);
2460 assert_eq!(nodes[0].node.list_channels().len(), 0);
2461 assert_eq!(nodes[1].node.list_channels().len(), 0);
2465 fn revoked_output_claim() {
2466 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2467 // transaction is broadcast by its counterparty
2468 let nodes = create_network(2);
2469 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2470 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2471 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
2472 assert_eq!(revoked_local_txn.len(), 1);
2473 // Only output is the full channel value back to nodes[0]:
2474 assert_eq!(revoked_local_txn[0].output.len(), 1);
2475 // Send a payment through, updating everyone's latest commitment txn
2476 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2478 // Inform nodes[1] that nodes[0] broadcast a stale tx
2479 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2480 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2481 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2482 assert_eq!(node_txn.len(), 3); // nodes[1] will broadcast justice tx twice, and its own local state once
2484 assert_eq!(node_txn[0], node_txn[2]);
2486 check_spends!(node_txn[0], revoked_local_txn[0].clone());
2487 check_spends!(node_txn[1], chan_1.3.clone());
2489 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2490 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2491 get_announce_close_broadcast_events(&nodes, 0, 1);
2495 fn claim_htlc_outputs_shared_tx() {
2496 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2497 let nodes = create_network(2);
2499 // Create some new channel:
2500 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2502 // Rebalance the network to generate htlc in the two directions
2503 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2504 // node[0] is gonna to revoke an old state thus node[1] should be able to claim both offered/received HTLC outputs on top of commitment tx
2505 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2506 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2508 // Get the will-be-revoked local txn from node[0]
2509 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
2510 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2511 assert_eq!(revoked_local_txn[0].input.len(), 1);
2512 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2513 assert_eq!(revoked_local_txn[1].input.len(), 1);
2514 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2515 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2516 check_spends!(revoked_local_txn[1], revoked_local_txn[0].clone());
2518 //Revoke the old state
2519 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2522 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2523 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2524 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2526 let events = nodes[1].node.get_and_clear_pending_events();
2527 assert_eq!(events.len(), 1);
2529 Event::PaymentFailed { payment_hash, .. } => {
2530 assert_eq!(payment_hash, payment_hash_2);
2532 _ => panic!("Unexpected event"),
2535 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2536 assert_eq!(node_txn.len(), 4);
2538 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2539 check_spends!(node_txn[0], revoked_local_txn[0].clone());
2541 assert_eq!(node_txn[0], node_txn[3]); // justice tx is duplicated due to block re-scanning
2543 let mut witness_lens = BTreeSet::new();
2544 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2545 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2546 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2547 assert_eq!(witness_lens.len(), 3);
2548 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2549 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2550 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2552 // Next nodes[1] broadcasts its current local tx state:
2553 assert_eq!(node_txn[1].input.len(), 1);
2554 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2556 assert_eq!(node_txn[2].input.len(), 1);
2557 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
2558 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2559 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
2560 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
2561 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
2563 get_announce_close_broadcast_events(&nodes, 0, 1);
2564 assert_eq!(nodes[0].node.list_channels().len(), 0);
2565 assert_eq!(nodes[1].node.list_channels().len(), 0);
2569 fn claim_htlc_outputs_single_tx() {
2570 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2571 let nodes = create_network(2);
2573 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2575 // Rebalance the network to generate htlc in the two directions
2576 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2577 // node[0] is gonna to revoke an old state thus node[1] should be able to claim both offered/received HTLC outputs on top of commitment tx, but this
2578 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2579 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2580 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2582 // Get the will-be-revoked local txn from node[0]
2583 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
2585 //Revoke the old state
2586 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2589 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2590 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2591 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2593 let events = nodes[1].node.get_and_clear_pending_events();
2594 assert_eq!(events.len(), 1);
2596 Event::PaymentFailed { payment_hash, .. } => {
2597 assert_eq!(payment_hash, payment_hash_2);
2599 _ => panic!("Unexpected event"),
2602 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2603 assert_eq!(node_txn.len(), 12); // ChannelManager : 2, ChannelMontitor: 8 (1 standard revoked output, 2 revocation htlc tx, 1 local commitment tx + 1 htlc timeout tx) * 2 (block-rescan)
2605 assert_eq!(node_txn[0], node_txn[7]);
2606 assert_eq!(node_txn[1], node_txn[8]);
2607 assert_eq!(node_txn[2], node_txn[9]);
2608 assert_eq!(node_txn[3], node_txn[10]);
2609 assert_eq!(node_txn[4], node_txn[11]);
2610 assert_eq!(node_txn[3], node_txn[5]); //local commitment tx + htlc timeout tx broadcated by ChannelManger
2611 assert_eq!(node_txn[4], node_txn[6]);
2613 assert_eq!(node_txn[0].input.len(), 1);
2614 assert_eq!(node_txn[1].input.len(), 1);
2615 assert_eq!(node_txn[2].input.len(), 1);
2617 let mut revoked_tx_map = HashMap::new();
2618 revoked_tx_map.insert(revoked_local_txn[0].txid(), revoked_local_txn[0].clone());
2619 node_txn[0].verify(&revoked_tx_map).unwrap();
2620 node_txn[1].verify(&revoked_tx_map).unwrap();
2621 node_txn[2].verify(&revoked_tx_map).unwrap();
2623 let mut witness_lens = BTreeSet::new();
2624 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2625 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2626 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2627 assert_eq!(witness_lens.len(), 3);
2628 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2629 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2630 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2632 assert_eq!(node_txn[3].input.len(), 1);
2633 check_spends!(node_txn[3], chan_1.3.clone());
2635 assert_eq!(node_txn[4].input.len(), 1);
2636 let witness_script = node_txn[4].input[0].witness.last().unwrap();
2637 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2638 assert_eq!(node_txn[4].input[0].previous_output.txid, node_txn[3].txid());
2639 assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
2640 assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[1].input[0].previous_output.txid);
2642 get_announce_close_broadcast_events(&nodes, 0, 1);
2643 assert_eq!(nodes[0].node.list_channels().len(), 0);
2644 assert_eq!(nodes[1].node.list_channels().len(), 0);
2648 fn test_htlc_on_chain_success() {
2649 // Test that in case of an unilateral close onchain, we detect the state of output thanks to
2650 // ChainWatchInterface and pass the preimage backward accordingly. So here we test that ChannelManager is
2651 // broadcasting the right event to other nodes in payment path.
2652 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2653 // A --------------------> B ----------------------> C (preimage)
2654 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2655 // commitment transaction was broadcast.
2656 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2658 // B should be able to claim via preimage if A then broadcasts its local tx.
2659 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2660 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2661 // PaymentSent event).
2663 let nodes = create_network(3);
2665 // Create some initial channels
2666 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2667 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2669 // Rebalance the network a bit by relaying one payment through all the channels...
2670 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2671 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2673 let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2674 let (our_payment_preimage_2, _payment_hash_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2675 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2677 // Broadcast legit commitment tx from C on B's chain
2678 // Broadcast HTLC Success transation by C on received output from C's commitment tx on B's chain
2679 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
2680 assert_eq!(commitment_tx.len(), 1);
2681 check_spends!(commitment_tx[0], chan_2.3.clone());
2682 nodes[2].node.claim_funds(our_payment_preimage);
2683 nodes[2].node.claim_funds(our_payment_preimage_2);
2684 check_added_monitors!(nodes[2], 2);
2685 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2686 assert!(updates.update_add_htlcs.is_empty());
2687 assert!(updates.update_fail_htlcs.is_empty());
2688 assert!(updates.update_fail_malformed_htlcs.is_empty());
2689 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2691 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2692 check_closed_broadcast!(nodes[2]);
2693 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx), ChannelMonitor : 4 (2*2 * HTLC-Success tx)
2694 assert_eq!(node_txn.len(), 5);
2695 assert_eq!(node_txn[0], node_txn[3]);
2696 assert_eq!(node_txn[1], node_txn[4]);
2697 assert_eq!(node_txn[2], commitment_tx[0]);
2698 check_spends!(node_txn[0], commitment_tx[0].clone());
2699 check_spends!(node_txn[1], commitment_tx[0].clone());
2700 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2701 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2702 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2703 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2704 assert_eq!(node_txn[0].lock_time, 0);
2705 assert_eq!(node_txn[1].lock_time, 0);
2707 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2708 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: node_txn}, 1);
2709 let events = nodes[1].node.get_and_clear_pending_msg_events();
2711 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
2712 assert_eq!(added_monitors.len(), 2);
2713 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2714 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2715 added_monitors.clear();
2717 assert_eq!(events.len(), 2);
2719 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2720 _ => panic!("Unexpected event"),
2723 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
2724 assert!(update_add_htlcs.is_empty());
2725 assert!(update_fail_htlcs.is_empty());
2726 assert_eq!(update_fulfill_htlcs.len(), 1);
2727 assert!(update_fail_malformed_htlcs.is_empty());
2728 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2730 _ => panic!("Unexpected event"),
2732 macro_rules! check_tx_local_broadcast {
2733 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2734 // ChannelManager : 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor : 2 (timeout tx) * 2 (block-rescan)
2735 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2736 assert_eq!(node_txn.len(), 7);
2737 assert_eq!(node_txn[0], node_txn[5]);
2738 assert_eq!(node_txn[1], node_txn[6]);
2739 check_spends!(node_txn[0], $commitment_tx.clone());
2740 check_spends!(node_txn[1], $commitment_tx.clone());
2741 assert_ne!(node_txn[0].lock_time, 0);
2742 assert_ne!(node_txn[1].lock_time, 0);
2744 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2745 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2746 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2747 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2749 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2750 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2751 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2752 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2754 check_spends!(node_txn[2], $chan_tx.clone());
2755 check_spends!(node_txn[3], node_txn[2].clone());
2756 check_spends!(node_txn[4], node_txn[2].clone());
2757 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), 71);
2758 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2759 assert_eq!(node_txn[4].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2760 assert!(node_txn[3].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2761 assert!(node_txn[4].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2762 assert_ne!(node_txn[3].lock_time, 0);
2763 assert_ne!(node_txn[4].lock_time, 0);
2767 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2768 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2769 // timeout-claim of the output that nodes[2] just claimed via success.
2770 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2772 // Broadcast legit commitment tx from A on B's chain
2773 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2774 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
2775 check_spends!(commitment_tx[0], chan_1.3.clone());
2776 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2777 check_closed_broadcast!(nodes[1]);
2778 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx), ChannelMonitor : 1 (HTLC-Success) * 2 (block-rescan)
2779 assert_eq!(node_txn.len(), 3);
2780 assert_eq!(node_txn[0], node_txn[2]);
2781 check_spends!(node_txn[0], commitment_tx[0].clone());
2782 assert_eq!(node_txn[0].input.len(), 2);
2783 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2784 assert_eq!(node_txn[0].input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2785 assert_eq!(node_txn[0].lock_time, 0);
2786 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2787 check_spends!(node_txn[1], chan_1.3.clone());
2788 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
2789 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2790 // we already checked the same situation with A.
2792 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2793 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
2794 check_closed_broadcast!(nodes[0]);
2795 let events = nodes[0].node.get_and_clear_pending_events();
2796 assert_eq!(events.len(), 2);
2797 let mut first_claimed = false;
2798 for event in events {
2800 Event::PaymentSent { payment_preimage } => {
2801 if payment_preimage == our_payment_preimage {
2802 assert!(!first_claimed);
2803 first_claimed = true;
2805 assert_eq!(payment_preimage, our_payment_preimage_2);
2808 _ => panic!("Unexpected event"),
2811 check_tx_local_broadcast!(nodes[0], true, commitment_tx[0], chan_1.3);
2815 fn test_htlc_on_chain_timeout() {
2816 // Test that in case of an unilateral close onchain, we detect the state of output thanks to
2817 // ChainWatchInterface and timeout the HTLC bacward accordingly. So here we test that ChannelManager is
2818 // broadcasting the right event to other nodes in payment path.
2819 // A ------------------> B ----------------------> C (timeout)
2820 // B's commitment tx C's commitment tx
2822 // B's HTLC timeout tx B's timeout tx
2824 let nodes = create_network(3);
2826 // Create some intial channels
2827 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2828 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2830 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2831 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2832 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2834 let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2835 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2837 // Brodacast legit commitment tx from C on B's chain
2838 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
2839 check_spends!(commitment_tx[0], chan_2.3.clone());
2840 nodes[2].node.fail_htlc_backwards(&payment_hash, 0);
2841 check_added_monitors!(nodes[2], 0);
2842 expect_pending_htlcs_forwardable!(nodes[2]);
2843 check_added_monitors!(nodes[2], 1);
2845 let events = nodes[2].node.get_and_clear_pending_msg_events();
2846 assert_eq!(events.len(), 1);
2848 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, .. } } => {
2849 assert!(update_add_htlcs.is_empty());
2850 assert!(!update_fail_htlcs.is_empty());
2851 assert!(update_fulfill_htlcs.is_empty());
2852 assert!(update_fail_malformed_htlcs.is_empty());
2853 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2855 _ => panic!("Unexpected event"),
2857 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2858 check_closed_broadcast!(nodes[2]);
2859 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2860 assert_eq!(node_txn.len(), 1);
2861 check_spends!(node_txn[0], chan_2.3.clone());
2862 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2864 // Broadcast timeout transaction by B on received output fron C's commitment tx on B's chain
2865 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2866 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
2869 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2870 assert_eq!(node_txn.len(), 8); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 6 (HTLC-Timeout tx, commitment tx, timeout tx) * 2 (block-rescan)
2871 assert_eq!(node_txn[0], node_txn[5]);
2872 assert_eq!(node_txn[1], node_txn[6]);
2873 assert_eq!(node_txn[2], node_txn[7]);
2874 check_spends!(node_txn[0], commitment_tx[0].clone());
2875 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2876 check_spends!(node_txn[1], chan_2.3.clone());
2877 check_spends!(node_txn[2], node_txn[1].clone());
2878 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
2879 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2880 check_spends!(node_txn[3], chan_2.3.clone());
2881 check_spends!(node_txn[4], node_txn[3].clone());
2882 assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2883 assert_eq!(node_txn[4].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2884 timeout_tx = node_txn[0].clone();
2888 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![timeout_tx]}, 1);
2889 check_added_monitors!(nodes[1], 0);
2890 check_closed_broadcast!(nodes[1]);
2892 expect_pending_htlcs_forwardable!(nodes[1]);
2893 check_added_monitors!(nodes[1], 1);
2894 let events = nodes[1].node.get_and_clear_pending_msg_events();
2895 assert_eq!(events.len(), 1);
2897 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
2898 assert!(update_add_htlcs.is_empty());
2899 assert!(!update_fail_htlcs.is_empty());
2900 assert!(update_fulfill_htlcs.is_empty());
2901 assert!(update_fail_malformed_htlcs.is_empty());
2902 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2904 _ => panic!("Unexpected event"),
2906 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // Well... here we detect our own htlc_timeout_tx so no tx to be generated
2907 assert_eq!(node_txn.len(), 0);
2909 // Broadcast legit commitment tx from B on A's chain
2910 let commitment_tx = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
2911 check_spends!(commitment_tx[0], chan_1.3.clone());
2913 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
2914 check_closed_broadcast!(nodes[0]);
2915 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (timeout tx) * 2 block-rescan
2916 assert_eq!(node_txn.len(), 4);
2917 assert_eq!(node_txn[0], node_txn[3]);
2918 check_spends!(node_txn[0], commitment_tx[0].clone());
2919 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2920 check_spends!(node_txn[1], chan_1.3.clone());
2921 check_spends!(node_txn[2], node_txn[1].clone());
2922 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
2923 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2927 fn test_simple_commitment_revoked_fail_backward() {
2928 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
2929 // and fail backward accordingly.
2931 let nodes = create_network(3);
2933 // Create some initial channels
2934 create_announced_chan_between_nodes(&nodes, 0, 1);
2935 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2937 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2938 // Get the will-be-revoked local txn from nodes[2]
2939 let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
2940 // Revoke the old state
2941 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
2943 route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2945 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2946 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2947 check_added_monitors!(nodes[1], 0);
2948 check_closed_broadcast!(nodes[1]);
2950 expect_pending_htlcs_forwardable!(nodes[1]);
2951 check_added_monitors!(nodes[1], 1);
2952 let events = nodes[1].node.get_and_clear_pending_msg_events();
2953 assert_eq!(events.len(), 1);
2955 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, ref commitment_signed, .. } } => {
2956 assert!(update_add_htlcs.is_empty());
2957 assert_eq!(update_fail_htlcs.len(), 1);
2958 assert!(update_fulfill_htlcs.is_empty());
2959 assert!(update_fail_malformed_htlcs.is_empty());
2960 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2962 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]).unwrap();
2963 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
2965 let events = nodes[0].node.get_and_clear_pending_msg_events();
2966 assert_eq!(events.len(), 1);
2968 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
2969 _ => panic!("Unexpected event"),
2971 let events = nodes[0].node.get_and_clear_pending_events();
2972 assert_eq!(events.len(), 1);
2974 Event::PaymentFailed { .. } => {},
2975 _ => panic!("Unexpected event"),
2978 _ => panic!("Unexpected event"),
2982 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
2983 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
2984 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
2985 // commitment transaction anymore.
2986 // To do this, we have the peer which will broadcast a revoked commitment transaction send
2987 // a number of update_fail/commitment_signed updates without ever sending the RAA in
2988 // response to our commitment_signed. This is somewhat misbehavior-y, though not
2989 // technically disallowed and we should probably handle it reasonably.
2990 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
2991 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
2993 // * Once we move it out of our holding cell/add it, we will immediately include it in a
2994 // commitment_signed (implying it will be in the latest remote commitment transaction).
2995 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
2996 // and once they revoke the previous commitment transaction (allowing us to send a new
2997 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
2998 let mut nodes = create_network(3);
3000 // Create some initial channels
3001 create_announced_chan_between_nodes(&nodes, 0, 1);
3002 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3004 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3005 // Get the will-be-revoked local txn from nodes[2]
3006 let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
3007 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3008 // Revoke the old state
3009 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3011 let value = if use_dust {
3012 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3013 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3014 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().our_dust_limit_satoshis * 1000
3017 let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3018 let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3019 let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3021 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, 0));
3022 expect_pending_htlcs_forwardable!(nodes[2]);
3023 check_added_monitors!(nodes[2], 1);
3024 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3025 assert!(updates.update_add_htlcs.is_empty());
3026 assert!(updates.update_fulfill_htlcs.is_empty());
3027 assert!(updates.update_fail_malformed_htlcs.is_empty());
3028 assert_eq!(updates.update_fail_htlcs.len(), 1);
3029 assert!(updates.update_fee.is_none());
3030 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
3031 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3032 // Drop the last RAA from 3 -> 2
3034 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, 0));
3035 expect_pending_htlcs_forwardable!(nodes[2]);
3036 check_added_monitors!(nodes[2], 1);
3037 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3038 assert!(updates.update_add_htlcs.is_empty());
3039 assert!(updates.update_fulfill_htlcs.is_empty());
3040 assert!(updates.update_fail_malformed_htlcs.is_empty());
3041 assert_eq!(updates.update_fail_htlcs.len(), 1);
3042 assert!(updates.update_fee.is_none());
3043 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
3044 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed).unwrap();
3045 check_added_monitors!(nodes[1], 1);
3046 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3047 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3048 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
3049 check_added_monitors!(nodes[2], 1);
3051 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, 0));
3052 expect_pending_htlcs_forwardable!(nodes[2]);
3053 check_added_monitors!(nodes[2], 1);
3054 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3055 assert!(updates.update_add_htlcs.is_empty());
3056 assert!(updates.update_fulfill_htlcs.is_empty());
3057 assert!(updates.update_fail_malformed_htlcs.is_empty());
3058 assert_eq!(updates.update_fail_htlcs.len(), 1);
3059 assert!(updates.update_fee.is_none());
3060 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
3061 // At this point first_payment_hash has dropped out of the latest two commitment
3062 // transactions that nodes[1] is tracking...
3063 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed).unwrap();
3064 check_added_monitors!(nodes[1], 1);
3065 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3066 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3067 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
3068 check_added_monitors!(nodes[2], 1);
3070 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3071 // on nodes[2]'s RAA.
3072 let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
3073 let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3074 nodes[1].node.send_payment(route, fourth_payment_hash).unwrap();
3075 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3076 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3077 check_added_monitors!(nodes[1], 0);
3080 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa).unwrap();
3081 // One monitor for the new revocation preimage, no second on as we won't generate a new
3082 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3083 check_added_monitors!(nodes[1], 1);
3084 let events = nodes[1].node.get_and_clear_pending_events();
3085 assert_eq!(events.len(), 1);
3087 Event::PendingHTLCsForwardable { .. } => { },
3088 _ => panic!("Unexpected event"),
3090 // Deliberately don't process the pending fail-back so they all fail back at once after
3091 // block connection just like the !deliver_bs_raa case
3094 let mut failed_htlcs = HashSet::new();
3095 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3097 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
3098 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3100 let events = nodes[1].node.get_and_clear_pending_events();
3101 assert_eq!(events.len(), if deliver_bs_raa { 1 } else { 2 });
3103 Event::PaymentFailed { ref payment_hash, .. } => {
3104 assert_eq!(*payment_hash, fourth_payment_hash);
3106 _ => panic!("Unexpected event"),
3108 if !deliver_bs_raa {
3110 Event::PendingHTLCsForwardable { .. } => { },
3111 _ => panic!("Unexpected event"),
3114 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
3115 nodes[1].node.process_pending_htlc_forwards();
3116 check_added_monitors!(nodes[1], 1);
3118 let events = nodes[1].node.get_and_clear_pending_msg_events();
3119 assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
3120 match events[if deliver_bs_raa { 1 } else { 0 }] {
3121 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3122 _ => panic!("Unexpected event"),
3126 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
3127 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3128 assert_eq!(update_add_htlcs.len(), 1);
3129 assert!(update_fulfill_htlcs.is_empty());
3130 assert!(update_fail_htlcs.is_empty());
3131 assert!(update_fail_malformed_htlcs.is_empty());
3133 _ => panic!("Unexpected event"),
3136 match events[if deliver_bs_raa { 2 } else { 1 }] {
3137 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, ref commitment_signed, .. } } => {
3138 assert!(update_add_htlcs.is_empty());
3139 assert_eq!(update_fail_htlcs.len(), 3);
3140 assert!(update_fulfill_htlcs.is_empty());
3141 assert!(update_fail_malformed_htlcs.is_empty());
3142 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3144 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]).unwrap();
3145 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]).unwrap();
3146 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]).unwrap();
3148 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3150 let events = nodes[0].node.get_and_clear_pending_msg_events();
3151 // If we delievered B's RAA we got an unknown preimage error, not something
3152 // that we should update our routing table for.
3153 assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
3154 for event in events {
3156 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3157 _ => panic!("Unexpected event"),
3160 let events = nodes[0].node.get_and_clear_pending_events();
3161 assert_eq!(events.len(), 3);
3163 Event::PaymentFailed { ref payment_hash, .. } => {
3164 assert!(failed_htlcs.insert(payment_hash.0));
3166 _ => panic!("Unexpected event"),
3169 Event::PaymentFailed { ref payment_hash, .. } => {
3170 assert!(failed_htlcs.insert(payment_hash.0));
3172 _ => panic!("Unexpected event"),
3175 Event::PaymentFailed { ref payment_hash, .. } => {
3176 assert!(failed_htlcs.insert(payment_hash.0));
3178 _ => panic!("Unexpected event"),
3181 _ => panic!("Unexpected event"),
3184 assert!(failed_htlcs.contains(&first_payment_hash.0));
3185 assert!(failed_htlcs.contains(&second_payment_hash.0));
3186 assert!(failed_htlcs.contains(&third_payment_hash.0));
3190 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3191 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3192 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3193 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3194 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3198 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3199 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3200 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3201 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3202 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3206 fn test_htlc_ignore_latest_remote_commitment() {
3207 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3208 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3209 let nodes = create_network(2);
3210 create_announced_chan_between_nodes(&nodes, 0, 1);
3212 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3213 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
3214 check_closed_broadcast!(nodes[0]);
3216 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3217 assert_eq!(node_txn.len(), 2);
3219 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3220 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
3221 check_closed_broadcast!(nodes[1]);
3223 // Duplicate the block_connected call since this may happen due to other listeners
3224 // registering new transactions
3225 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
3229 fn test_force_close_fail_back() {
3230 // Check which HTLCs are failed-backwards on channel force-closure
3231 let mut nodes = create_network(3);
3232 create_announced_chan_between_nodes(&nodes, 0, 1);
3233 create_announced_chan_between_nodes(&nodes, 1, 2);
3235 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, 42).unwrap();
3237 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3239 let mut payment_event = {
3240 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
3241 check_added_monitors!(nodes[0], 1);
3243 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3244 assert_eq!(events.len(), 1);
3245 SendEvent::from_event(events.remove(0))
3248 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
3249 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3251 expect_pending_htlcs_forwardable!(nodes[1]);
3253 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3254 assert_eq!(events_2.len(), 1);
3255 payment_event = SendEvent::from_event(events_2.remove(0));
3256 assert_eq!(payment_event.msgs.len(), 1);
3258 check_added_monitors!(nodes[1], 1);
3259 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
3260 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
3261 check_added_monitors!(nodes[2], 1);
3262 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3264 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3265 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3266 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3268 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
3269 check_closed_broadcast!(nodes[2]);
3271 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3272 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3273 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3274 // back to nodes[1] upon timeout otherwise.
3275 assert_eq!(node_txn.len(), 1);
3279 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3280 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
3282 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3283 check_closed_broadcast!(nodes[1]);
3285 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3287 let mut monitors = nodes[2].chan_monitor.simple_monitor.monitors.lock().unwrap();
3288 monitors.get_mut(&OutPoint::new(Sha256dHash::from(&payment_event.commitment_msg.channel_id[..]), 0)).unwrap()
3289 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
3291 nodes[2].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
3292 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3293 assert_eq!(node_txn.len(), 1);
3294 assert_eq!(node_txn[0].input.len(), 1);
3295 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3296 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3297 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3299 check_spends!(node_txn[0], tx);
3303 fn test_unconf_chan() {
3304 // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
3305 let nodes = create_network(2);
3306 create_announced_chan_between_nodes(&nodes, 0, 1);
3308 let channel_state = nodes[0].node.channel_state.lock().unwrap();
3309 assert_eq!(channel_state.by_id.len(), 1);
3310 assert_eq!(channel_state.short_to_id.len(), 1);
3311 mem::drop(channel_state);
3313 let mut headers = Vec::new();
3314 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3315 headers.push(header.clone());
3317 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3318 headers.push(header.clone());
3320 while !headers.is_empty() {
3321 nodes[0].node.block_disconnected(&headers.pop().unwrap());
3323 check_closed_broadcast!(nodes[0]);
3324 let channel_state = nodes[0].node.channel_state.lock().unwrap();
3325 assert_eq!(channel_state.by_id.len(), 0);
3326 assert_eq!(channel_state.short_to_id.len(), 0);
3329 macro_rules! get_chan_reestablish_msgs {
3330 ($src_node: expr, $dst_node: expr) => {
3332 let mut res = Vec::with_capacity(1);
3333 for msg in $src_node.node.get_and_clear_pending_msg_events() {
3334 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
3335 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
3336 res.push(msg.clone());
3338 panic!("Unexpected event")
3346 macro_rules! handle_chan_reestablish_msgs {
3347 ($src_node: expr, $dst_node: expr) => {
3349 let msg_events = $src_node.node.get_and_clear_pending_msg_events();
3351 let funding_locked = if let Some(&MessageSendEvent::SendFundingLocked { ref node_id, ref msg }) = msg_events.get(0) {
3353 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
3359 let mut revoke_and_ack = None;
3360 let mut commitment_update = None;
3361 let order = if let Some(ev) = msg_events.get(idx) {
3364 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
3365 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
3366 revoke_and_ack = Some(msg.clone());
3367 RAACommitmentOrder::RevokeAndACKFirst
3369 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3370 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
3371 commitment_update = Some(updates.clone());
3372 RAACommitmentOrder::CommitmentFirst
3374 _ => panic!("Unexpected event"),
3377 RAACommitmentOrder::CommitmentFirst
3380 if let Some(ev) = msg_events.get(idx) {
3382 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
3383 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
3384 assert!(revoke_and_ack.is_none());
3385 revoke_and_ack = Some(msg.clone());
3387 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3388 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
3389 assert!(commitment_update.is_none());
3390 commitment_update = Some(updates.clone());
3392 _ => panic!("Unexpected event"),
3396 (funding_locked, revoke_and_ack, commitment_update, order)
3401 /// pending_htlc_adds includes both the holding cell and in-flight update_add_htlcs, whereas
3402 /// for claims/fails they are separated out.
3403 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)) {
3404 node_a.node.peer_connected(&node_b.node.get_our_node_id());
3405 let reestablish_1 = get_chan_reestablish_msgs!(node_a, node_b);
3406 node_b.node.peer_connected(&node_a.node.get_our_node_id());
3407 let reestablish_2 = get_chan_reestablish_msgs!(node_b, node_a);
3409 if send_funding_locked.0 {
3410 // If a expects a funding_locked, it better not think it has received a revoke_and_ack
3412 for reestablish in reestablish_1.iter() {
3413 assert_eq!(reestablish.next_remote_commitment_number, 0);
3416 if send_funding_locked.1 {
3417 // If b expects a funding_locked, it better not think it has received a revoke_and_ack
3419 for reestablish in reestablish_2.iter() {
3420 assert_eq!(reestablish.next_remote_commitment_number, 0);
3423 if send_funding_locked.0 || send_funding_locked.1 {
3424 // If we expect any funding_locked's, both sides better have set
3425 // next_local_commitment_number to 1
3426 for reestablish in reestablish_1.iter() {
3427 assert_eq!(reestablish.next_local_commitment_number, 1);
3429 for reestablish in reestablish_2.iter() {
3430 assert_eq!(reestablish.next_local_commitment_number, 1);
3434 let mut resp_1 = Vec::new();
3435 for msg in reestablish_1 {
3436 node_b.node.handle_channel_reestablish(&node_a.node.get_our_node_id(), &msg).unwrap();
3437 resp_1.push(handle_chan_reestablish_msgs!(node_b, node_a));
3439 if pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
3440 check_added_monitors!(node_b, 1);
3442 check_added_monitors!(node_b, 0);
3445 let mut resp_2 = Vec::new();
3446 for msg in reestablish_2 {
3447 node_a.node.handle_channel_reestablish(&node_b.node.get_our_node_id(), &msg).unwrap();
3448 resp_2.push(handle_chan_reestablish_msgs!(node_a, node_b));
3450 if pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
3451 check_added_monitors!(node_a, 1);
3453 check_added_monitors!(node_a, 0);
3456 // We dont yet support both needing updates, as that would require a different commitment dance:
3457 assert!((pending_htlc_adds.0 == 0 && pending_htlc_claims.0 == 0 && pending_cell_htlc_claims.0 == 0 && pending_cell_htlc_fails.0 == 0) ||
3458 (pending_htlc_adds.1 == 0 && pending_htlc_claims.1 == 0 && pending_cell_htlc_claims.1 == 0 && pending_cell_htlc_fails.1 == 0));
3460 for chan_msgs in resp_1.drain(..) {
3461 if send_funding_locked.0 {
3462 node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
3463 let announcement_event = node_a.node.get_and_clear_pending_msg_events();
3464 if !announcement_event.is_empty() {
3465 assert_eq!(announcement_event.len(), 1);
3466 if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
3467 //TODO: Test announcement_sigs re-sending
3468 } else { panic!("Unexpected event!"); }
3471 assert!(chan_msgs.0.is_none());
3474 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
3475 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
3476 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
3477 check_added_monitors!(node_a, 1);
3479 assert!(chan_msgs.1.is_none());
3481 if pending_htlc_adds.0 != 0 || pending_htlc_claims.0 != 0 || pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
3482 let commitment_update = chan_msgs.2.unwrap();
3483 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
3484 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.0 as usize);
3486 assert!(commitment_update.update_add_htlcs.is_empty());
3488 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
3489 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
3490 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
3491 for update_add in commitment_update.update_add_htlcs {
3492 node_a.node.handle_update_add_htlc(&node_b.node.get_our_node_id(), &update_add).unwrap();
3494 for update_fulfill in commitment_update.update_fulfill_htlcs {
3495 node_a.node.handle_update_fulfill_htlc(&node_b.node.get_our_node_id(), &update_fulfill).unwrap();
3497 for update_fail in commitment_update.update_fail_htlcs {
3498 node_a.node.handle_update_fail_htlc(&node_b.node.get_our_node_id(), &update_fail).unwrap();
3501 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
3502 commitment_signed_dance!(node_a, node_b, commitment_update.commitment_signed, false);
3504 node_a.node.handle_commitment_signed(&node_b.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
3505 check_added_monitors!(node_a, 1);
3506 let as_revoke_and_ack = get_event_msg!(node_a, MessageSendEvent::SendRevokeAndACK, node_b.node.get_our_node_id());
3507 // No commitment_signed so get_event_msg's assert(len == 1) passes
3508 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
3509 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
3510 check_added_monitors!(node_b, 1);
3513 assert!(chan_msgs.2.is_none());
3517 for chan_msgs in resp_2.drain(..) {
3518 if send_funding_locked.1 {
3519 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
3520 let announcement_event = node_b.node.get_and_clear_pending_msg_events();
3521 if !announcement_event.is_empty() {
3522 assert_eq!(announcement_event.len(), 1);
3523 if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
3524 //TODO: Test announcement_sigs re-sending
3525 } else { panic!("Unexpected event!"); }
3528 assert!(chan_msgs.0.is_none());
3531 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
3532 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
3533 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
3534 check_added_monitors!(node_b, 1);
3536 assert!(chan_msgs.1.is_none());
3538 if pending_htlc_adds.1 != 0 || pending_htlc_claims.1 != 0 || pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
3539 let commitment_update = chan_msgs.2.unwrap();
3540 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
3541 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.1 as usize);
3543 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
3544 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
3545 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
3546 for update_add in commitment_update.update_add_htlcs {
3547 node_b.node.handle_update_add_htlc(&node_a.node.get_our_node_id(), &update_add).unwrap();
3549 for update_fulfill in commitment_update.update_fulfill_htlcs {
3550 node_b.node.handle_update_fulfill_htlc(&node_a.node.get_our_node_id(), &update_fulfill).unwrap();
3552 for update_fail in commitment_update.update_fail_htlcs {
3553 node_b.node.handle_update_fail_htlc(&node_a.node.get_our_node_id(), &update_fail).unwrap();
3556 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
3557 commitment_signed_dance!(node_b, node_a, commitment_update.commitment_signed, false);
3559 node_b.node.handle_commitment_signed(&node_a.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
3560 check_added_monitors!(node_b, 1);
3561 let bs_revoke_and_ack = get_event_msg!(node_b, MessageSendEvent::SendRevokeAndACK, node_a.node.get_our_node_id());
3562 // No commitment_signed so get_event_msg's assert(len == 1) passes
3563 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
3564 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
3565 check_added_monitors!(node_a, 1);
3568 assert!(chan_msgs.2.is_none());
3574 fn test_simple_peer_disconnect() {
3575 // Test that we can reconnect when there are no lost messages
3576 let nodes = create_network(3);
3577 create_announced_chan_between_nodes(&nodes, 0, 1);
3578 create_announced_chan_between_nodes(&nodes, 1, 2);
3580 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3581 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3582 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3584 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3585 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3586 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3587 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3589 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3590 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3591 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3593 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3594 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3595 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3596 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3598 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3599 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3601 claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3);
3602 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
3604 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3606 let events = nodes[0].node.get_and_clear_pending_events();
3607 assert_eq!(events.len(), 2);
3609 Event::PaymentSent { payment_preimage } => {
3610 assert_eq!(payment_preimage, payment_preimage_3);
3612 _ => panic!("Unexpected event"),
3615 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
3616 assert_eq!(payment_hash, payment_hash_5);
3617 assert!(rejected_by_dest);
3619 _ => panic!("Unexpected event"),
3623 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3624 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3627 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
3628 // Test that we can reconnect when in-flight HTLC updates get dropped
3629 let mut nodes = create_network(2);
3630 if messages_delivered == 0 {
3631 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3632 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3634 create_announced_chan_between_nodes(&nodes, 0, 1);
3637 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels()), &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
3638 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
3640 let payment_event = {
3641 nodes[0].node.send_payment(route.clone(), payment_hash_1).unwrap();
3642 check_added_monitors!(nodes[0], 1);
3644 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3645 assert_eq!(events.len(), 1);
3646 SendEvent::from_event(events.remove(0))
3648 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3650 if messages_delivered < 2 {
3651 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3653 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
3654 if messages_delivered >= 3 {
3655 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
3656 check_added_monitors!(nodes[1], 1);
3657 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3659 if messages_delivered >= 4 {
3660 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
3661 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3662 check_added_monitors!(nodes[0], 1);
3664 if messages_delivered >= 5 {
3665 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
3666 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3667 // No commitment_signed so get_event_msg's assert(len == 1) passes
3668 check_added_monitors!(nodes[0], 1);
3670 if messages_delivered >= 6 {
3671 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
3672 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3673 check_added_monitors!(nodes[1], 1);
3680 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3681 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3682 if messages_delivered < 3 {
3683 // Even if the funding_locked messages get exchanged, as long as nothing further was
3684 // received on either side, both sides will need to resend them.
3685 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
3686 } else if messages_delivered == 3 {
3687 // nodes[0] still wants its RAA + commitment_signed
3688 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
3689 } else if messages_delivered == 4 {
3690 // nodes[0] still wants its commitment_signed
3691 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3692 } else if messages_delivered == 5 {
3693 // nodes[1] still wants its final RAA
3694 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3695 } else if messages_delivered == 6 {
3696 // Everything was delivered...
3697 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3700 let events_1 = nodes[1].node.get_and_clear_pending_events();
3701 assert_eq!(events_1.len(), 1);
3703 Event::PendingHTLCsForwardable { .. } => { },
3704 _ => panic!("Unexpected event"),
3707 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3708 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3709 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3711 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
3712 nodes[1].node.process_pending_htlc_forwards();
3714 let events_2 = nodes[1].node.get_and_clear_pending_events();
3715 assert_eq!(events_2.len(), 1);
3717 Event::PaymentReceived { ref payment_hash, amt } => {
3718 assert_eq!(payment_hash_1, *payment_hash);
3719 assert_eq!(amt, 1000000);
3721 _ => panic!("Unexpected event"),
3724 nodes[1].node.claim_funds(payment_preimage_1);
3725 check_added_monitors!(nodes[1], 1);
3727 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3728 assert_eq!(events_3.len(), 1);
3729 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3730 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3731 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3732 assert!(updates.update_add_htlcs.is_empty());
3733 assert!(updates.update_fail_htlcs.is_empty());
3734 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3735 assert!(updates.update_fail_malformed_htlcs.is_empty());
3736 assert!(updates.update_fee.is_none());
3737 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3739 _ => panic!("Unexpected event"),
3742 if messages_delivered >= 1 {
3743 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc).unwrap();
3745 let events_4 = nodes[0].node.get_and_clear_pending_events();
3746 assert_eq!(events_4.len(), 1);
3748 Event::PaymentSent { ref payment_preimage } => {
3749 assert_eq!(payment_preimage_1, *payment_preimage);
3751 _ => panic!("Unexpected event"),
3754 if messages_delivered >= 2 {
3755 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
3756 check_added_monitors!(nodes[0], 1);
3757 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3759 if messages_delivered >= 3 {
3760 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
3761 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3762 check_added_monitors!(nodes[1], 1);
3764 if messages_delivered >= 4 {
3765 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed).unwrap();
3766 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3767 // No commitment_signed so get_event_msg's assert(len == 1) passes
3768 check_added_monitors!(nodes[1], 1);
3770 if messages_delivered >= 5 {
3771 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
3772 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3773 check_added_monitors!(nodes[0], 1);
3780 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3781 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3782 if messages_delivered < 2 {
3783 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
3784 //TODO: Deduplicate PaymentSent events, then enable this if:
3785 //if messages_delivered < 1 {
3786 let events_4 = nodes[0].node.get_and_clear_pending_events();
3787 assert_eq!(events_4.len(), 1);
3789 Event::PaymentSent { ref payment_preimage } => {
3790 assert_eq!(payment_preimage_1, *payment_preimage);
3792 _ => panic!("Unexpected event"),
3795 } else if messages_delivered == 2 {
3796 // nodes[0] still wants its RAA + commitment_signed
3797 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
3798 } else if messages_delivered == 3 {
3799 // nodes[0] still wants its commitment_signed
3800 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
3801 } else if messages_delivered == 4 {
3802 // nodes[1] still wants its final RAA
3803 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3804 } else if messages_delivered == 5 {
3805 // Everything was delivered...
3806 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3809 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3810 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3811 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3813 // Channel should still work fine...
3814 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3815 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3819 fn test_drop_messages_peer_disconnect_a() {
3820 do_test_drop_messages_peer_disconnect(0);
3821 do_test_drop_messages_peer_disconnect(1);
3822 do_test_drop_messages_peer_disconnect(2);
3823 do_test_drop_messages_peer_disconnect(3);
3827 fn test_drop_messages_peer_disconnect_b() {
3828 do_test_drop_messages_peer_disconnect(4);
3829 do_test_drop_messages_peer_disconnect(5);
3830 do_test_drop_messages_peer_disconnect(6);
3834 fn test_funding_peer_disconnect() {
3835 // Test that we can lock in our funding tx while disconnected
3836 let nodes = create_network(2);
3837 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001);
3839 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3840 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3842 confirm_transaction(&nodes[0].chain_monitor, &tx, tx.version);
3843 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3844 assert_eq!(events_1.len(), 1);
3846 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3847 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3849 _ => panic!("Unexpected event"),
3852 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3854 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3855 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3857 confirm_transaction(&nodes[1].chain_monitor, &tx, tx.version);
3858 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3859 assert_eq!(events_2.len(), 2);
3861 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3862 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3864 _ => panic!("Unexpected event"),
3867 MessageSendEvent::SendAnnouncementSignatures { ref node_id, msg: _ } => {
3868 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3870 _ => panic!("Unexpected event"),
3873 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3875 // TODO: We shouldn't need to manually pass list_usable_chanels here once we support
3876 // rebroadcasting announcement_signatures upon reconnect.
3878 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels()), &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
3879 let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3880 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
3884 fn test_drop_messages_peer_disconnect_dual_htlc() {
3885 // Test that we can handle reconnecting when both sides of a channel have pending
3886 // commitment_updates when we disconnect.
3887 let mut nodes = create_network(2);
3888 create_announced_chan_between_nodes(&nodes, 0, 1);
3890 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3892 // Now try to send a second payment which will fail to send
3893 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
3894 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
3896 nodes[0].node.send_payment(route.clone(), payment_hash_2).unwrap();
3897 check_added_monitors!(nodes[0], 1);
3899 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3900 assert_eq!(events_1.len(), 1);
3902 MessageSendEvent::UpdateHTLCs { .. } => {},
3903 _ => panic!("Unexpected event"),
3906 assert!(nodes[1].node.claim_funds(payment_preimage_1));
3907 check_added_monitors!(nodes[1], 1);
3909 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3910 assert_eq!(events_2.len(), 1);
3912 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 } } => {
3913 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3914 assert!(update_add_htlcs.is_empty());
3915 assert_eq!(update_fulfill_htlcs.len(), 1);
3916 assert!(update_fail_htlcs.is_empty());
3917 assert!(update_fail_malformed_htlcs.is_empty());
3918 assert!(update_fee.is_none());
3920 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
3921 let events_3 = nodes[0].node.get_and_clear_pending_events();
3922 assert_eq!(events_3.len(), 1);
3924 Event::PaymentSent { ref payment_preimage } => {
3925 assert_eq!(*payment_preimage, payment_preimage_1);
3927 _ => panic!("Unexpected event"),
3930 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
3931 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3932 // No commitment_signed so get_event_msg's assert(len == 1) passes
3933 check_added_monitors!(nodes[0], 1);
3935 _ => panic!("Unexpected event"),
3938 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3939 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3941 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
3942 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3943 assert_eq!(reestablish_1.len(), 1);
3944 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
3945 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3946 assert_eq!(reestablish_2.len(), 1);
3948 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
3949 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3950 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
3951 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3953 assert!(as_resp.0.is_none());
3954 assert!(bs_resp.0.is_none());
3956 assert!(bs_resp.1.is_none());
3957 assert!(bs_resp.2.is_none());
3959 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3961 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3962 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3963 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3964 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3965 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3966 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]).unwrap();
3967 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed).unwrap();
3968 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3969 // No commitment_signed so get_event_msg's assert(len == 1) passes
3970 check_added_monitors!(nodes[1], 1);
3972 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap()).unwrap();
3973 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3974 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3975 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3976 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3977 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3978 assert!(bs_second_commitment_signed.update_fee.is_none());
3979 check_added_monitors!(nodes[1], 1);
3981 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
3982 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3983 assert!(as_commitment_signed.update_add_htlcs.is_empty());
3984 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
3985 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
3986 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
3987 assert!(as_commitment_signed.update_fee.is_none());
3988 check_added_monitors!(nodes[0], 1);
3990 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed).unwrap();
3991 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3992 // No commitment_signed so get_event_msg's assert(len == 1) passes
3993 check_added_monitors!(nodes[0], 1);
3995 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed).unwrap();
3996 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3997 // No commitment_signed so get_event_msg's assert(len == 1) passes
3998 check_added_monitors!(nodes[1], 1);
4000 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
4001 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4002 check_added_monitors!(nodes[1], 1);
4004 expect_pending_htlcs_forwardable!(nodes[1]);
4006 let events_5 = nodes[1].node.get_and_clear_pending_events();
4007 assert_eq!(events_5.len(), 1);
4009 Event::PaymentReceived { ref payment_hash, amt: _ } => {
4010 assert_eq!(payment_hash_2, *payment_hash);
4012 _ => panic!("Unexpected event"),
4015 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap();
4016 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4017 check_added_monitors!(nodes[0], 1);
4019 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4023 fn test_simple_monitor_permanent_update_fail() {
4024 // Test that we handle a simple permanent monitor update failure
4025 let mut nodes = create_network(2);
4026 create_announced_chan_between_nodes(&nodes, 0, 1);
4028 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
4029 let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
4031 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::PermanentFailure);
4032 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route, payment_hash_1) {} else { panic!(); }
4033 check_added_monitors!(nodes[0], 1);
4035 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4036 assert_eq!(events_1.len(), 2);
4038 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4039 _ => panic!("Unexpected event"),
4042 MessageSendEvent::HandleError { node_id, .. } => assert_eq!(node_id, nodes[1].node.get_our_node_id()),
4043 _ => panic!("Unexpected event"),
4046 // TODO: Once we hit the chain with the failure transaction we should check that we get a
4047 // PaymentFailed event
4049 assert_eq!(nodes[0].node.list_channels().len(), 0);
4052 fn do_test_simple_monitor_temporary_update_fail(disconnect: bool) {
4053 // Test that we can recover from a simple temporary monitor update failure optionally with
4054 // a disconnect in between
4055 let mut nodes = create_network(2);
4056 create_announced_chan_between_nodes(&nodes, 0, 1);
4058 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
4059 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
4061 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
4062 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route.clone(), payment_hash_1) {} else { panic!(); }
4063 check_added_monitors!(nodes[0], 1);
4065 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4066 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4067 assert_eq!(nodes[0].node.list_channels().len(), 1);
4070 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4071 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4072 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4075 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
4076 nodes[0].node.test_restore_channel_monitor();
4077 check_added_monitors!(nodes[0], 1);
4079 let mut events_2 = nodes[0].node.get_and_clear_pending_msg_events();
4080 assert_eq!(events_2.len(), 1);
4081 let payment_event = SendEvent::from_event(events_2.pop().unwrap());
4082 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
4083 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4084 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4086 expect_pending_htlcs_forwardable!(nodes[1]);
4088 let events_3 = nodes[1].node.get_and_clear_pending_events();
4089 assert_eq!(events_3.len(), 1);
4091 Event::PaymentReceived { ref payment_hash, amt } => {
4092 assert_eq!(payment_hash_1, *payment_hash);
4093 assert_eq!(amt, 1000000);
4095 _ => panic!("Unexpected event"),
4098 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_1);
4100 // Now set it to failed again...
4101 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
4102 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
4103 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route, payment_hash_2) {} else { panic!(); }
4104 check_added_monitors!(nodes[0], 1);
4106 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4107 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4108 assert_eq!(nodes[0].node.list_channels().len(), 1);
4111 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4112 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4113 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4116 // ...and make sure we can force-close a TemporaryFailure channel with a PermanentFailure
4117 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::PermanentFailure);
4118 nodes[0].node.test_restore_channel_monitor();
4119 check_added_monitors!(nodes[0], 1);
4120 check_closed_broadcast!(nodes[0]);
4122 // TODO: Once we hit the chain with the failure transaction we should check that we get a
4123 // PaymentFailed event
4125 assert_eq!(nodes[0].node.list_channels().len(), 0);
4129 fn test_simple_monitor_temporary_update_fail() {
4130 do_test_simple_monitor_temporary_update_fail(false);
4131 do_test_simple_monitor_temporary_update_fail(true);
4134 fn do_test_monitor_temporary_update_fail(disconnect_count: usize) {
4135 let disconnect_flags = 8 | 16;
4137 // Test that we can recover from a temporary monitor update failure with some in-flight
4138 // HTLCs going on at the same time potentially with some disconnection thrown in.
4139 // * First we route a payment, then get a temporary monitor update failure when trying to
4140 // route a second payment. We then claim the first payment.
4141 // * If disconnect_count is set, we will disconnect at this point (which is likely as
4142 // TemporaryFailure likely indicates net disconnect which resulted in failing to update
4143 // the ChannelMonitor on a watchtower).
4144 // * If !(disconnect_count & 16) we deliver a update_fulfill_htlc/CS for the first payment
4145 // immediately, otherwise we wait sconnect and deliver them via the reconnect
4146 // channel_reestablish processing (ie disconnect_count & 16 makes no sense if
4147 // disconnect_count & !disconnect_flags is 0).
4148 // * We then update the channel monitor, reconnecting if disconnect_count is set and walk
4149 // through message sending, potentially disconnect/reconnecting multiple times based on
4150 // disconnect_count, to get the update_fulfill_htlc through.
4151 // * We then walk through more message exchanges to get the original update_add_htlc
4152 // through, swapping message ordering based on disconnect_count & 8 and optionally
4153 // disconnect/reconnecting based on disconnect_count.
4154 let mut nodes = create_network(2);
4155 create_announced_chan_between_nodes(&nodes, 0, 1);
4157 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4159 // Now try to send a second payment which will fail to send
4160 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
4161 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
4163 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
4164 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route.clone(), payment_hash_2) {} else { panic!(); }
4165 check_added_monitors!(nodes[0], 1);
4167 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4168 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4169 assert_eq!(nodes[0].node.list_channels().len(), 1);
4171 // Claim the previous payment, which will result in a update_fulfill_htlc/CS from nodes[1]
4172 // but nodes[0] won't respond since it is frozen.
4173 assert!(nodes[1].node.claim_funds(payment_preimage_1));
4174 check_added_monitors!(nodes[1], 1);
4175 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4176 assert_eq!(events_2.len(), 1);
4177 let (bs_initial_fulfill, bs_initial_commitment_signed) = match events_2[0] {
4178 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 } } => {
4179 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4180 assert!(update_add_htlcs.is_empty());
4181 assert_eq!(update_fulfill_htlcs.len(), 1);
4182 assert!(update_fail_htlcs.is_empty());
4183 assert!(update_fail_malformed_htlcs.is_empty());
4184 assert!(update_fee.is_none());
4186 if (disconnect_count & 16) == 0 {
4187 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
4188 let events_3 = nodes[0].node.get_and_clear_pending_events();
4189 assert_eq!(events_3.len(), 1);
4191 Event::PaymentSent { ref payment_preimage } => {
4192 assert_eq!(*payment_preimage, payment_preimage_1);
4194 _ => panic!("Unexpected event"),
4197 if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::IgnoreError) }) = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed) {
4198 assert_eq!(err, "Previous monitor update failure prevented generation of RAA");
4199 } else { panic!(); }
4202 (update_fulfill_htlcs[0].clone(), commitment_signed.clone())
4204 _ => panic!("Unexpected event"),
4207 if disconnect_count & !disconnect_flags > 0 {
4208 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4209 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4212 // Now fix monitor updating...
4213 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
4214 nodes[0].node.test_restore_channel_monitor();
4215 check_added_monitors!(nodes[0], 1);
4217 macro_rules! disconnect_reconnect_peers { () => { {
4218 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4219 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4221 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
4222 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4223 assert_eq!(reestablish_1.len(), 1);
4224 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
4225 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4226 assert_eq!(reestablish_2.len(), 1);
4228 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
4229 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4230 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
4231 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4233 assert!(as_resp.0.is_none());
4234 assert!(bs_resp.0.is_none());
4236 (reestablish_1, reestablish_2, as_resp, bs_resp)
4239 let (payment_event, initial_revoke_and_ack) = if disconnect_count & !disconnect_flags > 0 {
4240 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4241 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4243 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
4244 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4245 assert_eq!(reestablish_1.len(), 1);
4246 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
4247 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4248 assert_eq!(reestablish_2.len(), 1);
4250 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
4251 check_added_monitors!(nodes[0], 0);
4252 let mut as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4253 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
4254 check_added_monitors!(nodes[1], 0);
4255 let mut bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4257 assert!(as_resp.0.is_none());
4258 assert!(bs_resp.0.is_none());
4260 assert!(bs_resp.1.is_none());
4261 if (disconnect_count & 16) == 0 {
4262 assert!(bs_resp.2.is_none());
4264 assert!(as_resp.1.is_some());
4265 assert!(as_resp.2.is_some());
4266 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4268 assert!(bs_resp.2.as_ref().unwrap().update_add_htlcs.is_empty());
4269 assert!(bs_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4270 assert!(bs_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4271 assert!(bs_resp.2.as_ref().unwrap().update_fee.is_none());
4272 assert!(bs_resp.2.as_ref().unwrap().update_fulfill_htlcs == vec![bs_initial_fulfill]);
4273 assert!(bs_resp.2.as_ref().unwrap().commitment_signed == bs_initial_commitment_signed);
4275 assert!(as_resp.1.is_none());
4277 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_resp.2.as_ref().unwrap().update_fulfill_htlcs[0]).unwrap();
4278 let events_3 = nodes[0].node.get_and_clear_pending_events();
4279 assert_eq!(events_3.len(), 1);
4281 Event::PaymentSent { ref payment_preimage } => {
4282 assert_eq!(*payment_preimage, payment_preimage_1);
4284 _ => panic!("Unexpected event"),
4287 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_resp.2.as_ref().unwrap().commitment_signed).unwrap();
4288 let as_resp_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4289 // No commitment_signed so get_event_msg's assert(len == 1) passes
4290 check_added_monitors!(nodes[0], 1);
4292 as_resp.1 = Some(as_resp_raa);
4296 if disconnect_count & !disconnect_flags > 1 {
4297 let (second_reestablish_1, second_reestablish_2, second_as_resp, second_bs_resp) = disconnect_reconnect_peers!();
4299 if (disconnect_count & 16) == 0 {
4300 assert!(reestablish_1 == second_reestablish_1);
4301 assert!(reestablish_2 == second_reestablish_2);
4303 assert!(as_resp == second_as_resp);
4304 assert!(bs_resp == second_bs_resp);
4307 (SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), as_resp.2.unwrap()), as_resp.1.unwrap())
4309 let mut events_4 = nodes[0].node.get_and_clear_pending_msg_events();
4310 assert_eq!(events_4.len(), 2);
4311 (SendEvent::from_event(events_4.remove(0)), match events_4[0] {
4312 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
4313 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
4316 _ => panic!("Unexpected event"),
4320 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
4322 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4323 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
4324 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4325 // nodes[1] is awaiting an RAA from nodes[0] still so get_event_msg's assert(len == 1) passes
4326 check_added_monitors!(nodes[1], 1);
4328 if disconnect_count & !disconnect_flags > 2 {
4329 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
4331 assert!(as_resp.1.unwrap() == initial_revoke_and_ack);
4332 assert!(bs_resp.1.unwrap() == bs_revoke_and_ack);
4334 assert!(as_resp.2.is_none());
4335 assert!(bs_resp.2.is_none());
4338 let as_commitment_update;
4339 let bs_second_commitment_update;
4341 macro_rules! handle_bs_raa { () => {
4342 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
4343 as_commitment_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4344 assert!(as_commitment_update.update_add_htlcs.is_empty());
4345 assert!(as_commitment_update.update_fulfill_htlcs.is_empty());
4346 assert!(as_commitment_update.update_fail_htlcs.is_empty());
4347 assert!(as_commitment_update.update_fail_malformed_htlcs.is_empty());
4348 assert!(as_commitment_update.update_fee.is_none());
4349 check_added_monitors!(nodes[0], 1);
4352 macro_rules! handle_initial_raa { () => {
4353 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &initial_revoke_and_ack).unwrap();
4354 bs_second_commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4355 assert!(bs_second_commitment_update.update_add_htlcs.is_empty());
4356 assert!(bs_second_commitment_update.update_fulfill_htlcs.is_empty());
4357 assert!(bs_second_commitment_update.update_fail_htlcs.is_empty());
4358 assert!(bs_second_commitment_update.update_fail_malformed_htlcs.is_empty());
4359 assert!(bs_second_commitment_update.update_fee.is_none());
4360 check_added_monitors!(nodes[1], 1);
4363 if (disconnect_count & 8) == 0 {
4366 if disconnect_count & !disconnect_flags > 3 {
4367 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
4369 assert!(as_resp.1.unwrap() == initial_revoke_and_ack);
4370 assert!(bs_resp.1.is_none());
4372 assert!(as_resp.2.unwrap() == as_commitment_update);
4373 assert!(bs_resp.2.is_none());
4375 assert!(as_resp.3 == RAACommitmentOrder::RevokeAndACKFirst);
4378 handle_initial_raa!();
4380 if disconnect_count & !disconnect_flags > 4 {
4381 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
4383 assert!(as_resp.1.is_none());
4384 assert!(bs_resp.1.is_none());
4386 assert!(as_resp.2.unwrap() == as_commitment_update);
4387 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
4390 handle_initial_raa!();
4392 if disconnect_count & !disconnect_flags > 3 {
4393 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
4395 assert!(as_resp.1.is_none());
4396 assert!(bs_resp.1.unwrap() == bs_revoke_and_ack);
4398 assert!(as_resp.2.is_none());
4399 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
4401 assert!(bs_resp.3 == RAACommitmentOrder::RevokeAndACKFirst);
4406 if disconnect_count & !disconnect_flags > 4 {
4407 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
4409 assert!(as_resp.1.is_none());
4410 assert!(bs_resp.1.is_none());
4412 assert!(as_resp.2.unwrap() == as_commitment_update);
4413 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
4417 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_update.commitment_signed).unwrap();
4418 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4419 // No commitment_signed so get_event_msg's assert(len == 1) passes
4420 check_added_monitors!(nodes[0], 1);
4422 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_update.commitment_signed).unwrap();
4423 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4424 // No commitment_signed so get_event_msg's assert(len == 1) passes
4425 check_added_monitors!(nodes[1], 1);
4427 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
4428 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4429 check_added_monitors!(nodes[1], 1);
4431 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap();
4432 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4433 check_added_monitors!(nodes[0], 1);
4435 expect_pending_htlcs_forwardable!(nodes[1]);
4437 let events_5 = nodes[1].node.get_and_clear_pending_events();
4438 assert_eq!(events_5.len(), 1);
4440 Event::PaymentReceived { ref payment_hash, amt } => {
4441 assert_eq!(payment_hash_2, *payment_hash);
4442 assert_eq!(amt, 1000000);
4444 _ => panic!("Unexpected event"),
4447 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4451 fn test_monitor_temporary_update_fail_a() {
4452 do_test_monitor_temporary_update_fail(0);
4453 do_test_monitor_temporary_update_fail(1);
4454 do_test_monitor_temporary_update_fail(2);
4455 do_test_monitor_temporary_update_fail(3);
4456 do_test_monitor_temporary_update_fail(4);
4457 do_test_monitor_temporary_update_fail(5);
4461 fn test_monitor_temporary_update_fail_b() {
4462 do_test_monitor_temporary_update_fail(2 | 8);
4463 do_test_monitor_temporary_update_fail(3 | 8);
4464 do_test_monitor_temporary_update_fail(4 | 8);
4465 do_test_monitor_temporary_update_fail(5 | 8);
4469 fn test_monitor_temporary_update_fail_c() {
4470 do_test_monitor_temporary_update_fail(1 | 16);
4471 do_test_monitor_temporary_update_fail(2 | 16);
4472 do_test_monitor_temporary_update_fail(3 | 16);
4473 do_test_monitor_temporary_update_fail(2 | 8 | 16);
4474 do_test_monitor_temporary_update_fail(3 | 8 | 16);
4478 fn test_monitor_update_fail_cs() {
4479 // Tests handling of a monitor update failure when processing an incoming commitment_signed
4480 let mut nodes = create_network(2);
4481 create_announced_chan_between_nodes(&nodes, 0, 1);
4483 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
4484 let (payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4485 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
4486 check_added_monitors!(nodes[0], 1);
4488 let send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4489 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
4491 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
4492 if let msgs::HandleError { err, action: Some(msgs::ErrorAction::IgnoreError) } = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_event.commitment_msg).unwrap_err() {
4493 assert_eq!(err, "Failed to update ChannelMonitor");
4494 } else { panic!(); }
4495 check_added_monitors!(nodes[1], 1);
4496 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4498 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
4499 nodes[1].node.test_restore_channel_monitor();
4500 check_added_monitors!(nodes[1], 1);
4501 let responses = nodes[1].node.get_and_clear_pending_msg_events();
4502 assert_eq!(responses.len(), 2);
4504 match responses[0] {
4505 MessageSendEvent::SendRevokeAndACK { ref msg, ref node_id } => {
4506 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4507 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &msg).unwrap();
4508 check_added_monitors!(nodes[0], 1);
4510 _ => panic!("Unexpected event"),
4512 match responses[1] {
4513 MessageSendEvent::UpdateHTLCs { ref updates, ref node_id } => {
4514 assert!(updates.update_add_htlcs.is_empty());
4515 assert!(updates.update_fulfill_htlcs.is_empty());
4516 assert!(updates.update_fail_htlcs.is_empty());
4517 assert!(updates.update_fail_malformed_htlcs.is_empty());
4518 assert!(updates.update_fee.is_none());
4519 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4521 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
4522 if let msgs::HandleError { err, action: Some(msgs::ErrorAction::IgnoreError) } = nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &updates.commitment_signed).unwrap_err() {
4523 assert_eq!(err, "Failed to update ChannelMonitor");
4524 } else { panic!(); }
4525 check_added_monitors!(nodes[0], 1);
4526 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4528 _ => panic!("Unexpected event"),
4531 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
4532 nodes[0].node.test_restore_channel_monitor();
4533 check_added_monitors!(nodes[0], 1);
4535 let final_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4536 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &final_raa).unwrap();
4537 check_added_monitors!(nodes[1], 1);
4539 expect_pending_htlcs_forwardable!(nodes[1]);
4541 let events = nodes[1].node.get_and_clear_pending_events();
4542 assert_eq!(events.len(), 1);
4544 Event::PaymentReceived { payment_hash, amt } => {
4545 assert_eq!(payment_hash, our_payment_hash);
4546 assert_eq!(amt, 1000000);
4548 _ => panic!("Unexpected event"),
4551 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
4554 fn do_test_monitor_update_fail_raa(test_ignore_second_cs: bool) {
4555 // Tests handling of a monitor update failure when processing an incoming RAA
4556 let mut nodes = create_network(3);
4557 create_announced_chan_between_nodes(&nodes, 0, 1);
4558 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4560 // Rebalance a bit so that we can send backwards from 2 to 1.
4561 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 5000000);
4563 // Route a first payment that we'll fail backwards
4564 let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
4566 // Fail the payment backwards, failing the monitor update on nodes[1]'s receipt of the RAA
4567 assert!(nodes[2].node.fail_htlc_backwards(&payment_hash_1, 0));
4568 expect_pending_htlcs_forwardable!(nodes[2]);
4569 check_added_monitors!(nodes[2], 1);
4571 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4572 assert!(updates.update_add_htlcs.is_empty());
4573 assert!(updates.update_fulfill_htlcs.is_empty());
4574 assert_eq!(updates.update_fail_htlcs.len(), 1);
4575 assert!(updates.update_fail_malformed_htlcs.is_empty());
4576 assert!(updates.update_fee.is_none());
4577 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
4579 let bs_revoke_and_ack = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
4580 check_added_monitors!(nodes[0], 0);
4582 // While the second channel is AwaitingRAA, forward a second payment to get it into the
4584 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
4585 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
4586 nodes[0].node.send_payment(route, payment_hash_2).unwrap();
4587 check_added_monitors!(nodes[0], 1);
4589 let mut send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4590 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
4591 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false);
4593 expect_pending_htlcs_forwardable!(nodes[1]);
4594 check_added_monitors!(nodes[1], 0);
4595 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4597 // Now fail monitor updating.
4598 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
4599 if let msgs::HandleError { err, action: Some(msgs::ErrorAction::IgnoreError) } = nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack).unwrap_err() {
4600 assert_eq!(err, "Failed to update ChannelMonitor");
4601 } else { panic!(); }
4602 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4603 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4604 check_added_monitors!(nodes[1], 1);
4606 // Attempt to forward a third payment but fail due to the second channel being unavailable
4609 let (_, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
4610 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
4611 nodes[0].node.send_payment(route, payment_hash_3).unwrap();
4612 check_added_monitors!(nodes[0], 1);
4614 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(()); // We succeed in updating the monitor for the first channel
4615 send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4616 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
4617 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false, true);
4618 check_added_monitors!(nodes[1], 0);
4620 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4621 assert_eq!(events_2.len(), 1);
4622 match events_2.remove(0) {
4623 MessageSendEvent::UpdateHTLCs { node_id, updates } => {
4624 assert_eq!(node_id, nodes[0].node.get_our_node_id());
4625 assert!(updates.update_fulfill_htlcs.is_empty());
4626 assert_eq!(updates.update_fail_htlcs.len(), 1);
4627 assert!(updates.update_fail_malformed_htlcs.is_empty());
4628 assert!(updates.update_add_htlcs.is_empty());
4629 assert!(updates.update_fee.is_none());
4631 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
4632 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
4634 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4635 assert_eq!(msg_events.len(), 1);
4636 match msg_events[0] {
4637 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
4638 assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
4639 assert_eq!(msg.contents.flags & 2, 2); // temp disabled
4641 _ => panic!("Unexpected event"),
4644 let events = nodes[0].node.get_and_clear_pending_events();
4645 assert_eq!(events.len(), 1);
4646 if let Event::PaymentFailed { payment_hash, rejected_by_dest, .. } = events[0] {
4647 assert_eq!(payment_hash, payment_hash_3);
4648 assert!(!rejected_by_dest);
4649 } else { panic!("Unexpected event!"); }
4651 _ => panic!("Unexpected event type!"),
4654 let (payment_preimage_4, payment_hash_4) = if test_ignore_second_cs {
4655 // Try to route another payment backwards from 2 to make sure 1 holds off on responding
4656 let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[0]);
4657 let route = nodes[2].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
4658 nodes[2].node.send_payment(route, payment_hash_4).unwrap();
4659 check_added_monitors!(nodes[2], 1);
4661 send_event = SendEvent::from_event(nodes[2].node.get_and_clear_pending_msg_events().remove(0));
4662 nodes[1].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
4663 if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::IgnoreError) }) = nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &send_event.commitment_msg) {
4664 assert_eq!(err, "Previous monitor update failure prevented generation of RAA");
4665 } else { panic!(); }
4666 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4667 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4668 (Some(payment_preimage_4), Some(payment_hash_4))
4669 } else { (None, None) };
4671 // Restore monitor updating, ensuring we immediately get a fail-back update and a
4672 // update_add update.
4673 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
4674 nodes[1].node.test_restore_channel_monitor();
4675 check_added_monitors!(nodes[1], 1);
4676 expect_pending_htlcs_forwardable!(nodes[1]);
4677 check_added_monitors!(nodes[1], 1);
4679 let mut events_3 = nodes[1].node.get_and_clear_pending_msg_events();
4680 if test_ignore_second_cs {
4681 assert_eq!(events_3.len(), 3);
4683 assert_eq!(events_3.len(), 2);
4686 // Note that the ordering of the events for different nodes is non-prescriptive, though the
4687 // ordering of the two events that both go to nodes[2] have to stay in the same order.
4688 let messages_a = match events_3.pop().unwrap() {
4689 MessageSendEvent::UpdateHTLCs { node_id, mut updates } => {
4690 assert_eq!(node_id, nodes[0].node.get_our_node_id());
4691 assert!(updates.update_fulfill_htlcs.is_empty());
4692 assert_eq!(updates.update_fail_htlcs.len(), 1);
4693 assert!(updates.update_fail_malformed_htlcs.is_empty());
4694 assert!(updates.update_add_htlcs.is_empty());
4695 assert!(updates.update_fee.is_none());
4696 (updates.update_fail_htlcs.remove(0), updates.commitment_signed)
4698 _ => panic!("Unexpected event type!"),
4700 let raa = if test_ignore_second_cs {
4701 match events_3.remove(1) {
4702 MessageSendEvent::SendRevokeAndACK { node_id, msg } => {
4703 assert_eq!(node_id, nodes[2].node.get_our_node_id());
4706 _ => panic!("Unexpected event"),
4709 let send_event_b = SendEvent::from_event(events_3.remove(0));
4710 assert_eq!(send_event_b.node_id, nodes[2].node.get_our_node_id());
4712 // Now deliver the new messages...
4714 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &messages_a.0).unwrap();
4715 commitment_signed_dance!(nodes[0], nodes[1], messages_a.1, false);
4716 let events_4 = nodes[0].node.get_and_clear_pending_events();
4717 assert_eq!(events_4.len(), 1);
4718 if let Event::PaymentFailed { payment_hash, rejected_by_dest, .. } = events_4[0] {
4719 assert_eq!(payment_hash, payment_hash_1);
4720 assert!(rejected_by_dest);
4721 } else { panic!("Unexpected event!"); }
4723 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event_b.msgs[0]).unwrap();
4724 if test_ignore_second_cs {
4725 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_event_b.commitment_msg).unwrap();
4726 check_added_monitors!(nodes[2], 1);
4727 let bs_revoke_and_ack = get_event_msg!(nodes[2], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4728 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa.unwrap()).unwrap();
4729 check_added_monitors!(nodes[2], 1);
4730 let bs_cs = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4731 assert!(bs_cs.update_add_htlcs.is_empty());
4732 assert!(bs_cs.update_fail_htlcs.is_empty());
4733 assert!(bs_cs.update_fail_malformed_htlcs.is_empty());
4734 assert!(bs_cs.update_fulfill_htlcs.is_empty());
4735 assert!(bs_cs.update_fee.is_none());
4737 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
4738 check_added_monitors!(nodes[1], 1);
4739 let as_cs = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
4740 assert!(as_cs.update_add_htlcs.is_empty());
4741 assert!(as_cs.update_fail_htlcs.is_empty());
4742 assert!(as_cs.update_fail_malformed_htlcs.is_empty());
4743 assert!(as_cs.update_fulfill_htlcs.is_empty());
4744 assert!(as_cs.update_fee.is_none());
4746 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_cs.commitment_signed).unwrap();
4747 check_added_monitors!(nodes[1], 1);
4748 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
4750 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_cs.commitment_signed).unwrap();
4751 check_added_monitors!(nodes[2], 1);
4752 let bs_second_raa = get_event_msg!(nodes[2], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4754 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
4755 check_added_monitors!(nodes[2], 1);
4756 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
4758 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_second_raa).unwrap();
4759 check_added_monitors!(nodes[1], 1);
4760 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4762 commitment_signed_dance!(nodes[2], nodes[1], send_event_b.commitment_msg, false);
4765 expect_pending_htlcs_forwardable!(nodes[2]);
4767 let events_6 = nodes[2].node.get_and_clear_pending_events();
4768 assert_eq!(events_6.len(), 1);
4770 Event::PaymentReceived { payment_hash, .. } => { assert_eq!(payment_hash, payment_hash_2); },
4771 _ => panic!("Unexpected event"),
4774 if test_ignore_second_cs {
4775 expect_pending_htlcs_forwardable!(nodes[1]);
4776 check_added_monitors!(nodes[1], 1);
4778 send_event = SendEvent::from_node(&nodes[1]);
4779 assert_eq!(send_event.node_id, nodes[0].node.get_our_node_id());
4780 assert_eq!(send_event.msgs.len(), 1);
4781 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
4782 commitment_signed_dance!(nodes[0], nodes[1], send_event.commitment_msg, false);
4784 expect_pending_htlcs_forwardable!(nodes[0]);
4786 let events_9 = nodes[0].node.get_and_clear_pending_events();
4787 assert_eq!(events_9.len(), 1);
4789 Event::PaymentReceived { payment_hash, .. } => assert_eq!(payment_hash, payment_hash_4.unwrap()),
4790 _ => panic!("Unexpected event"),
4792 claim_payment(&nodes[2], &[&nodes[1], &nodes[0]], payment_preimage_4.unwrap());
4795 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
4799 fn test_monitor_update_fail_raa() {
4800 do_test_monitor_update_fail_raa(false);
4801 do_test_monitor_update_fail_raa(true);
4805 fn test_monitor_update_fail_reestablish() {
4806 // Simple test for message retransmission after monitor update failure on
4807 // channel_reestablish generating a monitor update (which comes from freeing holding cell
4809 let mut nodes = create_network(3);
4810 create_announced_chan_between_nodes(&nodes, 0, 1);
4811 create_announced_chan_between_nodes(&nodes, 1, 2);
4813 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
4815 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4816 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4818 assert!(nodes[2].node.claim_funds(our_payment_preimage));
4819 check_added_monitors!(nodes[2], 1);
4820 let mut updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4821 assert!(updates.update_add_htlcs.is_empty());
4822 assert!(updates.update_fail_htlcs.is_empty());
4823 assert!(updates.update_fail_malformed_htlcs.is_empty());
4824 assert!(updates.update_fee.is_none());
4825 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4826 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
4827 check_added_monitors!(nodes[1], 1);
4828 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4829 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
4831 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
4832 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
4833 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
4835 let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
4836 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4838 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish).unwrap();
4840 if let msgs::HandleError { err, action: Some(msgs::ErrorAction::IgnoreError) } = nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish).unwrap_err() {
4841 assert_eq!(err, "Failed to update ChannelMonitor");
4842 } else { panic!(); }
4843 check_added_monitors!(nodes[1], 1);
4845 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4846 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4848 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
4849 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
4851 assert!(as_reestablish == get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id()));
4852 assert!(bs_reestablish == get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id()));
4854 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish).unwrap();
4856 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish).unwrap();
4857 check_added_monitors!(nodes[1], 0);
4858 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4860 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
4861 nodes[1].node.test_restore_channel_monitor();
4862 check_added_monitors!(nodes[1], 1);
4864 updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4865 assert!(updates.update_add_htlcs.is_empty());
4866 assert!(updates.update_fail_htlcs.is_empty());
4867 assert!(updates.update_fail_malformed_htlcs.is_empty());
4868 assert!(updates.update_fee.is_none());
4869 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4870 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
4871 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
4873 let events = nodes[0].node.get_and_clear_pending_events();
4874 assert_eq!(events.len(), 1);
4876 Event::PaymentSent { payment_preimage, .. } => assert_eq!(payment_preimage, our_payment_preimage),
4877 _ => panic!("Unexpected event"),
4882 fn test_invalid_channel_announcement() {
4883 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
4884 let secp_ctx = Secp256k1::new();
4885 let nodes = create_network(2);
4887 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1]);
4889 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
4890 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
4891 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4892 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4894 let _ = nodes[0].router.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id : as_chan.get_short_channel_id().unwrap(), is_permanent: false } );
4896 let as_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &as_chan.get_local_keys().funding_key);
4897 let bs_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &bs_chan.get_local_keys().funding_key);
4899 let as_network_key = nodes[0].node.get_our_node_id();
4900 let bs_network_key = nodes[1].node.get_our_node_id();
4902 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
4904 let mut chan_announcement;
4906 macro_rules! dummy_unsigned_msg {
4908 msgs::UnsignedChannelAnnouncement {
4909 features: msgs::GlobalFeatures::new(),
4910 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
4911 short_channel_id: as_chan.get_short_channel_id().unwrap(),
4912 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
4913 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
4914 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
4915 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
4916 excess_data: Vec::new(),
4921 macro_rules! sign_msg {
4922 ($unsigned_msg: expr) => {
4923 let msghash = Message::from_slice(&Sha256dHash::from_data(&$unsigned_msg.encode()[..])[..]).unwrap();
4924 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_local_keys().funding_key);
4925 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_local_keys().funding_key);
4926 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
4927 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
4928 chan_announcement = msgs::ChannelAnnouncement {
4929 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
4930 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
4931 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
4932 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
4933 contents: $unsigned_msg
4938 let unsigned_msg = dummy_unsigned_msg!();
4939 sign_msg!(unsigned_msg);
4940 assert_eq!(nodes[0].router.handle_channel_announcement(&chan_announcement).unwrap(), true);
4941 let _ = nodes[0].router.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id : as_chan.get_short_channel_id().unwrap(), is_permanent: false } );
4943 // Configured with Network::Testnet
4944 let mut unsigned_msg = dummy_unsigned_msg!();
4945 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.bitcoin_hash();
4946 sign_msg!(unsigned_msg);
4947 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
4949 let mut unsigned_msg = dummy_unsigned_msg!();
4950 unsigned_msg.chain_hash = Sha256dHash::from_data(&[1,2,3,4,5,6,7,8,9]);
4951 sign_msg!(unsigned_msg);
4952 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
4955 struct VecWriter(Vec<u8>);
4956 impl Writer for VecWriter {
4957 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
4958 self.0.extend_from_slice(buf);
4961 fn size_hint(&mut self, size: usize) {
4962 self.0.reserve_exact(size);
4967 fn test_no_txn_manager_serialize_deserialize() {
4968 let mut nodes = create_network(2);
4970 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001);
4972 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4974 let nodes_0_serialized = nodes[0].node.encode();
4975 let mut chan_0_monitor_serialized = VecWriter(Vec::new());
4976 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
4978 nodes[0].chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), Arc::new(test_utils::TestLogger::new())));
4979 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4980 let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
4981 assert!(chan_0_monitor_read.is_empty());
4983 let mut nodes_0_read = &nodes_0_serialized[..];
4984 let config = UserConfig::new();
4985 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
4986 let (_, nodes_0_deserialized) = {
4987 let mut channel_monitors = HashMap::new();
4988 channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
4989 <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4990 default_config: config,
4992 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
4993 monitor: nodes[0].chan_monitor.clone(),
4994 chain_monitor: nodes[0].chain_monitor.clone(),
4995 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4996 logger: Arc::new(test_utils::TestLogger::new()),
4997 channel_monitors: &channel_monitors,
5000 assert!(nodes_0_read.is_empty());
5002 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
5003 nodes[0].node = Arc::new(nodes_0_deserialized);
5004 let nodes_0_as_listener: Arc<ChainListener> = nodes[0].node.clone();
5005 nodes[0].chain_monitor.register_listener(Arc::downgrade(&nodes_0_as_listener));
5006 assert_eq!(nodes[0].node.list_channels().len(), 1);
5007 check_added_monitors!(nodes[0], 1);
5009 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
5010 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
5011 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
5012 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
5014 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
5015 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5016 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
5017 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5019 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
5020 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
5021 for node in nodes.iter() {
5022 assert!(node.router.handle_channel_announcement(&announcement).unwrap());
5023 node.router.handle_channel_update(&as_update).unwrap();
5024 node.router.handle_channel_update(&bs_update).unwrap();
5027 send_payment(&nodes[0], &[&nodes[1]], 1000000);
5031 fn test_simple_manager_serialize_deserialize() {
5032 let mut nodes = create_network(2);
5033 create_announced_chan_between_nodes(&nodes, 0, 1);
5035 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
5036 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
5038 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5040 let nodes_0_serialized = nodes[0].node.encode();
5041 let mut chan_0_monitor_serialized = VecWriter(Vec::new());
5042 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
5044 nodes[0].chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), Arc::new(test_utils::TestLogger::new())));
5045 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
5046 let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
5047 assert!(chan_0_monitor_read.is_empty());
5049 let mut nodes_0_read = &nodes_0_serialized[..];
5050 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
5051 let (_, nodes_0_deserialized) = {
5052 let mut channel_monitors = HashMap::new();
5053 channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
5054 <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
5055 default_config: UserConfig::new(),
5057 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
5058 monitor: nodes[0].chan_monitor.clone(),
5059 chain_monitor: nodes[0].chain_monitor.clone(),
5060 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
5061 logger: Arc::new(test_utils::TestLogger::new()),
5062 channel_monitors: &channel_monitors,
5065 assert!(nodes_0_read.is_empty());
5067 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
5068 nodes[0].node = Arc::new(nodes_0_deserialized);
5069 check_added_monitors!(nodes[0], 1);
5071 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5073 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
5074 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
5078 fn test_manager_serialize_deserialize_inconsistent_monitor() {
5079 // Test deserializing a ChannelManager with a out-of-date ChannelMonitor
5080 let mut nodes = create_network(4);
5081 create_announced_chan_between_nodes(&nodes, 0, 1);
5082 create_announced_chan_between_nodes(&nodes, 2, 0);
5083 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3);
5085 let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
5087 // Serialize the ChannelManager here, but the monitor we keep up-to-date
5088 let nodes_0_serialized = nodes[0].node.encode();
5090 route_payment(&nodes[0], &[&nodes[3]], 1000000);
5091 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5092 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5093 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5095 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
5097 let mut node_0_monitors_serialized = Vec::new();
5098 for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
5099 let mut writer = VecWriter(Vec::new());
5100 monitor.1.write_for_disk(&mut writer).unwrap();
5101 node_0_monitors_serialized.push(writer.0);
5104 nodes[0].chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), Arc::new(test_utils::TestLogger::new())));
5105 let mut node_0_monitors = Vec::new();
5106 for serialized in node_0_monitors_serialized.iter() {
5107 let mut read = &serialized[..];
5108 let (_, monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut read, Arc::new(test_utils::TestLogger::new())).unwrap();
5109 assert!(read.is_empty());
5110 node_0_monitors.push(monitor);
5113 let mut nodes_0_read = &nodes_0_serialized[..];
5114 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
5115 let (_, nodes_0_deserialized) = <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
5116 default_config: UserConfig::new(),
5118 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
5119 monitor: nodes[0].chan_monitor.clone(),
5120 chain_monitor: nodes[0].chain_monitor.clone(),
5121 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
5122 logger: Arc::new(test_utils::TestLogger::new()),
5123 channel_monitors: &node_0_monitors.iter().map(|monitor| { (monitor.get_funding_txo().unwrap(), monitor) }).collect(),
5125 assert!(nodes_0_read.is_empty());
5127 { // Channel close should result in a commitment tx and an HTLC tx
5128 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5129 assert_eq!(txn.len(), 2);
5130 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
5131 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
5134 for monitor in node_0_monitors.drain(..) {
5135 assert!(nodes[0].chan_monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor).is_ok());
5136 check_added_monitors!(nodes[0], 1);
5138 nodes[0].node = Arc::new(nodes_0_deserialized);
5140 // nodes[1] and nodes[2] have no lost state with nodes[0]...
5141 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5142 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5143 //... and we can even still claim the payment!
5144 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
5146 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id());
5147 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
5148 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id());
5149 if let Err(msgs::HandleError { action: Some(msgs::ErrorAction::SendErrorMessage { msg }), .. }) = nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish) {
5150 assert_eq!(msg.channel_id, channel_id);
5151 } else { panic!("Unexpected result"); }
5154 macro_rules! check_spendable_outputs {
5155 ($node: expr, $der_idx: expr) => {
5157 let events = $node.chan_monitor.simple_monitor.get_and_clear_pending_events();
5158 let mut txn = Vec::new();
5159 for event in events {
5161 Event::SpendableOutputs { ref outputs } => {
5162 for outp in outputs {
5164 SpendableOutputDescriptor::DynamicOutputP2WPKH { ref outpoint, ref key, ref output } => {
5166 previous_output: outpoint.clone(),
5167 script_sig: Script::new(),
5169 witness: Vec::new(),
5172 script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
5173 value: output.value,
5175 let mut spend_tx = Transaction {
5181 let secp_ctx = Secp256k1::new();
5182 let remotepubkey = PublicKey::from_secret_key(&secp_ctx, &key);
5183 let witness_script = Address::p2pkh(&remotepubkey, Network::Testnet).script_pubkey();
5184 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
5185 let remotesig = secp_ctx.sign(&sighash, key);
5186 spend_tx.input[0].witness.push(remotesig.serialize_der(&secp_ctx).to_vec());
5187 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
5188 spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
5191 SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref key, ref witness_script, ref to_self_delay, ref output } => {
5193 previous_output: outpoint.clone(),
5194 script_sig: Script::new(),
5195 sequence: *to_self_delay as u32,
5196 witness: Vec::new(),
5199 script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
5200 value: output.value,
5202 let mut spend_tx = Transaction {
5208 let secp_ctx = Secp256k1::new();
5209 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], witness_script, output.value)[..]).unwrap();
5210 let local_delaysig = secp_ctx.sign(&sighash, key);
5211 spend_tx.input[0].witness.push(local_delaysig.serialize_der(&secp_ctx).to_vec());
5212 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
5213 spend_tx.input[0].witness.push(vec!(0));
5214 spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
5217 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
5218 let secp_ctx = Secp256k1::new();
5220 previous_output: outpoint.clone(),
5221 script_sig: Script::new(),
5223 witness: Vec::new(),
5226 script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
5227 value: output.value,
5229 let mut spend_tx = Transaction {
5233 output: vec![outp.clone()],
5236 match ExtendedPrivKey::new_master(&secp_ctx, Network::Testnet, &$node.node_seed) {
5238 match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx)) {
5240 Err(_) => panic!("Your RNG is busted"),
5243 Err(_) => panic!("Your rng is busted"),
5246 let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
5247 let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
5248 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
5249 let sig = secp_ctx.sign(&sighash, &secret.secret_key);
5250 spend_tx.input[0].witness.push(sig.serialize_der(&secp_ctx).to_vec());
5251 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
5252 spend_tx.input[0].witness.push(pubkey.serialize().to_vec());
5258 _ => panic!("Unexpected event"),
5267 fn test_claim_sizeable_push_msat() {
5268 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
5269 let nodes = create_network(2);
5271 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000);
5272 nodes[1].node.force_close_channel(&chan.2);
5273 check_closed_broadcast!(nodes[1]);
5274 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5275 assert_eq!(node_txn.len(), 1);
5276 check_spends!(node_txn[0], chan.3.clone());
5277 assert_eq!(node_txn[0].output.len(), 2); // We can't force trimming of to_remote output as channel_reserve_satoshis block us to do so at channel opening
5279 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5280 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
5281 let spend_txn = check_spendable_outputs!(nodes[1], 1);
5282 assert_eq!(spend_txn.len(), 1);
5283 check_spends!(spend_txn[0], node_txn[0].clone());
5287 fn test_claim_on_remote_sizeable_push_msat() {
5288 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
5289 // to_remote output is encumbered by a P2WPKH
5291 let nodes = create_network(2);
5293 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000);
5294 nodes[0].node.force_close_channel(&chan.2);
5295 check_closed_broadcast!(nodes[0]);
5297 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5298 assert_eq!(node_txn.len(), 1);
5299 check_spends!(node_txn[0], chan.3.clone());
5300 assert_eq!(node_txn[0].output.len(), 2); // We can't force trimming of to_remote output as channel_reserve_satoshis block us to do so at channel opening
5302 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5303 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
5304 check_closed_broadcast!(nodes[1]);
5305 let spend_txn = check_spendable_outputs!(nodes[1], 1);
5306 assert_eq!(spend_txn.len(), 2);
5307 assert_eq!(spend_txn[0], spend_txn[1]);
5308 check_spends!(spend_txn[0], node_txn[0].clone());
5312 fn test_claim_on_remote_revoked_sizeable_push_msat() {
5313 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
5314 // to_remote output is encumbered by a P2WPKH
5316 let nodes = create_network(2);
5318 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
5319 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5320 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
5321 assert_eq!(revoked_local_txn[0].input.len(), 1);
5322 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
5324 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5325 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5326 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5327 check_closed_broadcast!(nodes[1]);
5329 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5330 let spend_txn = check_spendable_outputs!(nodes[1], 1);
5331 assert_eq!(spend_txn.len(), 4);
5332 assert_eq!(spend_txn[0], spend_txn[2]); // to_remote output on revoked remote commitment_tx
5333 check_spends!(spend_txn[0], revoked_local_txn[0].clone());
5334 assert_eq!(spend_txn[1], spend_txn[3]); // to_local output on local commitment tx
5335 check_spends!(spend_txn[1], node_txn[0].clone());
5339 fn test_static_spendable_outputs_preimage_tx() {
5340 let nodes = create_network(2);
5342 // Create some initial channels
5343 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5345 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5347 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
5348 assert_eq!(commitment_tx[0].input.len(), 1);
5349 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
5351 // Settle A's commitment tx on B's chain
5352 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5353 assert!(nodes[1].node.claim_funds(payment_preimage));
5354 check_added_monitors!(nodes[1], 1);
5355 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
5356 let events = nodes[1].node.get_and_clear_pending_msg_events();
5358 MessageSendEvent::UpdateHTLCs { .. } => {},
5359 _ => panic!("Unexpected event"),
5362 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5363 _ => panic!("Unexepected event"),
5366 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
5367 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 1 (local commitment tx), ChannelMonitor: 2 (1 preimage tx) * 2 (block-rescan)
5368 check_spends!(node_txn[0], commitment_tx[0].clone());
5369 assert_eq!(node_txn[0], node_txn[2]);
5370 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5371 check_spends!(node_txn[1], chan_1.3.clone());
5373 let spend_txn = check_spendable_outputs!(nodes[1], 1); // , 0, 0, 1, 1);
5374 assert_eq!(spend_txn.len(), 2);
5375 assert_eq!(spend_txn[0], spend_txn[1]);
5376 check_spends!(spend_txn[0], node_txn[0].clone());
5380 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
5381 let nodes = create_network(2);
5383 // Create some initial channels
5384 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5386 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5387 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
5388 assert_eq!(revoked_local_txn[0].input.len(), 1);
5389 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5391 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5393 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5394 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5395 check_closed_broadcast!(nodes[1]);
5397 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5398 assert_eq!(node_txn.len(), 3);
5399 assert_eq!(node_txn.pop().unwrap(), node_txn[0]);
5400 assert_eq!(node_txn[0].input.len(), 2);
5401 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5403 let spend_txn = check_spendable_outputs!(nodes[1], 1);
5404 assert_eq!(spend_txn.len(), 2);
5405 assert_eq!(spend_txn[0], spend_txn[1]);
5406 check_spends!(spend_txn[0], node_txn[0].clone());
5410 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
5411 let nodes = create_network(2);
5413 // Create some initial channels
5414 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5416 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5417 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
5418 assert_eq!(revoked_local_txn[0].input.len(), 1);
5419 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5421 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5423 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5424 // A will generate HTLC-Timeout from revoked commitment tx
5425 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5426 check_closed_broadcast!(nodes[0]);
5428 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5429 assert_eq!(revoked_htlc_txn.len(), 3);
5430 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
5431 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5432 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5433 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
5434 check_spends!(revoked_htlc_txn[1], chan_1.3.clone());
5436 // B will generate justice tx from A's revoked commitment/HTLC tx
5437 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
5438 check_closed_broadcast!(nodes[1]);
5440 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5441 assert_eq!(node_txn.len(), 4);
5442 assert_eq!(node_txn[3].input.len(), 1);
5443 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
5445 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
5446 let spend_txn = check_spendable_outputs!(nodes[1], 1);
5447 assert_eq!(spend_txn.len(), 3);
5448 assert_eq!(spend_txn[0], spend_txn[1]);
5449 check_spends!(spend_txn[0], node_txn[0].clone());
5450 check_spends!(spend_txn[2], node_txn[3].clone());
5454 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
5455 let nodes = create_network(2);
5457 // Create some initial channels
5458 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5460 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5461 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
5462 assert_eq!(revoked_local_txn[0].input.len(), 1);
5463 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5465 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5467 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5468 // B will generate HTLC-Success from revoked commitment tx
5469 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5470 check_closed_broadcast!(nodes[1]);
5471 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5473 assert_eq!(revoked_htlc_txn.len(), 3);
5474 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
5475 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5476 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5477 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
5479 // A will generate justice tx from B's revoked commitment/HTLC tx
5480 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
5481 check_closed_broadcast!(nodes[0]);
5483 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5484 assert_eq!(node_txn.len(), 4);
5485 assert_eq!(node_txn[3].input.len(), 1);
5486 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
5488 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5489 let spend_txn = check_spendable_outputs!(nodes[0], 1);
5490 assert_eq!(spend_txn.len(), 5);
5491 assert_eq!(spend_txn[0], spend_txn[2]);
5492 assert_eq!(spend_txn[1], spend_txn[3]);
5493 check_spends!(spend_txn[0], revoked_local_txn[0].clone()); // spending to_remote output from revoked local tx
5494 check_spends!(spend_txn[1], node_txn[2].clone()); // spending justice tx output from revoked local tx htlc received output
5495 check_spends!(spend_txn[4], node_txn[3].clone()); // spending justice tx output on htlc success tx
5499 fn test_onchain_to_onchain_claim() {
5500 // Test that in case of channel closure, we detect the state of output thanks to
5501 // ChainWatchInterface and claim HTLC on downstream peer's remote commitment tx.
5502 // First, have C claim an HTLC against its own latest commitment transaction.
5503 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5505 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5508 let nodes = create_network(3);
5510 // Create some initial channels
5511 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5512 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5514 // Rebalance the network a bit by relaying one payment through all the channels ...
5515 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5516 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5518 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5519 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5520 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
5521 check_spends!(commitment_tx[0], chan_2.3.clone());
5522 nodes[2].node.claim_funds(payment_preimage);
5523 check_added_monitors!(nodes[2], 1);
5524 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5525 assert!(updates.update_add_htlcs.is_empty());
5526 assert!(updates.update_fail_htlcs.is_empty());
5527 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5528 assert!(updates.update_fail_malformed_htlcs.is_empty());
5530 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
5531 check_closed_broadcast!(nodes[2]);
5533 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5534 assert_eq!(c_txn.len(), 3);
5535 assert_eq!(c_txn[0], c_txn[2]);
5536 assert_eq!(commitment_tx[0], c_txn[1]);
5537 check_spends!(c_txn[1], chan_2.3.clone());
5538 check_spends!(c_txn[2], c_txn[1].clone());
5539 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5540 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5541 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5542 assert_eq!(c_txn[0].lock_time, 0); // Success tx
5544 // So we broadcast C's commitment tx and HTLC-Success on B's chain, we should successfully be able to extract preimage and update downstream monitor
5545 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
5547 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5548 assert_eq!(b_txn.len(), 4);
5549 assert_eq!(b_txn[0], b_txn[3]);
5550 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
5551 check_spends!(b_txn[2], b_txn[1].clone()); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
5552 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5553 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5554 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5555 check_spends!(b_txn[0], c_txn[1].clone()); // timeout tx on C remote commitment tx, issued by ChannelMonitor, * 2 due to block rescan
5556 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5557 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5558 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5561 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5562 check_added_monitors!(nodes[1], 1);
5563 match msg_events[0] {
5564 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5565 _ => panic!("Unexpected event"),
5567 match msg_events[1] {
5568 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, .. } } => {
5569 assert!(update_add_htlcs.is_empty());
5570 assert!(update_fail_htlcs.is_empty());
5571 assert_eq!(update_fulfill_htlcs.len(), 1);
5572 assert!(update_fail_malformed_htlcs.is_empty());
5573 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5575 _ => panic!("Unexpected event"),
5577 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5578 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
5579 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
5580 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5581 assert_eq!(b_txn.len(), 3);
5582 check_spends!(b_txn[1], chan_1.3); // Local commitment tx, issued by ChannelManager
5583 assert_eq!(b_txn[0], b_txn[2]); // HTLC-Success tx, issued by ChannelMonitor, * 2 due to block rescan
5584 check_spends!(b_txn[0], commitment_tx[0].clone());
5585 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5586 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5587 assert_eq!(b_txn[2].lock_time, 0); // Success tx
5589 check_closed_broadcast!(nodes[1]);
5593 fn test_duplicate_payment_hash_one_failure_one_success() {
5594 // Topology : A --> B --> C
5595 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5596 let mut nodes = create_network(3);
5598 create_announced_chan_between_nodes(&nodes, 0, 1);
5599 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5601 let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5602 *nodes[0].network_payment_count.borrow_mut() -= 1;
5603 assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
5605 let commitment_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
5606 assert_eq!(commitment_txn[0].input.len(), 1);
5607 check_spends!(commitment_txn[0], chan_2.3.clone());
5609 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5610 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
5611 check_closed_broadcast!(nodes[1]);
5613 let htlc_timeout_tx;
5614 { // Extract one of the two HTLC-Timeout transaction
5615 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5616 assert_eq!(node_txn.len(), 7);
5617 assert_eq!(node_txn[0], node_txn[5]);
5618 assert_eq!(node_txn[1], node_txn[6]);
5619 check_spends!(node_txn[0], commitment_txn[0].clone());
5620 assert_eq!(node_txn[0].input.len(), 1);
5621 check_spends!(node_txn[1], commitment_txn[0].clone());
5622 assert_eq!(node_txn[1].input.len(), 1);
5623 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
5624 check_spends!(node_txn[2], chan_2.3.clone());
5625 check_spends!(node_txn[3], node_txn[2].clone());
5626 check_spends!(node_txn[4], node_txn[2].clone());
5627 htlc_timeout_tx = node_txn[1].clone();
5630 nodes[2].node.claim_funds(our_payment_preimage);
5631 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
5632 check_added_monitors!(nodes[2], 2);
5633 let events = nodes[2].node.get_and_clear_pending_msg_events();
5635 MessageSendEvent::UpdateHTLCs { .. } => {},
5636 _ => panic!("Unexpected event"),
5639 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5640 _ => panic!("Unexepected event"),
5642 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5643 assert_eq!(htlc_success_txn.len(), 5);
5644 check_spends!(htlc_success_txn[2], chan_2.3.clone());
5645 assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
5646 assert_eq!(htlc_success_txn[0].input.len(), 1);
5647 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5648 assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
5649 assert_eq!(htlc_success_txn[1].input.len(), 1);
5650 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5651 assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
5652 check_spends!(htlc_success_txn[0], commitment_txn[0].clone());
5653 check_spends!(htlc_success_txn[1], commitment_txn[0].clone());
5655 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![htlc_timeout_tx] }, 200);
5656 expect_pending_htlcs_forwardable!(nodes[1]);
5657 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5658 assert!(htlc_updates.update_add_htlcs.is_empty());
5659 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5660 assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
5661 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5662 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5663 check_added_monitors!(nodes[1], 1);
5665 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]).unwrap();
5666 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5668 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5669 let events = nodes[0].node.get_and_clear_pending_msg_events();
5670 assert_eq!(events.len(), 1);
5672 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. } } => {
5674 _ => { panic!("Unexpected event"); }
5677 let events = nodes[0].node.get_and_clear_pending_events();
5679 Event::PaymentFailed { ref payment_hash, .. } => {
5680 assert_eq!(*payment_hash, duplicate_payment_hash);
5682 _ => panic!("Unexpected event"),
5685 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5686 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
5687 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5688 assert!(updates.update_add_htlcs.is_empty());
5689 assert!(updates.update_fail_htlcs.is_empty());
5690 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5691 assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
5692 assert!(updates.update_fail_malformed_htlcs.is_empty());
5693 check_added_monitors!(nodes[1], 1);
5695 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
5696 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5698 let events = nodes[0].node.get_and_clear_pending_events();
5700 Event::PaymentSent { ref payment_preimage } => {
5701 assert_eq!(*payment_preimage, our_payment_preimage);
5703 _ => panic!("Unexpected event"),
5708 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5709 let nodes = create_network(2);
5711 // Create some initial channels
5712 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5714 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5715 let local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
5716 assert_eq!(local_txn[0].input.len(), 1);
5717 check_spends!(local_txn[0], chan_1.3.clone());
5719 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5720 nodes[1].node.claim_funds(payment_preimage);
5721 check_added_monitors!(nodes[1], 1);
5722 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5723 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 1);
5724 let events = nodes[1].node.get_and_clear_pending_msg_events();
5726 MessageSendEvent::UpdateHTLCs { .. } => {},
5727 _ => panic!("Unexpected event"),
5730 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5731 _ => panic!("Unexepected event"),
5733 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5734 assert_eq!(node_txn[0].input.len(), 1);
5735 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5736 check_spends!(node_txn[0], local_txn[0].clone());
5738 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5739 let spend_txn = check_spendable_outputs!(nodes[1], 1);
5740 assert_eq!(spend_txn.len(), 2);
5741 check_spends!(spend_txn[0], node_txn[0].clone());
5742 check_spends!(spend_txn[1], node_txn[2].clone());
5745 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5746 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5747 // unrevoked commitment transaction.
5748 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5749 // a remote RAA before they could be failed backwards (and combinations thereof).
5750 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5751 // use the same payment hashes.
5752 // Thus, we use a six-node network:
5757 // And test where C fails back to A/B when D announces its latest commitment transaction
5758 let nodes = create_network(6);
5760 create_announced_chan_between_nodes(&nodes, 0, 2);
5761 create_announced_chan_between_nodes(&nodes, 1, 2);
5762 let chan = create_announced_chan_between_nodes(&nodes, 2, 3);
5763 create_announced_chan_between_nodes(&nodes, 3, 4);
5764 create_announced_chan_between_nodes(&nodes, 3, 5);
5766 // Rebalance and check output sanity...
5767 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5768 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5769 assert_eq!(nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn[0].output.len(), 2);
5771 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
5773 let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], ds_dust_limit*1000); // not added < dust limit + HTLC tx fee
5775 let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], ds_dust_limit*1000); // not added < dust limit + HTLC tx fee
5776 let route = nodes[1].router.get_route(&nodes[5].node.get_our_node_id(), None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV).unwrap();
5778 send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], ds_dust_limit*1000, payment_hash_1); // not added < dust limit + HTLC tx fee
5780 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], ds_dust_limit*1000, payment_hash_2); // not added < dust limit + HTLC tx fee
5782 let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5784 let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5785 let route = nodes[1].router.get_route(&nodes[5].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
5787 send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_3);
5789 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_4);
5792 let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5794 let route = nodes[1].router.get_route(&nodes[5].node.get_our_node_id(), None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV).unwrap();
5795 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], ds_dust_limit*1000, payment_hash_5); // not added < dust limit + HTLC tx fee
5798 let (_, payment_hash_6) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], ds_dust_limit*1000); // not added < dust limit + HTLC tx fee
5800 let route = nodes[1].router.get_route(&nodes[5].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
5801 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_6);
5803 // Double-check that six of the new HTLC were added
5804 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5805 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5806 assert_eq!(nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.len(), 1);
5807 assert_eq!(nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn[0].output.len(), 8);
5809 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5810 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5811 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1, ds_dust_limit*1000));
5812 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3, 1000000));
5813 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5, 1000000));
5814 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6, ds_dust_limit*1000));
5815 check_added_monitors!(nodes[4], 0);
5816 expect_pending_htlcs_forwardable!(nodes[4]);
5817 check_added_monitors!(nodes[4], 1);
5819 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5820 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]).unwrap();
5821 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]).unwrap();
5822 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]).unwrap();
5823 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]).unwrap();
5824 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5826 // Fail 3rd below-dust and 7th above-dust HTLCs
5827 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2, ds_dust_limit*1000));
5828 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4, 1000000));
5829 check_added_monitors!(nodes[5], 0);
5830 expect_pending_htlcs_forwardable!(nodes[5]);
5831 check_added_monitors!(nodes[5], 1);
5833 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5834 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]).unwrap();
5835 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]).unwrap();
5836 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5838 let ds_prev_commitment_tx = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
5840 expect_pending_htlcs_forwardable!(nodes[3]);
5841 check_added_monitors!(nodes[3], 1);
5842 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5843 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]).unwrap();
5844 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]).unwrap();
5845 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]).unwrap();
5846 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]).unwrap();
5847 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]).unwrap();
5848 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]).unwrap();
5849 if deliver_last_raa {
5850 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5852 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5855 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5856 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5857 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5858 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5860 // We now broadcast the latest commitment transaction, which *should* result in failures for
5861 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5862 // the non-broadcast above-dust HTLCs.
5864 // Alternatively, we may broadcast the previous commitment transaction, which should only
5865 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5866 let ds_last_commitment_tx = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
5868 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5869 if announce_latest {
5870 nodes[2].chain_monitor.block_connected_checked(&header, 1, &[&ds_last_commitment_tx[0]], &[1; 1]);
5872 nodes[2].chain_monitor.block_connected_checked(&header, 1, &[&ds_prev_commitment_tx[0]], &[1; 1]);
5874 check_closed_broadcast!(nodes[2]);
5875 expect_pending_htlcs_forwardable!(nodes[2]);
5876 check_added_monitors!(nodes[2], 2);
5878 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5879 assert_eq!(cs_msgs.len(), 2);
5880 let mut a_done = false;
5881 for msg in cs_msgs {
5883 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5884 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5885 // should be failed-backwards here.
5886 let target = if *node_id == nodes[0].node.get_our_node_id() {
5887 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5888 for htlc in &updates.update_fail_htlcs {
5889 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 6 || if announce_latest { htlc.htlc_id == 3 || htlc.htlc_id == 5 } else { false });
5891 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5896 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5897 for htlc in &updates.update_fail_htlcs {
5898 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5900 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5901 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5904 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
5905 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]).unwrap();
5906 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]).unwrap();
5907 if announce_latest {
5908 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]).unwrap();
5909 if *node_id == nodes[0].node.get_our_node_id() {
5910 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]).unwrap();
5913 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5915 _ => panic!("Unexpected event"),
5919 let as_events = nodes[0].node.get_and_clear_pending_events();
5920 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5921 let mut as_failds = HashSet::new();
5922 for event in as_events.iter() {
5923 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5924 assert!(as_failds.insert(*payment_hash));
5925 if *payment_hash != payment_hash_2 {
5926 assert_eq!(*rejected_by_dest, deliver_last_raa);
5928 assert!(!rejected_by_dest);
5930 } else { panic!("Unexpected event"); }
5932 assert!(as_failds.contains(&payment_hash_1));
5933 assert!(as_failds.contains(&payment_hash_2));
5934 if announce_latest {
5935 assert!(as_failds.contains(&payment_hash_3));
5936 assert!(as_failds.contains(&payment_hash_5));
5938 assert!(as_failds.contains(&payment_hash_6));
5940 let bs_events = nodes[1].node.get_and_clear_pending_events();
5941 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5942 let mut bs_failds = HashSet::new();
5943 for event in bs_events.iter() {
5944 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5945 assert!(bs_failds.insert(*payment_hash));
5946 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5947 assert_eq!(*rejected_by_dest, deliver_last_raa);
5949 assert!(!rejected_by_dest);
5951 } else { panic!("Unexpected event"); }
5953 assert!(bs_failds.contains(&payment_hash_1));
5954 assert!(bs_failds.contains(&payment_hash_2));
5955 if announce_latest {
5956 assert!(bs_failds.contains(&payment_hash_4));
5958 assert!(bs_failds.contains(&payment_hash_5));
5960 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5961 // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
5962 // to unknown-preimage-etc, B should have gotten 2. Thus, in the
5963 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
5964 // PaymentFailureNetworkUpdates.
5965 let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
5966 assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5967 let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5968 assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5969 for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
5971 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
5972 _ => panic!("Unexpected event"),
5978 fn test_fail_backwards_latest_remote_announce_a() {
5979 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5983 fn test_fail_backwards_latest_remote_announce_b() {
5984 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5988 fn test_fail_backwards_previous_remote_announce() {
5989 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5990 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5991 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5995 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5996 let nodes = create_network(2);
5998 // Create some initial channels
5999 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6001 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
6002 let local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6003 assert_eq!(local_txn[0].input.len(), 1);
6004 check_spends!(local_txn[0], chan_1.3.clone());
6006 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
6007 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6008 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 200);
6009 check_closed_broadcast!(nodes[0]);
6011 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
6012 assert_eq!(node_txn[0].input.len(), 1);
6013 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6014 check_spends!(node_txn[0], local_txn[0].clone());
6016 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
6017 let spend_txn = check_spendable_outputs!(nodes[0], 1);
6018 assert_eq!(spend_txn.len(), 8);
6019 assert_eq!(spend_txn[0], spend_txn[2]);
6020 assert_eq!(spend_txn[0], spend_txn[4]);
6021 assert_eq!(spend_txn[0], spend_txn[6]);
6022 assert_eq!(spend_txn[1], spend_txn[3]);
6023 assert_eq!(spend_txn[1], spend_txn[5]);
6024 assert_eq!(spend_txn[1], spend_txn[7]);
6025 check_spends!(spend_txn[0], local_txn[0].clone());
6026 check_spends!(spend_txn[1], node_txn[0].clone());
6030 fn test_static_output_closing_tx() {
6031 let nodes = create_network(2);
6033 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6035 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
6036 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
6038 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6039 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
6040 let spend_txn = check_spendable_outputs!(nodes[0], 2);
6041 assert_eq!(spend_txn.len(), 1);
6042 check_spends!(spend_txn[0], closing_tx.clone());
6044 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
6045 let spend_txn = check_spendable_outputs!(nodes[1], 2);
6046 assert_eq!(spend_txn.len(), 1);
6047 check_spends!(spend_txn[0], closing_tx);
6050 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
6051 let nodes = create_network(2);
6052 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6054 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
6056 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
6057 // present in B's local commitment transaction, but none of A's commitment transactions.
6058 assert!(nodes[1].node.claim_funds(our_payment_preimage));
6059 check_added_monitors!(nodes[1], 1);
6061 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6062 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]).unwrap();
6063 let events = nodes[0].node.get_and_clear_pending_events();
6064 assert_eq!(events.len(), 1);
6066 Event::PaymentSent { payment_preimage } => {
6067 assert_eq!(payment_preimage, our_payment_preimage);
6069 _ => panic!("Unexpected event"),
6072 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed).unwrap();
6073 check_added_monitors!(nodes[0], 1);
6074 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6075 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0).unwrap();
6076 check_added_monitors!(nodes[1], 1);
6078 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6079 for i in 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + CHAN_CONFIRM_DEPTH + 1 {
6080 nodes[1].chain_monitor.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
6081 header.prev_blockhash = header.bitcoin_hash();
6083 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
6084 check_closed_broadcast!(nodes[1]);
6087 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
6088 let mut nodes = create_network(2);
6089 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6091 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), if use_dust { 50000 } else { 3000000 }, TEST_FINAL_CLTV).unwrap();
6092 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
6093 nodes[0].node.send_payment(route, payment_hash).unwrap();
6094 check_added_monitors!(nodes[0], 1);
6096 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6098 // As far as A is concerened, the HTLC is now present only in the latest remote commitment
6099 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
6100 // to "time out" the HTLC.
6102 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6103 for i in 1..TEST_FINAL_CLTV + HTLC_FAIL_TIMEOUT_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
6104 nodes[0].chain_monitor.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
6105 header.prev_blockhash = header.bitcoin_hash();
6107 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
6108 check_closed_broadcast!(nodes[0]);
6111 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
6112 let nodes = create_network(3);
6113 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6115 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
6116 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
6117 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
6118 // actually revoked.
6119 let htlc_value = if use_dust { 50000 } else { 3000000 };
6120 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
6121 assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash, htlc_value));
6122 expect_pending_htlcs_forwardable!(nodes[1]);
6123 check_added_monitors!(nodes[1], 1);
6125 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6126 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]).unwrap();
6127 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed).unwrap();
6128 check_added_monitors!(nodes[0], 1);
6129 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6130 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0).unwrap();
6131 check_added_monitors!(nodes[1], 1);
6132 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1).unwrap();
6133 check_added_monitors!(nodes[1], 1);
6134 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6136 if check_revoke_no_close {
6137 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
6138 check_added_monitors!(nodes[0], 1);
6141 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6142 for i in 1..TEST_FINAL_CLTV + HTLC_FAIL_TIMEOUT_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
6143 nodes[0].chain_monitor.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
6144 header.prev_blockhash = header.bitcoin_hash();
6146 if !check_revoke_no_close {
6147 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
6148 check_closed_broadcast!(nodes[0]);
6150 let events = nodes[0].node.get_and_clear_pending_events();
6151 assert_eq!(events.len(), 1);
6153 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
6154 assert_eq!(payment_hash, our_payment_hash);
6155 assert!(rejected_by_dest);
6157 _ => panic!("Unexpected event"),
6162 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
6163 // There are only a few cases to test here:
6164 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
6165 // broadcastable commitment transactions result in channel closure,
6166 // * its included in an unrevoked-but-previous remote commitment transaction,
6167 // * its included in the latest remote or local commitment transactions.
6168 // We test each of the three possible commitment transactions individually and use both dust and
6170 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
6171 // assume they are handled the same across all six cases, as both outbound and inbound failures are
6172 // tested for at least one of the cases in other tests.
6174 fn htlc_claim_single_commitment_only_a() {
6175 do_htlc_claim_local_commitment_only(true);
6176 do_htlc_claim_local_commitment_only(false);
6178 do_htlc_claim_current_remote_commitment_only(true);
6179 do_htlc_claim_current_remote_commitment_only(false);
6183 fn htlc_claim_single_commitment_only_b() {
6184 do_htlc_claim_previous_remote_commitment_only(true, false);
6185 do_htlc_claim_previous_remote_commitment_only(false, false);
6186 do_htlc_claim_previous_remote_commitment_only(true, true);
6187 do_htlc_claim_previous_remote_commitment_only(false, true);
6190 fn run_onion_failure_test<F1,F2>(_name: &str, test_case: u8, nodes: &Vec<Node>, route: &Route, payment_hash: &PaymentHash, callback_msg: F1, callback_node: F2, expected_retryable: bool, expected_error_code: Option<u16>, expected_channel_update: Option<HTLCFailChannelUpdate>)
6191 where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
6194 run_onion_failure_test_with_fail_intercept(_name, test_case, nodes, route, payment_hash, callback_msg, |_|{}, callback_node, expected_retryable, expected_error_code, expected_channel_update);
6198 // 0: node1 fail backward
6199 // 1: final node fail backward
6200 // 2: payment completed but the user reject the payment
6201 // 3: final node fail backward (but tamper onion payloads from node0)
6202 // 100: trigger error in the intermediate node and tamper returnning fail_htlc
6203 // 200: trigger error in the final node and tamper returnning fail_htlc
6204 fn run_onion_failure_test_with_fail_intercept<F1,F2,F3>(_name: &str, test_case: u8, nodes: &Vec<Node>, route: &Route, payment_hash: &PaymentHash, mut callback_msg: F1, mut callback_fail: F2, mut callback_node: F3, expected_retryable: bool, expected_error_code: Option<u16>, expected_channel_update: Option<HTLCFailChannelUpdate>)
6205 where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
6206 F2: for <'a> FnMut(&'a mut msgs::UpdateFailHTLC),
6209 use ln::msgs::HTLCFailChannelUpdate;
6211 // reset block height
6212 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6213 for ix in 0..nodes.len() {
6214 nodes[ix].chain_monitor.block_connected_checked(&header, 1, &Vec::new()[..], &[0; 0]);
6217 macro_rules! expect_event {
6218 ($node: expr, $event_type: path) => {{
6219 let events = $node.node.get_and_clear_pending_events();
6220 assert_eq!(events.len(), 1);
6222 $event_type { .. } => {},
6223 _ => panic!("Unexpected event"),
6228 macro_rules! expect_htlc_forward {
6230 expect_event!($node, Event::PendingHTLCsForwardable);
6231 $node.node.channel_state.lock().unwrap().next_forward = Instant::now();
6232 $node.node.process_pending_htlc_forwards();
6236 // 0 ~~> 2 send payment
6237 nodes[0].node.send_payment(route.clone(), payment_hash.clone()).unwrap();
6238 check_added_monitors!(nodes[0], 1);
6239 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6240 // temper update_add (0 => 1)
6241 let mut update_add_0 = update_0.update_add_htlcs[0].clone();
6242 if test_case == 0 || test_case == 3 || test_case == 100 {
6243 callback_msg(&mut update_add_0);
6246 // 0 => 1 update_add & CS
6247 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_0).unwrap();
6248 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
6250 let update_1_0 = match test_case {
6251 0|100 => { // intermediate node failure; fail backward to 0
6252 let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6253 assert!(update_1_0.update_fail_htlcs.len()+update_1_0.update_fail_malformed_htlcs.len()==1 && (update_1_0.update_fail_htlcs.len()==1 || update_1_0.update_fail_malformed_htlcs.len()==1));
6256 1|2|3|200 => { // final node failure; forwarding to 2
6257 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
6259 if test_case != 200 {
6262 expect_htlc_forward!(&nodes[1]);
6264 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
6265 check_added_monitors!(&nodes[1], 1);
6266 assert_eq!(update_1.update_add_htlcs.len(), 1);
6267 // tamper update_add (1 => 2)
6268 let mut update_add_1 = update_1.update_add_htlcs[0].clone();
6269 if test_case != 3 && test_case != 200 {
6270 callback_msg(&mut update_add_1);
6274 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_1).unwrap();
6275 commitment_signed_dance!(nodes[2], nodes[1], update_1.commitment_signed, false, true);
6277 if test_case == 2 || test_case == 200 {
6278 expect_htlc_forward!(&nodes[2]);
6279 expect_event!(&nodes[2], Event::PaymentReceived);
6281 expect_pending_htlcs_forwardable!(nodes[2]);
6284 let update_2_1 = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6285 if test_case == 2 || test_case == 200 {
6286 check_added_monitors!(&nodes[2], 1);
6288 assert!(update_2_1.update_fail_htlcs.len() == 1);
6290 let mut fail_msg = update_2_1.update_fail_htlcs[0].clone();
6291 if test_case == 200 {
6292 callback_fail(&mut fail_msg);
6296 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_msg).unwrap();
6297 commitment_signed_dance!(nodes[1], nodes[2], update_2_1.commitment_signed, true);
6299 // backward fail on 1
6300 let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6301 assert!(update_1_0.update_fail_htlcs.len() == 1);
6304 _ => unreachable!(),
6307 // 1 => 0 commitment_signed_dance
6308 if update_1_0.update_fail_htlcs.len() > 0 {
6309 let mut fail_msg = update_1_0.update_fail_htlcs[0].clone();
6310 if test_case == 100 {
6311 callback_fail(&mut fail_msg);
6313 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg).unwrap();
6315 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_1_0.update_fail_malformed_htlcs[0]).unwrap();
6318 commitment_signed_dance!(nodes[0], nodes[1], update_1_0.commitment_signed, false, true);
6320 let events = nodes[0].node.get_and_clear_pending_events();
6321 assert_eq!(events.len(), 1);
6322 if let &Event::PaymentFailed { payment_hash:_, ref rejected_by_dest, ref error_code } = &events[0] {
6323 assert_eq!(*rejected_by_dest, !expected_retryable);
6324 assert_eq!(*error_code, expected_error_code);
6326 panic!("Uexpected event");
6329 let events = nodes[0].node.get_and_clear_pending_msg_events();
6330 if expected_channel_update.is_some() {
6331 assert_eq!(events.len(), 1);
6333 MessageSendEvent::PaymentFailureNetworkUpdate { ref update } => {
6335 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {
6336 if let HTLCFailChannelUpdate::ChannelUpdateMessage { .. } = expected_channel_update.unwrap() {} else {
6337 panic!("channel_update not found!");
6340 &HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id, ref is_permanent } => {
6341 if let HTLCFailChannelUpdate::ChannelClosed { short_channel_id: ref expected_short_channel_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
6342 assert!(*short_channel_id == *expected_short_channel_id);
6343 assert!(*is_permanent == *expected_is_permanent);
6345 panic!("Unexpected message event");
6348 &HTLCFailChannelUpdate::NodeFailure { ref node_id, ref is_permanent } => {
6349 if let HTLCFailChannelUpdate::NodeFailure { node_id: ref expected_node_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
6350 assert!(*node_id == *expected_node_id);
6351 assert!(*is_permanent == *expected_is_permanent);
6353 panic!("Unexpected message event");
6358 _ => panic!("Unexpected message event"),
6361 assert_eq!(events.len(), 0);
6365 impl msgs::ChannelUpdate {
6366 fn dummy() -> msgs::ChannelUpdate {
6367 use secp256k1::ffi::Signature as FFISignature;
6368 use secp256k1::Signature;
6369 msgs::ChannelUpdate {
6370 signature: Signature::from(FFISignature::new()),
6371 contents: msgs::UnsignedChannelUpdate {
6372 chain_hash: Sha256dHash::from_data(&vec![0u8][..]),
6373 short_channel_id: 0,
6376 cltv_expiry_delta: 0,
6377 htlc_minimum_msat: 0,
6379 fee_proportional_millionths: 0,
6380 excess_data: vec![],
6387 fn test_onion_failure() {
6388 use ln::msgs::ChannelUpdate;
6389 use ln::channelmanager::CLTV_FAR_FAR_AWAY;
6392 const BADONION: u16 = 0x8000;
6393 const PERM: u16 = 0x4000;
6394 const NODE: u16 = 0x2000;
6395 const UPDATE: u16 = 0x1000;
6397 let mut nodes = create_network(3);
6398 for node in nodes.iter() {
6399 *node.keys_manager.override_session_priv.lock().unwrap() = Some(SecretKey::from_slice(&Secp256k1::without_caps(), &[3; 32]).unwrap());
6401 let channels = [create_announced_chan_between_nodes(&nodes, 0, 1), create_announced_chan_between_nodes(&nodes, 1, 2)];
6402 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
6403 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV).unwrap();
6405 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 40000);
6407 // intermediate node failure
6408 run_onion_failure_test("invalid_realm", 0, &nodes, &route, &payment_hash, |msg| {
6409 let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
6410 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
6411 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
6412 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
6413 onion_payloads[0].realm = 3;
6414 msg.onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
6415 }, ||{}, true, Some(PERM|1), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));//XXX incremented channels idx here
6417 // final node failure
6418 run_onion_failure_test("invalid_realm", 3, &nodes, &route, &payment_hash, |msg| {
6419 let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
6420 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
6421 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
6422 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
6423 onion_payloads[1].realm = 3;
6424 msg.onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
6425 }, ||{}, false, Some(PERM|1), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
6427 // the following three with run_onion_failure_test_with_fail_intercept() test only the origin node
6428 // receiving simulated fail messages
6429 // intermediate node failure
6430 run_onion_failure_test_with_fail_intercept("temporary_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
6432 msg.amount_msat -= 1;
6434 // and tamper returing error message
6435 let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
6436 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
6437 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], NODE|2, &[0;0]);
6438 }, ||{}, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: false}));
6440 // final node failure
6441 run_onion_failure_test_with_fail_intercept("temporary_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
6442 // and tamper returing error message
6443 let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
6444 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
6445 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], NODE|2, &[0;0]);
6447 nodes[2].node.fail_htlc_backwards(&payment_hash, 0);
6448 }, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: false}));
6450 // intermediate node failure
6451 run_onion_failure_test_with_fail_intercept("permanent_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
6452 msg.amount_msat -= 1;
6454 let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
6455 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
6456 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|2, &[0;0]);
6457 }, ||{}, true, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: true}));
6459 // final node failure
6460 run_onion_failure_test_with_fail_intercept("permanent_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
6461 let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
6462 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
6463 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|2, &[0;0]);
6465 nodes[2].node.fail_htlc_backwards(&payment_hash, 0);
6466 }, false, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: true}));
6468 // intermediate node failure
6469 run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
6470 msg.amount_msat -= 1;
6472 let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
6473 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
6474 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|3, &[0;0]);
6476 nodes[2].node.fail_htlc_backwards(&payment_hash, 0);
6477 }, true, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: true}));
6479 // final node failure
6480 run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
6481 let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
6482 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
6483 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|3, &[0;0]);
6485 nodes[2].node.fail_htlc_backwards(&payment_hash, 0);
6486 }, false, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: true}));
6488 run_onion_failure_test("invalid_onion_version", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.version = 1; }, ||{}, true,
6489 Some(BADONION|PERM|4), None);
6491 run_onion_failure_test("invalid_onion_hmac", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.hmac = [3; 32]; }, ||{}, true,
6492 Some(BADONION|PERM|5), None);
6494 run_onion_failure_test("invalid_onion_key", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.public_key = Err(secp256k1::Error::InvalidPublicKey);}, ||{}, true,
6495 Some(BADONION|PERM|6), None);
6497 run_onion_failure_test_with_fail_intercept("temporary_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
6498 msg.amount_msat -= 1;
6500 let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
6501 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
6502 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], UPDATE|7, &ChannelUpdate::dummy().encode_with_len()[..]);
6503 }, ||{}, true, Some(UPDATE|7), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
6505 run_onion_failure_test_with_fail_intercept("permanent_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
6506 msg.amount_msat -= 1;
6508 let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
6509 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
6510 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|8, &[0;0]);
6511 // short_channel_id from the processing node
6512 }, ||{}, true, Some(PERM|8), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
6514 run_onion_failure_test_with_fail_intercept("required_channel_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
6515 msg.amount_msat -= 1;
6517 let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
6518 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
6519 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|9, &[0;0]);
6520 // short_channel_id from the processing node
6521 }, ||{}, true, Some(PERM|9), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
6523 let mut bogus_route = route.clone();
6524 bogus_route.hops[1].short_channel_id -= 1;
6525 run_onion_failure_test("unknown_next_peer", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(PERM|10),
6526 Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: bogus_route.hops[1].short_channel_id, is_permanent:true}));
6528 let amt_to_forward = nodes[1].node.channel_state.lock().unwrap().by_id.get(&channels[1].2).unwrap().get_their_htlc_minimum_msat() - 1;
6529 let mut bogus_route = route.clone();
6530 let route_len = bogus_route.hops.len();
6531 bogus_route.hops[route_len-1].fee_msat = amt_to_forward;
6532 run_onion_failure_test("amount_below_minimum", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(UPDATE|11), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
6534 //TODO: with new config API, we will be able to generate both valid and
6535 //invalid channel_update cases.
6536 run_onion_failure_test("fee_insufficient", 0, &nodes, &route, &payment_hash, |msg| {
6537 msg.amount_msat -= 1;
6538 }, || {}, true, Some(UPDATE|12), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
6540 run_onion_failure_test("incorrect_cltv_expiry", 0, &nodes, &route, &payment_hash, |msg| {
6541 // need to violate: cltv_expiry - cltv_expiry_delta >= outgoing_cltv_value
6542 msg.cltv_expiry -= 1;
6543 }, || {}, true, Some(UPDATE|13), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
6545 run_onion_failure_test("expiry_too_soon", 0, &nodes, &route, &payment_hash, |msg| {
6546 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - HTLC_FAIL_TIMEOUT_BLOCKS + 1;
6547 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6548 nodes[1].chain_monitor.block_connected_checked(&header, height, &Vec::new()[..], &[0; 0]);
6549 }, ||{}, true, Some(UPDATE|14), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
6551 run_onion_failure_test("unknown_payment_hash", 2, &nodes, &route, &payment_hash, |_| {}, || {
6552 nodes[2].node.fail_htlc_backwards(&payment_hash, 0);
6553 }, false, Some(PERM|15), None);
6555 run_onion_failure_test("final_expiry_too_soon", 1, &nodes, &route, &payment_hash, |msg| {
6556 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - HTLC_FAIL_TIMEOUT_BLOCKS + 1;
6557 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6558 nodes[2].chain_monitor.block_connected_checked(&header, height, &Vec::new()[..], &[0; 0]);
6559 }, || {}, true, Some(17), None);
6561 run_onion_failure_test("final_incorrect_cltv_expiry", 1, &nodes, &route, &payment_hash, |_| {}, || {
6562 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().borrow_parts().forward_htlcs.iter_mut() {
6563 for f in pending_forwards.iter_mut() {
6565 &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
6566 forward_info.outgoing_cltv_value += 1,
6571 }, true, Some(18), None);
6573 run_onion_failure_test("final_incorrect_htlc_amount", 1, &nodes, &route, &payment_hash, |_| {}, || {
6574 // violate amt_to_forward > msg.amount_msat
6575 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().borrow_parts().forward_htlcs.iter_mut() {
6576 for f in pending_forwards.iter_mut() {
6578 &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
6579 forward_info.amt_to_forward -= 1,
6584 }, true, Some(19), None);
6586 run_onion_failure_test("channel_disabled", 0, &nodes, &route, &payment_hash, |_| {}, || {
6587 // disconnect event to the channel between nodes[1] ~ nodes[2]
6588 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
6589 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6590 }, true, Some(UPDATE|20), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
6591 reconnect_nodes(&nodes[1], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
6593 run_onion_failure_test("expiry_too_far", 0, &nodes, &route, &payment_hash, |msg| {
6594 let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
6595 let mut route = route.clone();
6597 route.hops[1].cltv_expiry_delta += CLTV_FAR_FAR_AWAY + route.hops[0].cltv_expiry_delta + 1;
6598 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
6599 let (onion_payloads, _, htlc_cltv) = onion_utils::build_onion_payloads(&route, height).unwrap();
6600 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
6601 msg.cltv_expiry = htlc_cltv;
6602 msg.onion_routing_packet = onion_packet;
6603 }, ||{}, true, Some(21), None);
6606 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6607 // BOLT 2 Requirement: MUST NOT offer amount_msat it cannot pay for in the remote commitment transaction at the current feerate_per_kw (see "Updating Fees") while maintaining its channel reserve.
6608 //TODO: I don't believe this is explicitly enforced when sending an HTLC but as the Fee aspect of the BOLT specs is in flux leaving this as a TODO.
6611 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6612 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6613 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6614 let mut nodes = create_network(2);
6615 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6616 let mut route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
6617 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6619 route.hops[0].fee_msat = 0;
6621 let err = nodes[0].node.send_payment(route, our_payment_hash);
6623 if let Err(APIError::ChannelUnavailable{err}) = err {
6624 assert_eq!(err, "Cannot send less than their minimum HTLC value");
6631 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6632 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6633 //TODO: This is not currently explicitly checked when sending an HTLC and exists as TODO in the channel::send_htlc(...) function
6634 //It is enforced when constructing a route.
6635 let mut nodes = create_network(2);
6636 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 0);
6637 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000000, 500000001).unwrap();
6638 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6640 let err = nodes[0].node.send_payment(route, our_payment_hash);
6642 if let Err(APIError::RouteError{err}) = err {
6643 assert_eq!(err, "Channel CLTV overflowed?!");
6650 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6651 //BOLT 2 Requirement: if result would be offering more than the remote's max_accepted_htlcs HTLCs, in the remote commitment transaction: MUST NOT add an HTLC.
6652 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6653 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6654 let mut nodes = create_network(2);
6655 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6656 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().their_max_accepted_htlcs as u64;
6658 for i in 0..max_accepted_htlcs {
6659 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
6660 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6661 let mut payment_event = {
6662 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
6663 check_added_monitors!(nodes[0], 1);
6665 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6666 assert_eq!(events.len(), 1);
6667 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6668 assert_eq!(htlcs[0].htlc_id, i);
6672 SendEvent::from_event(events.remove(0))
6674 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
6675 check_added_monitors!(nodes[1], 0);
6676 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6678 expect_pending_htlcs_forwardable!(nodes[1]);
6679 expect_payment_received!(nodes[1], our_payment_hash, 100000);
6681 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
6682 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6683 let err = nodes[0].node.send_payment(route, our_payment_hash);
6685 if let Err(APIError::ChannelUnavailable{err}) = err {
6686 assert_eq!(err, "Cannot push more than their max accepted HTLCs");
6693 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6694 //BOLT 2 Requirement: if the sum of total offered HTLCs would exceed the remote's max_htlc_value_in_flight_msat: MUST NOT add an HTLC.
6695 let mut nodes = create_network(2);
6696 let channel_value = 100000;
6697 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6698 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).their_max_htlc_value_in_flight_msat;
6700 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6702 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], max_in_flight+1, TEST_FINAL_CLTV).unwrap();
6703 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6704 let err = nodes[0].node.send_payment(route, our_payment_hash);
6706 if let Err(APIError::ChannelUnavailable{err}) = err {
6707 assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight");
6713 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6715 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6716 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6717 let mut nodes = create_network(2);
6718 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6719 let htlc_minimum_msat: u64;
6721 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6722 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6723 htlc_minimum_msat = channel.get_our_htlc_minimum_msat();
6725 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], htlc_minimum_msat+1, TEST_FINAL_CLTV).unwrap();
6726 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6727 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
6728 check_added_monitors!(nodes[0], 1);
6729 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6730 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6731 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6732 if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
6733 assert_eq!(err, "Remote side tried to send less than our minimum HTLC value");
6737 assert!(nodes[1].node.list_channels().is_empty());
6738 check_closed_broadcast!(nodes[1]);
6742 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6743 //BOLT2 Requirement: receiving an amount_msat that the sending node cannot afford at the current feerate_per_kw (while maintaining its channel reserve): SHOULD fail the channel
6744 let mut nodes = create_network(2);
6745 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6747 let their_channel_reserve = get_channel_value_stat!(nodes[0], chan.2).channel_reserve_msat;
6749 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 5000000-their_channel_reserve, TEST_FINAL_CLTV).unwrap();
6750 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6751 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
6752 check_added_monitors!(nodes[0], 1);
6753 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6755 updates.update_add_htlcs[0].amount_msat = 5000000-their_channel_reserve+1;
6756 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6758 if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
6759 assert_eq!(err, "Remote HTLC add would put them over their reserve value");
6764 assert!(nodes[1].node.list_channels().is_empty());
6765 check_closed_broadcast!(nodes[1]);
6769 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6771 let secp_ctx = Secp256k1::new();
6773 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6774 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6775 let mut nodes = create_network(2);
6776 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6777 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 3999999, TEST_FINAL_CLTV).unwrap();
6778 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6780 let session_priv = SecretKey::from_slice(&secp_ctx, &{
6781 let mut session_key = [0; 32];
6782 rng::fill_bytes(&mut session_key);
6784 }).expect("RNG is bad!");
6786 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
6787 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
6788 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
6789 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, &our_payment_hash);
6791 let mut msg = msgs::UpdateAddHTLC {
6795 payment_hash: our_payment_hash,
6796 cltv_expiry: htlc_cltv,
6797 onion_routing_packet: onion_packet.clone(),
6800 for i in 0..super::channel::OUR_MAX_HTLCS {
6801 msg.htlc_id = i as u64;
6802 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg).unwrap();
6804 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6805 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6807 if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
6808 assert_eq!(err, "Remote tried to push more than our max accepted HTLCs");
6813 assert!(nodes[1].node.list_channels().is_empty());
6814 check_closed_broadcast!(nodes[1]);
6818 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6819 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6820 let mut nodes = create_network(2);
6821 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6822 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
6823 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6824 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
6825 check_added_monitors!(nodes[0], 1);
6826 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6827 updates.update_add_htlcs[0].amount_msat = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().their_max_htlc_value_in_flight_msat + 1;
6828 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6830 if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
6831 assert_eq!(err,"Remote HTLC add would put them over their max HTLC value in flight");
6836 assert!(nodes[1].node.list_channels().is_empty());
6837 check_closed_broadcast!(nodes[1]);
6841 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6842 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6843 let mut nodes = create_network(2);
6844 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6845 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 3999999, TEST_FINAL_CLTV).unwrap();
6846 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6847 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
6848 check_added_monitors!(nodes[0], 1);
6849 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6850 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6851 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6853 if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
6854 assert_eq!(err,"Remote provided CLTV expiry in seconds instead of block height");
6859 assert!(nodes[1].node.list_channels().is_empty());
6860 check_closed_broadcast!(nodes[1]);
6864 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6865 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6866 let mut nodes = create_network(2);
6867 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6868 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 3999999, TEST_FINAL_CLTV).unwrap();
6869 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6870 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
6871 check_added_monitors!(nodes[0], 1);
6872 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6873 let _ = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6874 assert_eq!(nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().next_remote_htlc_id, 1);
6876 //Disconnect and Reconnect
6877 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6878 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6879 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
6880 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6881 assert_eq!(reestablish_1.len(), 1);
6882 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
6883 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6884 assert_eq!(reestablish_2.len(), 1);
6885 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
6886 let _ = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6887 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
6888 let _ = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6891 let _ = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6892 assert_eq!(nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().next_remote_htlc_id, 1);
6893 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);