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;
26 use bitcoin::util::hash::{BitcoinHash, Sha256dHash};
27 use bitcoin::util::bip143;
28 use bitcoin::util::address::Address;
29 use bitcoin::util::bip32::{ChildNumber, ExtendedPubKey, ExtendedPrivKey};
30 use bitcoin::blockdata::block::{Block, BlockHeader};
31 use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType};
32 use bitcoin::blockdata::script::{Builder, Script};
33 use bitcoin::blockdata::opcodes;
34 use bitcoin::blockdata::constants::genesis_block;
35 use bitcoin::network::constants::Network;
37 use bitcoin_hashes::sha256::Hash as Sha256;
38 use bitcoin_hashes::Hash;
40 use secp256k1::{Secp256k1, Message};
41 use secp256k1::key::{PublicKey,SecretKey};
43 use rand::{thread_rng,Rng};
45 use std::cell::RefCell;
46 use std::collections::{BTreeSet, HashMap, HashSet};
47 use std::default::Default;
49 use std::sync::{Arc, Mutex};
50 use std::sync::atomic::Ordering;
51 use std::time::Instant;
54 const CHAN_CONFIRM_DEPTH: u32 = 100;
55 fn confirm_transaction(chain: &chaininterface::ChainWatchInterfaceUtil, tx: &Transaction, chan_id: u32) {
56 assert!(chain.does_match_tx(tx));
57 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
58 chain.block_connected_checked(&header, 1, &[tx; 1], &[chan_id; 1]);
59 for i in 2..CHAN_CONFIRM_DEPTH {
60 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
61 chain.block_connected_checked(&header, i, &[tx; 0], &[0; 0]);
66 chain_monitor: Arc<chaininterface::ChainWatchInterfaceUtil>,
67 tx_broadcaster: Arc<test_utils::TestBroadcaster>,
68 chan_monitor: Arc<test_utils::TestChannelMonitor>,
69 keys_manager: Arc<test_utils::TestKeysInterface>,
70 node: Arc<ChannelManager>,
73 network_payment_count: Rc<RefCell<u8>>,
74 network_chan_count: Rc<RefCell<u32>>,
78 if !::std::thread::panicking() {
79 // Check that we processed all pending events
80 assert!(self.node.get_and_clear_pending_msg_events().is_empty());
81 assert!(self.node.get_and_clear_pending_events().is_empty());
82 assert!(self.chan_monitor.added_monitors.lock().unwrap().is_empty());
87 fn create_chan_between_nodes(node_a: &Node, node_b: &Node) -> (msgs::ChannelAnnouncement, msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
88 create_chan_between_nodes_with_value(node_a, node_b, 100000, 10001)
91 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) {
92 let (funding_locked, channel_id, tx) = create_chan_between_nodes_with_value_a(node_a, node_b, channel_value, push_msat);
93 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(node_a, node_b, &funding_locked);
94 (announcement, as_update, bs_update, channel_id, tx)
97 macro_rules! get_revoke_commit_msgs {
98 ($node: expr, $node_id: expr) => {
100 let events = $node.node.get_and_clear_pending_msg_events();
101 assert_eq!(events.len(), 2);
103 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
104 assert_eq!(*node_id, $node_id);
107 _ => panic!("Unexpected event"),
109 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
110 assert_eq!(*node_id, $node_id);
111 assert!(updates.update_add_htlcs.is_empty());
112 assert!(updates.update_fulfill_htlcs.is_empty());
113 assert!(updates.update_fail_htlcs.is_empty());
114 assert!(updates.update_fail_malformed_htlcs.is_empty());
115 assert!(updates.update_fee.is_none());
116 updates.commitment_signed.clone()
118 _ => panic!("Unexpected event"),
124 macro_rules! get_event_msg {
125 ($node: expr, $event_type: path, $node_id: expr) => {
127 let events = $node.node.get_and_clear_pending_msg_events();
128 assert_eq!(events.len(), 1);
130 $event_type { ref node_id, ref msg } => {
131 assert_eq!(*node_id, $node_id);
134 _ => panic!("Unexpected event"),
140 macro_rules! get_htlc_update_msgs {
141 ($node: expr, $node_id: expr) => {
143 let events = $node.node.get_and_clear_pending_msg_events();
144 assert_eq!(events.len(), 1);
146 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
147 assert_eq!(*node_id, $node_id);
150 _ => panic!("Unexpected event"),
156 macro_rules! get_feerate {
157 ($node: expr, $channel_id: expr) => {
159 let chan_lock = $node.node.channel_state.lock().unwrap();
160 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
167 fn create_chan_between_nodes_with_value_init(node_a: &Node, node_b: &Node, channel_value: u64, push_msat: u64) -> Transaction {
168 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42).unwrap();
169 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();
170 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();
172 let chan_id = *node_a.network_chan_count.borrow();
176 let events_2 = node_a.node.get_and_clear_pending_events();
177 assert_eq!(events_2.len(), 1);
179 Event::FundingGenerationReady { ref temporary_channel_id, ref channel_value_satoshis, ref output_script, user_channel_id } => {
180 assert_eq!(*channel_value_satoshis, channel_value);
181 assert_eq!(user_channel_id, 42);
183 tx = Transaction { version: chan_id as u32, lock_time: 0, input: Vec::new(), output: vec![TxOut {
184 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
186 funding_output = OutPoint::new(tx.txid(), 0);
188 node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
189 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
190 assert_eq!(added_monitors.len(), 1);
191 assert_eq!(added_monitors[0].0, funding_output);
192 added_monitors.clear();
194 _ => panic!("Unexpected event"),
197 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();
199 let mut added_monitors = node_b.chan_monitor.added_monitors.lock().unwrap();
200 assert_eq!(added_monitors.len(), 1);
201 assert_eq!(added_monitors[0].0, funding_output);
202 added_monitors.clear();
205 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();
207 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
208 assert_eq!(added_monitors.len(), 1);
209 assert_eq!(added_monitors[0].0, funding_output);
210 added_monitors.clear();
213 let events_4 = node_a.node.get_and_clear_pending_events();
214 assert_eq!(events_4.len(), 1);
216 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
217 assert_eq!(user_channel_id, 42);
218 assert_eq!(*funding_txo, funding_output);
220 _ => panic!("Unexpected event"),
226 fn create_chan_between_nodes_with_value_confirm(node_a: &Node, node_b: &Node, tx: &Transaction) -> ((msgs::FundingLocked, msgs::AnnouncementSignatures), [u8; 32]) {
227 confirm_transaction(&node_b.chain_monitor, &tx, tx.version);
228 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();
232 confirm_transaction(&node_a.chain_monitor, &tx, tx.version);
233 let events_6 = node_a.node.get_and_clear_pending_msg_events();
234 assert_eq!(events_6.len(), 2);
235 ((match events_6[0] {
236 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
237 channel_id = msg.channel_id.clone();
238 assert_eq!(*node_id, node_b.node.get_our_node_id());
241 _ => panic!("Unexpected event"),
242 }, match events_6[1] {
243 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
244 assert_eq!(*node_id, node_b.node.get_our_node_id());
247 _ => panic!("Unexpected event"),
251 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) {
252 let tx = create_chan_between_nodes_with_value_init(node_a, node_b, channel_value, push_msat);
253 let (msgs, chan_id) = create_chan_between_nodes_with_value_confirm(node_a, node_b, &tx);
257 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) {
258 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &as_funding_msgs.0).unwrap();
259 let bs_announcement_sigs = get_event_msg!(node_b, MessageSendEvent::SendAnnouncementSignatures, node_a.node.get_our_node_id());
260 node_b.node.handle_announcement_signatures(&node_a.node.get_our_node_id(), &as_funding_msgs.1).unwrap();
262 let events_7 = node_b.node.get_and_clear_pending_msg_events();
263 assert_eq!(events_7.len(), 1);
264 let (announcement, bs_update) = match events_7[0] {
265 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
268 _ => panic!("Unexpected event"),
271 node_a.node.handle_announcement_signatures(&node_b.node.get_our_node_id(), &bs_announcement_sigs).unwrap();
272 let events_8 = node_a.node.get_and_clear_pending_msg_events();
273 assert_eq!(events_8.len(), 1);
274 let as_update = match events_8[0] {
275 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
276 assert!(*announcement == *msg);
277 assert_eq!(update_msg.contents.short_channel_id, announcement.contents.short_channel_id);
278 assert_eq!(update_msg.contents.short_channel_id, bs_update.contents.short_channel_id);
281 _ => panic!("Unexpected event"),
284 *node_a.network_chan_count.borrow_mut() += 1;
286 ((*announcement).clone(), (*as_update).clone(), (*bs_update).clone())
289 fn create_announced_chan_between_nodes(nodes: &Vec<Node>, a: usize, b: usize) -> (msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction) {
290 create_announced_chan_between_nodes_with_value(nodes, a, b, 100000, 10001)
293 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) {
294 let chan_announcement = create_chan_between_nodes_with_value(&nodes[a], &nodes[b], channel_value, push_msat);
296 assert!(node.router.handle_channel_announcement(&chan_announcement.0).unwrap());
297 node.router.handle_channel_update(&chan_announcement.1).unwrap();
298 node.router.handle_channel_update(&chan_announcement.2).unwrap();
300 (chan_announcement.1, chan_announcement.2, chan_announcement.3, chan_announcement.4)
303 macro_rules! check_spends {
304 ($tx: expr, $spends_tx: expr) => {
306 let mut funding_tx_map = HashMap::new();
307 let spends_tx = $spends_tx;
308 funding_tx_map.insert(spends_tx.txid(), spends_tx);
309 $tx.verify(&funding_tx_map).unwrap();
314 macro_rules! get_closing_signed_broadcast {
315 ($node: expr, $dest_pubkey: expr) => {
317 let events = $node.get_and_clear_pending_msg_events();
318 assert!(events.len() == 1 || events.len() == 2);
319 (match events[events.len() - 1] {
320 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
321 assert_eq!(msg.contents.flags & 2, 2);
324 _ => panic!("Unexpected event"),
325 }, if events.len() == 2 {
327 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
328 assert_eq!(*node_id, $dest_pubkey);
331 _ => panic!("Unexpected event"),
338 macro_rules! check_closed_broadcast {
340 let events = $node.node.get_and_clear_pending_msg_events();
341 assert_eq!(events.len(), 1);
343 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
344 assert_eq!(msg.contents.flags & 2, 2);
346 _ => panic!("Unexpected event"),
351 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) {
352 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) };
353 let (node_b, broadcaster_b) = if close_inbound_first { (&outbound_node.node, &outbound_node.tx_broadcaster) } else { (&inbound_node.node, &inbound_node.tx_broadcaster) };
356 node_a.close_channel(channel_id).unwrap();
357 node_b.handle_shutdown(&node_a.get_our_node_id(), &get_event_msg!(struct_a, MessageSendEvent::SendShutdown, node_b.get_our_node_id())).unwrap();
359 let events_1 = node_b.get_and_clear_pending_msg_events();
360 assert!(events_1.len() >= 1);
361 let shutdown_b = match events_1[0] {
362 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
363 assert_eq!(node_id, &node_a.get_our_node_id());
366 _ => panic!("Unexpected event"),
369 let closing_signed_b = if !close_inbound_first {
370 assert_eq!(events_1.len(), 1);
373 Some(match events_1[1] {
374 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
375 assert_eq!(node_id, &node_a.get_our_node_id());
378 _ => panic!("Unexpected event"),
382 node_a.handle_shutdown(&node_b.get_our_node_id(), &shutdown_b).unwrap();
383 let (as_update, bs_update) = if close_inbound_first {
384 assert!(node_a.get_and_clear_pending_msg_events().is_empty());
385 node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
386 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
387 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
388 let (as_update, closing_signed_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
390 node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a.unwrap()).unwrap();
391 let (bs_update, none_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
392 assert!(none_b.is_none());
393 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
394 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
395 (as_update, bs_update)
397 let closing_signed_a = get_event_msg!(struct_a, MessageSendEvent::SendClosingSigned, node_b.get_our_node_id());
399 node_b.handle_closing_signed(&node_a.get_our_node_id(), &closing_signed_a).unwrap();
400 assert_eq!(broadcaster_b.txn_broadcasted.lock().unwrap().len(), 1);
401 tx_b = broadcaster_b.txn_broadcasted.lock().unwrap().remove(0);
402 let (bs_update, closing_signed_b) = get_closing_signed_broadcast!(node_b, node_a.get_our_node_id());
404 node_a.handle_closing_signed(&node_b.get_our_node_id(), &closing_signed_b.unwrap()).unwrap();
405 let (as_update, none_a) = get_closing_signed_broadcast!(node_a, node_b.get_our_node_id());
406 assert!(none_a.is_none());
407 assert_eq!(broadcaster_a.txn_broadcasted.lock().unwrap().len(), 1);
408 tx_a = broadcaster_a.txn_broadcasted.lock().unwrap().remove(0);
409 (as_update, bs_update)
411 assert_eq!(tx_a, tx_b);
412 check_spends!(tx_a, funding_tx);
414 (as_update, bs_update, tx_a)
419 msgs: Vec<msgs::UpdateAddHTLC>,
420 commitment_msg: msgs::CommitmentSigned,
423 fn from_commitment_update(node_id: PublicKey, updates: msgs::CommitmentUpdate) -> SendEvent {
424 assert!(updates.update_fulfill_htlcs.is_empty());
425 assert!(updates.update_fail_htlcs.is_empty());
426 assert!(updates.update_fail_malformed_htlcs.is_empty());
427 assert!(updates.update_fee.is_none());
428 SendEvent { node_id: node_id, msgs: updates.update_add_htlcs, commitment_msg: updates.commitment_signed }
431 fn from_event(event: MessageSendEvent) -> SendEvent {
433 MessageSendEvent::UpdateHTLCs { node_id, updates } => SendEvent::from_commitment_update(node_id, updates),
434 _ => panic!("Unexpected event type!"),
438 fn from_node(node: &Node) -> SendEvent {
439 let mut events = node.node.get_and_clear_pending_msg_events();
440 assert_eq!(events.len(), 1);
441 SendEvent::from_event(events.pop().unwrap())
445 macro_rules! check_added_monitors {
446 ($node: expr, $count: expr) => {
448 let mut added_monitors = $node.chan_monitor.added_monitors.lock().unwrap();
449 assert_eq!(added_monitors.len(), $count);
450 added_monitors.clear();
455 macro_rules! commitment_signed_dance {
456 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */) => {
458 check_added_monitors!($node_a, 0);
459 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
460 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
461 check_added_monitors!($node_a, 1);
462 commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, false);
465 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */, true /* return last RAA */) => {
467 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!($node_a, $node_b.node.get_our_node_id());
468 check_added_monitors!($node_b, 0);
469 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
470 $node_b.node.handle_revoke_and_ack(&$node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
471 assert!($node_b.node.get_and_clear_pending_msg_events().is_empty());
472 check_added_monitors!($node_b, 1);
473 $node_b.node.handle_commitment_signed(&$node_a.node.get_our_node_id(), &as_commitment_signed).unwrap();
474 let (bs_revoke_and_ack, extra_msg_option) = {
475 let events = $node_b.node.get_and_clear_pending_msg_events();
476 assert!(events.len() <= 2);
478 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
479 assert_eq!(*node_id, $node_a.node.get_our_node_id());
482 _ => panic!("Unexpected event"),
483 }, events.get(1).map(|e| e.clone()))
485 check_added_monitors!($node_b, 1);
487 assert!($node_a.node.get_and_clear_pending_events().is_empty());
488 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
490 (extra_msg_option, bs_revoke_and_ack)
493 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr, true /* skip last step */, false /* return extra message */, true /* return last RAA */) => {
495 check_added_monitors!($node_a, 0);
496 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
497 $node_a.node.handle_commitment_signed(&$node_b.node.get_our_node_id(), &$commitment_signed).unwrap();
498 check_added_monitors!($node_a, 1);
499 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
500 assert!(extra_msg_option.is_none());
504 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, true /* return extra message */) => {
506 let (extra_msg_option, bs_revoke_and_ack) = commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true, true);
507 $node_a.node.handle_revoke_and_ack(&$node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
508 check_added_monitors!($node_a, 1);
512 ($node_a: expr, $node_b: expr, (), $fail_backwards: expr, true /* skip last step */, false /* no extra message */) => {
514 assert!(commitment_signed_dance!($node_a, $node_b, (), $fail_backwards, true, true).is_none());
517 ($node_a: expr, $node_b: expr, $commitment_signed: expr, $fail_backwards: expr) => {
519 commitment_signed_dance!($node_a, $node_b, $commitment_signed, $fail_backwards, true);
521 expect_pending_htlcs_forwardable!($node_a);
522 check_added_monitors!($node_a, 1);
524 let channel_state = $node_a.node.channel_state.lock().unwrap();
525 assert_eq!(channel_state.pending_msg_events.len(), 1);
526 if let MessageSendEvent::UpdateHTLCs { ref node_id, .. } = channel_state.pending_msg_events[0] {
527 assert_ne!(*node_id, $node_b.node.get_our_node_id());
528 } else { panic!("Unexpected event"); }
530 assert!($node_a.node.get_and_clear_pending_msg_events().is_empty());
536 macro_rules! get_payment_preimage_hash {
539 let payment_preimage = PaymentPreimage([*$node.network_payment_count.borrow(); 32]);
540 *$node.network_payment_count.borrow_mut() += 1;
541 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner());
542 (payment_preimage, payment_hash)
547 macro_rules! expect_pending_htlcs_forwardable {
549 let events = $node.node.get_and_clear_pending_events();
550 assert_eq!(events.len(), 1);
552 Event::PendingHTLCsForwardable { .. } => { },
553 _ => panic!("Unexpected event"),
555 let node_ref: &Node = &$node;
556 node_ref.node.channel_state.lock().unwrap().next_forward = Instant::now();
557 $node.node.process_pending_htlc_forwards();
561 fn send_along_route_with_hash(origin_node: &Node, route: Route, expected_route: &[&Node], recv_value: u64, our_payment_hash: PaymentHash) {
562 let mut payment_event = {
563 origin_node.node.send_payment(route, our_payment_hash).unwrap();
564 check_added_monitors!(origin_node, 1);
566 let mut events = origin_node.node.get_and_clear_pending_msg_events();
567 assert_eq!(events.len(), 1);
568 SendEvent::from_event(events.remove(0))
570 let mut prev_node = origin_node;
572 for (idx, &node) in expected_route.iter().enumerate() {
573 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
575 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
576 check_added_monitors!(node, 0);
577 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
579 expect_pending_htlcs_forwardable!(node);
581 if idx == expected_route.len() - 1 {
582 let events_2 = node.node.get_and_clear_pending_events();
583 assert_eq!(events_2.len(), 1);
585 Event::PaymentReceived { ref payment_hash, amt } => {
586 assert_eq!(our_payment_hash, *payment_hash);
587 assert_eq!(amt, recv_value);
589 _ => panic!("Unexpected event"),
592 let mut events_2 = node.node.get_and_clear_pending_msg_events();
593 assert_eq!(events_2.len(), 1);
594 check_added_monitors!(node, 1);
595 payment_event = SendEvent::from_event(events_2.remove(0));
596 assert_eq!(payment_event.msgs.len(), 1);
603 fn send_along_route(origin_node: &Node, route: Route, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
604 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(origin_node);
605 send_along_route_with_hash(origin_node, route, expected_route, recv_value, our_payment_hash);
606 (our_payment_preimage, our_payment_hash)
609 fn claim_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_preimage: PaymentPreimage) {
610 assert!(expected_route.last().unwrap().node.claim_funds(our_payment_preimage));
611 check_added_monitors!(expected_route.last().unwrap(), 1);
613 let mut next_msgs: Option<(msgs::UpdateFulfillHTLC, msgs::CommitmentSigned)> = None;
614 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
615 macro_rules! get_next_msgs {
618 let events = $node.node.get_and_clear_pending_msg_events();
619 assert_eq!(events.len(), 1);
621 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 } } => {
622 assert!(update_add_htlcs.is_empty());
623 assert_eq!(update_fulfill_htlcs.len(), 1);
624 assert!(update_fail_htlcs.is_empty());
625 assert!(update_fail_malformed_htlcs.is_empty());
626 assert!(update_fee.is_none());
627 expected_next_node = node_id.clone();
628 Some((update_fulfill_htlcs[0].clone(), commitment_signed.clone()))
630 _ => panic!("Unexpected event"),
636 macro_rules! last_update_fulfill_dance {
637 ($node: expr, $prev_node: expr) => {
639 $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
640 check_added_monitors!($node, 0);
641 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
642 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
646 macro_rules! mid_update_fulfill_dance {
647 ($node: expr, $prev_node: expr, $new_msgs: expr) => {
649 $node.node.handle_update_fulfill_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
650 check_added_monitors!($node, 1);
651 let new_next_msgs = if $new_msgs {
652 get_next_msgs!($node)
654 assert!($node.node.get_and_clear_pending_msg_events().is_empty());
657 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, false);
658 next_msgs = new_next_msgs;
663 let mut prev_node = expected_route.last().unwrap();
664 for (idx, node) in expected_route.iter().rev().enumerate() {
665 assert_eq!(expected_next_node, node.node.get_our_node_id());
666 let update_next_msgs = !skip_last || idx != expected_route.len() - 1;
667 if next_msgs.is_some() {
668 mid_update_fulfill_dance!(node, prev_node, update_next_msgs);
669 } else if update_next_msgs {
670 next_msgs = get_next_msgs!(node);
672 assert!(node.node.get_and_clear_pending_msg_events().is_empty());
674 if !skip_last && idx == expected_route.len() - 1 {
675 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
682 last_update_fulfill_dance!(origin_node, expected_route.first().unwrap());
683 let events = origin_node.node.get_and_clear_pending_events();
684 assert_eq!(events.len(), 1);
686 Event::PaymentSent { payment_preimage } => {
687 assert_eq!(payment_preimage, our_payment_preimage);
689 _ => panic!("Unexpected event"),
694 fn claim_payment(origin_node: &Node, expected_route: &[&Node], our_payment_preimage: PaymentPreimage) {
695 claim_payment_along_route(origin_node, expected_route, false, our_payment_preimage);
698 const TEST_FINAL_CLTV: u32 = 32;
700 fn route_payment(origin_node: &Node, expected_route: &[&Node], recv_value: u64) -> (PaymentPreimage, PaymentHash) {
701 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();
702 assert_eq!(route.hops.len(), expected_route.len());
703 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
704 assert_eq!(hop.pubkey, node.node.get_our_node_id());
707 send_along_route(origin_node, route, expected_route, recv_value)
710 fn route_over_limit(origin_node: &Node, expected_route: &[&Node], recv_value: u64) {
711 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();
712 assert_eq!(route.hops.len(), expected_route.len());
713 for (node, hop) in expected_route.iter().zip(route.hops.iter()) {
714 assert_eq!(hop.pubkey, node.node.get_our_node_id());
717 let (_, our_payment_hash) = get_payment_preimage_hash!(origin_node);
719 let err = origin_node.node.send_payment(route, our_payment_hash).err().unwrap();
721 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
722 _ => panic!("Unknown error variants"),
726 fn send_payment(origin: &Node, expected_route: &[&Node], recv_value: u64) {
727 let our_payment_preimage = route_payment(&origin, expected_route, recv_value).0;
728 claim_payment(&origin, expected_route, our_payment_preimage);
731 fn fail_payment_along_route(origin_node: &Node, expected_route: &[&Node], skip_last: bool, our_payment_hash: PaymentHash) {
732 assert!(expected_route.last().unwrap().node.fail_htlc_backwards(&our_payment_hash, 0));
733 expect_pending_htlcs_forwardable!(expected_route.last().unwrap());
734 check_added_monitors!(expected_route.last().unwrap(), 1);
736 let mut next_msgs: Option<(msgs::UpdateFailHTLC, msgs::CommitmentSigned)> = None;
737 macro_rules! update_fail_dance {
738 ($node: expr, $prev_node: expr, $last_node: expr) => {
740 $node.node.handle_update_fail_htlc(&$prev_node.node.get_our_node_id(), &next_msgs.as_ref().unwrap().0).unwrap();
741 commitment_signed_dance!($node, $prev_node, next_msgs.as_ref().unwrap().1, !$last_node);
742 if skip_last && $last_node {
743 expect_pending_htlcs_forwardable!($node);
749 let mut expected_next_node = expected_route.last().unwrap().node.get_our_node_id();
750 let mut prev_node = expected_route.last().unwrap();
751 for (idx, node) in expected_route.iter().rev().enumerate() {
752 assert_eq!(expected_next_node, node.node.get_our_node_id());
753 if next_msgs.is_some() {
754 // We may be the "last node" for the purpose of the commitment dance if we're
755 // skipping the last node (implying it is disconnected) and we're the
756 // second-to-last node!
757 update_fail_dance!(node, prev_node, skip_last && idx == expected_route.len() - 1);
760 let events = node.node.get_and_clear_pending_msg_events();
761 if !skip_last || idx != expected_route.len() - 1 {
762 assert_eq!(events.len(), 1);
764 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 } } => {
765 assert!(update_add_htlcs.is_empty());
766 assert!(update_fulfill_htlcs.is_empty());
767 assert_eq!(update_fail_htlcs.len(), 1);
768 assert!(update_fail_malformed_htlcs.is_empty());
769 assert!(update_fee.is_none());
770 expected_next_node = node_id.clone();
771 next_msgs = Some((update_fail_htlcs[0].clone(), commitment_signed.clone()));
773 _ => panic!("Unexpected event"),
776 assert!(events.is_empty());
778 if !skip_last && idx == expected_route.len() - 1 {
779 assert_eq!(expected_next_node, origin_node.node.get_our_node_id());
786 update_fail_dance!(origin_node, expected_route.first().unwrap(), true);
788 let events = origin_node.node.get_and_clear_pending_events();
789 assert_eq!(events.len(), 1);
791 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
792 assert_eq!(payment_hash, our_payment_hash);
793 assert!(rejected_by_dest);
795 _ => panic!("Unexpected event"),
800 fn fail_payment(origin_node: &Node, expected_route: &[&Node], our_payment_hash: PaymentHash) {
801 fail_payment_along_route(origin_node, expected_route, false, our_payment_hash);
804 fn create_network(node_count: usize) -> Vec<Node> {
805 let mut nodes = Vec::new();
806 let mut rng = thread_rng();
807 let secp_ctx = Secp256k1::new();
809 let chan_count = Rc::new(RefCell::new(0));
810 let payment_count = Rc::new(RefCell::new(0));
812 for i in 0..node_count {
813 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::with_id(format!("node {}", i)));
814 let feeest = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 });
815 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
816 let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())});
817 let mut seed = [0; 32];
818 rng.fill_bytes(&mut seed);
819 let keys_manager = Arc::new(test_utils::TestKeysInterface::new(&seed, Network::Testnet, Arc::clone(&logger)));
820 let chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(chain_monitor.clone(), tx_broadcaster.clone(), logger.clone()));
821 let mut config = UserConfig::new();
822 config.channel_options.announced_channel = true;
823 config.channel_limits.force_announced_channel_preference = false;
824 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();
825 let router = Router::new(PublicKey::from_secret_key(&secp_ctx, &keys_manager.get_node_secret()), chain_monitor.clone(), Arc::clone(&logger));
826 nodes.push(Node { chain_monitor, tx_broadcaster, chan_monitor, node, router, keys_manager, node_seed: seed,
827 network_payment_count: payment_count.clone(),
828 network_chan_count: chan_count.clone(),
836 fn test_async_inbound_update_fee() {
837 let mut nodes = create_network(2);
838 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
839 let channel_id = chan.2;
842 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
846 // send (1) commitment_signed -.
847 // <- update_add_htlc/commitment_signed
848 // send (2) RAA (awaiting remote revoke) -.
849 // (1) commitment_signed is delivered ->
850 // .- send (3) RAA (awaiting remote revoke)
851 // (2) RAA is delivered ->
852 // .- send (4) commitment_signed
853 // <- (3) RAA is delivered
854 // send (5) commitment_signed -.
855 // <- (4) commitment_signed is delivered
857 // (5) commitment_signed is delivered ->
859 // (6) RAA is delivered ->
861 // First nodes[0] generates an update_fee
862 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
863 check_added_monitors!(nodes[0], 1);
865 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
866 assert_eq!(events_0.len(), 1);
867 let (update_msg, commitment_signed) = match events_0[0] { // (1)
868 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
869 (update_fee.as_ref(), commitment_signed)
871 _ => panic!("Unexpected event"),
874 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
876 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
877 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
878 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();
879 check_added_monitors!(nodes[1], 1);
881 let payment_event = {
882 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
883 assert_eq!(events_1.len(), 1);
884 SendEvent::from_event(events_1.remove(0))
886 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
887 assert_eq!(payment_event.msgs.len(), 1);
889 // ...now when the messages get delivered everyone should be happy
890 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
891 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
892 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
893 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
894 check_added_monitors!(nodes[0], 1);
896 // deliver(1), generate (3):
897 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
898 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
899 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
900 check_added_monitors!(nodes[1], 1);
902 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap(); // deliver (2)
903 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
904 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
905 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
906 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
907 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
908 assert!(bs_update.update_fee.is_none()); // (4)
909 check_added_monitors!(nodes[1], 1);
911 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap(); // deliver (3)
912 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
913 assert!(as_update.update_add_htlcs.is_empty()); // (5)
914 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
915 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
916 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
917 assert!(as_update.update_fee.is_none()); // (5)
918 check_added_monitors!(nodes[0], 1);
920 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed).unwrap(); // deliver (4)
921 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
922 // only (6) so get_event_msg's assert(len == 1) passes
923 check_added_monitors!(nodes[0], 1);
925 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed).unwrap(); // deliver (5)
926 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
927 check_added_monitors!(nodes[1], 1);
929 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
930 check_added_monitors!(nodes[0], 1);
932 let events_2 = nodes[0].node.get_and_clear_pending_events();
933 assert_eq!(events_2.len(), 1);
935 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
936 _ => panic!("Unexpected event"),
939 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap(); // deliver (6)
940 check_added_monitors!(nodes[1], 1);
944 fn test_update_fee_unordered_raa() {
945 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
946 // crash in an earlier version of the update_fee patch)
947 let mut nodes = create_network(2);
948 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
949 let channel_id = chan.2;
952 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
954 // First nodes[0] generates an update_fee
955 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
956 check_added_monitors!(nodes[0], 1);
958 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
959 assert_eq!(events_0.len(), 1);
960 let update_msg = match events_0[0] { // (1)
961 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
964 _ => panic!("Unexpected event"),
967 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
969 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
970 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
971 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();
972 check_added_monitors!(nodes[1], 1);
974 let payment_event = {
975 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
976 assert_eq!(events_1.len(), 1);
977 SendEvent::from_event(events_1.remove(0))
979 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
980 assert_eq!(payment_event.msgs.len(), 1);
982 // ...now when the messages get delivered everyone should be happy
983 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
984 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
985 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
986 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
987 check_added_monitors!(nodes[0], 1);
989 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap(); // deliver (2)
990 check_added_monitors!(nodes[1], 1);
992 // We can't continue, sadly, because our (1) now has a bogus signature
996 fn test_multi_flight_update_fee() {
997 let nodes = create_network(2);
998 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
999 let channel_id = chan.2;
1002 // update_fee/commitment_signed ->
1003 // .- send (1) RAA and (2) commitment_signed
1004 // update_fee (never committed) ->
1005 // (3) update_fee ->
1006 // We have to manually generate the above update_fee, it is allowed by the protocol but we
1007 // don't track which updates correspond to which revoke_and_ack responses so we're in
1008 // AwaitingRAA mode and will not generate the update_fee yet.
1009 // <- (1) RAA delivered
1010 // (3) is generated and send (4) CS -.
1011 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
1012 // know the per_commitment_point to use for it.
1013 // <- (2) commitment_signed delivered
1014 // revoke_and_ack ->
1015 // B should send no response here
1016 // (4) commitment_signed delivered ->
1017 // <- RAA/commitment_signed delivered
1018 // revoke_and_ack ->
1020 // First nodes[0] generates an update_fee
1021 let initial_feerate = get_feerate!(nodes[0], channel_id);
1022 nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
1023 check_added_monitors!(nodes[0], 1);
1025 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
1026 assert_eq!(events_0.len(), 1);
1027 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
1028 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
1029 (update_fee.as_ref().unwrap(), commitment_signed)
1031 _ => panic!("Unexpected event"),
1034 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
1035 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1).unwrap();
1036 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1).unwrap();
1037 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1038 check_added_monitors!(nodes[1], 1);
1040 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
1042 nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
1043 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1044 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1046 // Create the (3) update_fee message that nodes[0] will generate before it does...
1047 let mut update_msg_2 = msgs::UpdateFee {
1048 channel_id: update_msg_1.channel_id.clone(),
1049 feerate_per_kw: (initial_feerate + 30) as u32,
1052 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
1054 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
1056 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
1058 // Deliver (1), generating (3) and (4)
1059 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg).unwrap();
1060 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1061 check_added_monitors!(nodes[0], 1);
1062 assert!(as_second_update.update_add_htlcs.is_empty());
1063 assert!(as_second_update.update_fulfill_htlcs.is_empty());
1064 assert!(as_second_update.update_fail_htlcs.is_empty());
1065 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
1066 // Check that the update_fee newly generated matches what we delivered:
1067 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
1068 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
1070 // Deliver (2) commitment_signed
1071 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
1072 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1073 check_added_monitors!(nodes[0], 1);
1074 // No commitment_signed so get_event_msg's assert(len == 1) passes
1076 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap();
1077 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1078 check_added_monitors!(nodes[1], 1);
1081 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed).unwrap();
1082 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1083 check_added_monitors!(nodes[1], 1);
1085 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
1086 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1087 check_added_monitors!(nodes[0], 1);
1089 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment).unwrap();
1090 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1091 // No commitment_signed so get_event_msg's assert(len == 1) passes
1092 check_added_monitors!(nodes[0], 1);
1094 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap();
1095 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1096 check_added_monitors!(nodes[1], 1);
1100 fn test_update_fee_vanilla() {
1101 let nodes = create_network(2);
1102 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
1103 let channel_id = chan.2;
1105 let feerate = get_feerate!(nodes[0], channel_id);
1106 nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
1107 check_added_monitors!(nodes[0], 1);
1109 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
1110 assert_eq!(events_0.len(), 1);
1111 let (update_msg, commitment_signed) = match events_0[0] {
1112 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 } } => {
1113 (update_fee.as_ref(), commitment_signed)
1115 _ => panic!("Unexpected event"),
1117 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
1119 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
1120 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1121 check_added_monitors!(nodes[1], 1);
1123 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
1124 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1125 check_added_monitors!(nodes[0], 1);
1127 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
1128 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1129 // No commitment_signed so get_event_msg's assert(len == 1) passes
1130 check_added_monitors!(nodes[0], 1);
1132 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
1133 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1134 check_added_monitors!(nodes[1], 1);
1138 fn test_update_fee_that_funder_cannot_afford() {
1139 let nodes = create_network(2);
1140 let channel_value = 1888;
1141 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000);
1142 let channel_id = chan.2;
1145 nodes[0].node.update_fee(channel_id, feerate).unwrap();
1146 check_added_monitors!(nodes[0], 1);
1147 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1149 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap()).unwrap();
1151 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
1153 //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
1154 //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
1156 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1157 let chan = chan_lock.by_id.get(&channel_id).unwrap();
1159 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
1160 let num_htlcs = chan.last_local_commitment_txn[0].output.len() - 2;
1161 let total_fee: u64 = feerate * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
1162 let mut actual_fee = chan.last_local_commitment_txn[0].output.iter().fold(0, |acc, output| acc + output.value);
1163 actual_fee = channel_value - actual_fee;
1164 assert_eq!(total_fee, actual_fee);
1167 //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
1168 //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
1169 nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
1170 check_added_monitors!(nodes[0], 1);
1172 let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1174 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap()).unwrap();
1176 //While producing the commitment_signed response after handling a received update_fee request the
1177 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
1178 //Should produce and error.
1179 let err = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed).unwrap_err();
1181 assert!(match err.err {
1182 "Funding remote cannot afford proposed new fee" => true,
1186 //clear the message we could not handle
1187 nodes[1].node.get_and_clear_pending_msg_events();
1191 fn test_update_fee_with_fundee_update_add_htlc() {
1192 let mut nodes = create_network(2);
1193 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
1194 let channel_id = chan.2;
1197 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1199 let feerate = get_feerate!(nodes[0], channel_id);
1200 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
1201 check_added_monitors!(nodes[0], 1);
1203 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
1204 assert_eq!(events_0.len(), 1);
1205 let (update_msg, commitment_signed) = match events_0[0] {
1206 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 } } => {
1207 (update_fee.as_ref(), commitment_signed)
1209 _ => panic!("Unexpected event"),
1211 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
1212 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
1213 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1214 check_added_monitors!(nodes[1], 1);
1216 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 800000, TEST_FINAL_CLTV).unwrap();
1218 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
1220 // nothing happens since node[1] is in AwaitingRemoteRevoke
1221 nodes[1].node.send_payment(route, our_payment_hash).unwrap();
1223 let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
1224 assert_eq!(added_monitors.len(), 0);
1225 added_monitors.clear();
1227 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1228 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1229 // node[1] has nothing to do
1231 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
1232 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1233 check_added_monitors!(nodes[0], 1);
1235 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
1236 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1237 // No commitment_signed so get_event_msg's assert(len == 1) passes
1238 check_added_monitors!(nodes[0], 1);
1239 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
1240 check_added_monitors!(nodes[1], 1);
1241 // AwaitingRemoteRevoke ends here
1243 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1244 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
1245 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
1246 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
1247 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
1248 assert_eq!(commitment_update.update_fee.is_none(), true);
1250 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]).unwrap();
1251 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
1252 check_added_monitors!(nodes[0], 1);
1253 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1255 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke).unwrap();
1256 check_added_monitors!(nodes[1], 1);
1257 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1259 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed).unwrap();
1260 check_added_monitors!(nodes[1], 1);
1261 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1262 // No commitment_signed so get_event_msg's assert(len == 1) passes
1264 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke).unwrap();
1265 check_added_monitors!(nodes[0], 1);
1266 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1268 expect_pending_htlcs_forwardable!(nodes[0]);
1270 let events = nodes[0].node.get_and_clear_pending_events();
1271 assert_eq!(events.len(), 1);
1273 Event::PaymentReceived { .. } => { },
1274 _ => panic!("Unexpected event"),
1277 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
1279 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
1280 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
1281 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
1285 fn test_update_fee() {
1286 let nodes = create_network(2);
1287 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
1288 let channel_id = chan.2;
1291 // (1) update_fee/commitment_signed ->
1292 // <- (2) revoke_and_ack
1293 // .- send (3) commitment_signed
1294 // (4) update_fee/commitment_signed ->
1295 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
1296 // <- (3) commitment_signed delivered
1297 // send (6) revoke_and_ack -.
1298 // <- (5) deliver revoke_and_ack
1299 // (6) deliver revoke_and_ack ->
1300 // .- send (7) commitment_signed in response to (4)
1301 // <- (7) deliver commitment_signed
1302 // revoke_and_ack ->
1304 // Create and deliver (1)...
1305 let feerate = get_feerate!(nodes[0], channel_id);
1306 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
1307 check_added_monitors!(nodes[0], 1);
1309 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
1310 assert_eq!(events_0.len(), 1);
1311 let (update_msg, commitment_signed) = match events_0[0] {
1312 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 } } => {
1313 (update_fee.as_ref(), commitment_signed)
1315 _ => panic!("Unexpected event"),
1317 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
1319 // Generate (2) and (3):
1320 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
1321 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1322 check_added_monitors!(nodes[1], 1);
1325 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
1326 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1327 check_added_monitors!(nodes[0], 1);
1329 // Create and deliver (4)...
1330 nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
1331 check_added_monitors!(nodes[0], 1);
1332 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
1333 assert_eq!(events_0.len(), 1);
1334 let (update_msg, commitment_signed) = match events_0[0] {
1335 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 } } => {
1336 (update_fee.as_ref(), commitment_signed)
1338 _ => panic!("Unexpected event"),
1341 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
1342 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
1343 check_added_monitors!(nodes[1], 1);
1345 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1346 // No commitment_signed so get_event_msg's assert(len == 1) passes
1348 // Handle (3), creating (6):
1349 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0).unwrap();
1350 check_added_monitors!(nodes[0], 1);
1351 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1352 // No commitment_signed so get_event_msg's assert(len == 1) passes
1355 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
1356 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1357 check_added_monitors!(nodes[0], 1);
1359 // Deliver (6), creating (7):
1360 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0).unwrap();
1361 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1362 assert!(commitment_update.update_add_htlcs.is_empty());
1363 assert!(commitment_update.update_fulfill_htlcs.is_empty());
1364 assert!(commitment_update.update_fail_htlcs.is_empty());
1365 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
1366 assert!(commitment_update.update_fee.is_none());
1367 check_added_monitors!(nodes[1], 1);
1370 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
1371 check_added_monitors!(nodes[0], 1);
1372 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1373 // No commitment_signed so get_event_msg's assert(len == 1) passes
1375 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
1376 check_added_monitors!(nodes[1], 1);
1377 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1379 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
1380 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
1381 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
1385 fn pre_funding_lock_shutdown_test() {
1386 // Test sending a shutdown prior to funding_locked after funding generation
1387 let nodes = create_network(2);
1388 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0);
1389 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1390 nodes[0].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
1391 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
1393 nodes[0].node.close_channel(&OutPoint::new(tx.txid(), 0).to_channel_id()).unwrap();
1394 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1395 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
1396 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1397 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
1399 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1400 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
1401 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1402 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
1403 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1404 assert!(node_0_none.is_none());
1406 assert!(nodes[0].node.list_channels().is_empty());
1407 assert!(nodes[1].node.list_channels().is_empty());
1411 fn updates_shutdown_wait() {
1412 // Test sending a shutdown with outstanding updates pending
1413 let mut nodes = create_network(3);
1414 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1415 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1416 let route_1 = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
1417 let route_2 = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
1419 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
1421 nodes[0].node.close_channel(&chan_1.2).unwrap();
1422 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1423 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
1424 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1425 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
1427 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1428 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1430 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1431 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route_1, payment_hash) {}
1432 else { panic!("New sends should fail!") };
1433 if let Err(APIError::ChannelUnavailable {..}) = nodes[1].node.send_payment(route_2, payment_hash) {}
1434 else { panic!("New sends should fail!") };
1436 assert!(nodes[2].node.claim_funds(our_payment_preimage));
1437 check_added_monitors!(nodes[2], 1);
1438 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1439 assert!(updates.update_add_htlcs.is_empty());
1440 assert!(updates.update_fail_htlcs.is_empty());
1441 assert!(updates.update_fail_malformed_htlcs.is_empty());
1442 assert!(updates.update_fee.is_none());
1443 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
1444 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
1445 check_added_monitors!(nodes[1], 1);
1446 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1447 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
1449 assert!(updates_2.update_add_htlcs.is_empty());
1450 assert!(updates_2.update_fail_htlcs.is_empty());
1451 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
1452 assert!(updates_2.update_fee.is_none());
1453 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
1454 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
1455 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
1457 let events = nodes[0].node.get_and_clear_pending_events();
1458 assert_eq!(events.len(), 1);
1460 Event::PaymentSent { ref payment_preimage } => {
1461 assert_eq!(our_payment_preimage, *payment_preimage);
1463 _ => panic!("Unexpected event"),
1466 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1467 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
1468 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1469 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
1470 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1471 assert!(node_0_none.is_none());
1473 assert!(nodes[0].node.list_channels().is_empty());
1475 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1476 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1477 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1478 assert!(nodes[1].node.list_channels().is_empty());
1479 assert!(nodes[2].node.list_channels().is_empty());
1483 fn htlc_fail_async_shutdown() {
1484 // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
1485 let mut nodes = create_network(3);
1486 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1487 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1489 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
1490 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
1491 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
1492 check_added_monitors!(nodes[0], 1);
1493 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1494 assert_eq!(updates.update_add_htlcs.len(), 1);
1495 assert!(updates.update_fulfill_htlcs.is_empty());
1496 assert!(updates.update_fail_htlcs.is_empty());
1497 assert!(updates.update_fail_malformed_htlcs.is_empty());
1498 assert!(updates.update_fee.is_none());
1500 nodes[1].node.close_channel(&chan_1.2).unwrap();
1501 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1502 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
1503 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1505 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
1506 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed).unwrap();
1507 check_added_monitors!(nodes[1], 1);
1508 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
1509 commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
1511 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1512 assert!(updates_2.update_add_htlcs.is_empty());
1513 assert!(updates_2.update_fulfill_htlcs.is_empty());
1514 assert_eq!(updates_2.update_fail_htlcs.len(), 1);
1515 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
1516 assert!(updates_2.update_fee.is_none());
1518 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]).unwrap();
1519 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
1521 let events = nodes[0].node.get_and_clear_pending_events();
1522 assert_eq!(events.len(), 1);
1524 Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } => {
1525 assert_eq!(our_payment_hash, *payment_hash);
1526 assert!(!rejected_by_dest);
1528 _ => panic!("Unexpected event"),
1531 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1532 assert_eq!(msg_events.len(), 2);
1533 let node_0_closing_signed = match msg_events[0] {
1534 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
1535 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
1538 _ => panic!("Unexpected event"),
1540 match msg_events[1] {
1541 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
1542 assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
1544 _ => panic!("Unexpected event"),
1547 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1548 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
1549 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1550 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
1551 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1552 assert!(node_0_none.is_none());
1554 assert!(nodes[0].node.list_channels().is_empty());
1556 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1557 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1558 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1559 assert!(nodes[1].node.list_channels().is_empty());
1560 assert!(nodes[2].node.list_channels().is_empty());
1563 fn do_test_shutdown_rebroadcast(recv_count: u8) {
1564 // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
1565 // messages delivered prior to disconnect
1566 let nodes = create_network(3);
1567 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1568 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1570 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
1572 nodes[1].node.close_channel(&chan_1.2).unwrap();
1573 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1575 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
1576 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1578 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
1582 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1583 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1585 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
1586 let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1587 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
1588 let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1590 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish).unwrap();
1591 let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1592 assert!(node_1_shutdown == node_1_2nd_shutdown);
1594 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish).unwrap();
1595 let node_0_2nd_shutdown = if recv_count > 0 {
1596 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1597 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
1600 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1601 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
1602 get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
1604 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown).unwrap();
1606 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1607 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1609 assert!(nodes[2].node.claim_funds(our_payment_preimage));
1610 check_added_monitors!(nodes[2], 1);
1611 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1612 assert!(updates.update_add_htlcs.is_empty());
1613 assert!(updates.update_fail_htlcs.is_empty());
1614 assert!(updates.update_fail_malformed_htlcs.is_empty());
1615 assert!(updates.update_fee.is_none());
1616 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
1617 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
1618 check_added_monitors!(nodes[1], 1);
1619 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1620 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
1622 assert!(updates_2.update_add_htlcs.is_empty());
1623 assert!(updates_2.update_fail_htlcs.is_empty());
1624 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
1625 assert!(updates_2.update_fee.is_none());
1626 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
1627 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
1628 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
1630 let events = nodes[0].node.get_and_clear_pending_events();
1631 assert_eq!(events.len(), 1);
1633 Event::PaymentSent { ref payment_preimage } => {
1634 assert_eq!(our_payment_preimage, *payment_preimage);
1636 _ => panic!("Unexpected event"),
1639 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1641 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
1642 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1643 assert!(node_1_closing_signed.is_some());
1646 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1647 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1649 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
1650 let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1651 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
1652 if recv_count == 0 {
1653 // If all closing_signeds weren't delivered we can just resume where we left off...
1654 let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1656 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish).unwrap();
1657 let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1658 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
1660 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish).unwrap();
1661 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1662 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
1664 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown).unwrap();
1665 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1667 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown).unwrap();
1668 let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1669 assert!(node_0_closing_signed == node_0_2nd_closing_signed);
1671 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed).unwrap();
1672 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1673 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
1674 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1675 assert!(node_0_none.is_none());
1677 // If one node, however, received + responded with an identical closing_signed we end
1678 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
1679 // There isn't really anything better we can do simply, but in the future we might
1680 // explore storing a set of recently-closed channels that got disconnected during
1681 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
1682 // give our counterparty enough time to (potentially) broadcast a cooperative closing
1684 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1686 if let Err(msgs::HandleError{action: Some(msgs::ErrorAction::SendErrorMessage{msg}), ..}) =
1687 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish) {
1688 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
1689 let msgs::ErrorMessage {ref channel_id, ..} = msg;
1690 assert_eq!(*channel_id, chan_1.2);
1691 } else { panic!("Needed SendErrorMessage close"); }
1693 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
1694 // checks it, but in this case nodes[0] didn't ever get a chance to receive a
1695 // closing_signed so we do it ourselves
1696 check_closed_broadcast!(nodes[0]);
1699 assert!(nodes[0].node.list_channels().is_empty());
1701 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1702 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1703 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1704 assert!(nodes[1].node.list_channels().is_empty());
1705 assert!(nodes[2].node.list_channels().is_empty());
1709 fn test_shutdown_rebroadcast() {
1710 do_test_shutdown_rebroadcast(0);
1711 do_test_shutdown_rebroadcast(1);
1712 do_test_shutdown_rebroadcast(2);
1716 fn fake_network_test() {
1717 // Simple test which builds a network of ChannelManagers, connects them to each other, and
1718 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
1719 let nodes = create_network(4);
1721 // Create some initial channels
1722 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1723 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1724 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
1726 // Rebalance the network a bit by relaying one payment through all the channels...
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);
1730 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1732 // Send some more payments
1733 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
1734 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
1735 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
1737 // Test failure packets
1738 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1739 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1741 // Add a new channel that skips 3
1742 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
1744 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
1745 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
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);
1750 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1752 // Do some rebalance loop payments, simultaneously
1753 let mut hops = Vec::with_capacity(3);
1754 hops.push(RouteHop {
1755 pubkey: nodes[2].node.get_our_node_id(),
1756 short_channel_id: chan_2.0.contents.short_channel_id,
1758 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1760 hops.push(RouteHop {
1761 pubkey: nodes[3].node.get_our_node_id(),
1762 short_channel_id: chan_3.0.contents.short_channel_id,
1764 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1766 hops.push(RouteHop {
1767 pubkey: nodes[1].node.get_our_node_id(),
1768 short_channel_id: chan_4.0.contents.short_channel_id,
1770 cltv_expiry_delta: TEST_FINAL_CLTV,
1772 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;
1773 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;
1774 let payment_preimage_1 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1776 let mut hops = Vec::with_capacity(3);
1777 hops.push(RouteHop {
1778 pubkey: nodes[3].node.get_our_node_id(),
1779 short_channel_id: chan_4.0.contents.short_channel_id,
1781 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1783 hops.push(RouteHop {
1784 pubkey: nodes[2].node.get_our_node_id(),
1785 short_channel_id: chan_3.0.contents.short_channel_id,
1787 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1789 hops.push(RouteHop {
1790 pubkey: nodes[1].node.get_our_node_id(),
1791 short_channel_id: chan_2.0.contents.short_channel_id,
1793 cltv_expiry_delta: TEST_FINAL_CLTV,
1795 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;
1796 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;
1797 let payment_hash_2 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1799 // Claim the rebalances...
1800 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1801 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1803 // Add a duplicate new channel from 2 to 4
1804 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3);
1806 // Send some payments across both channels
1807 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1808 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1809 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1811 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1813 //TODO: Test that routes work again here as we've been notified that the channel is full
1815 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
1816 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
1817 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
1819 // Close down the channels...
1820 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1821 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1822 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1823 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1824 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1828 fn duplicate_htlc_test() {
1829 // Test that we accept duplicate payment_hash HTLCs across the network and that
1830 // claiming/failing them are all separate and don't effect each other
1831 let mut nodes = create_network(6);
1833 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1834 create_announced_chan_between_nodes(&nodes, 0, 3);
1835 create_announced_chan_between_nodes(&nodes, 1, 3);
1836 create_announced_chan_between_nodes(&nodes, 2, 3);
1837 create_announced_chan_between_nodes(&nodes, 3, 4);
1838 create_announced_chan_between_nodes(&nodes, 3, 5);
1840 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1842 *nodes[0].network_payment_count.borrow_mut() -= 1;
1843 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1845 *nodes[0].network_payment_count.borrow_mut() -= 1;
1846 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1848 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1849 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1850 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1853 #[derive(PartialEq)]
1854 enum HTLCType { NONE, TIMEOUT, SUCCESS }
1855 /// Tests that the given node has broadcast transactions for the given Channel
1857 /// First checks that the latest local commitment tx has been broadcast, unless an explicit
1858 /// commitment_tx is provided, which may be used to test that a remote commitment tx was
1859 /// broadcast and the revoked outputs were claimed.
1861 /// Next tests that there is (or is not) a transaction that spends the commitment transaction
1862 /// that appears to be the type of HTLC transaction specified in has_htlc_tx.
1864 /// All broadcast transactions must be accounted for in one of the above three types of we'll
1866 fn test_txn_broadcast(node: &Node, chan: &(msgs::ChannelUpdate, msgs::ChannelUpdate, [u8; 32], Transaction), commitment_tx: Option<Transaction>, has_htlc_tx: HTLCType) -> Vec<Transaction> {
1867 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
1868 assert!(node_txn.len() >= if commitment_tx.is_some() { 0 } else { 1 } + if has_htlc_tx == HTLCType::NONE { 0 } else { 1 });
1870 let mut res = Vec::with_capacity(2);
1871 node_txn.retain(|tx| {
1872 if tx.input.len() == 1 && tx.input[0].previous_output.txid == chan.3.txid() {
1873 check_spends!(tx, chan.3.clone());
1874 if commitment_tx.is_none() {
1875 res.push(tx.clone());
1880 if let Some(explicit_tx) = commitment_tx {
1881 res.push(explicit_tx.clone());
1884 assert_eq!(res.len(), 1);
1886 if has_htlc_tx != HTLCType::NONE {
1887 node_txn.retain(|tx| {
1888 if tx.input.len() == 1 && tx.input[0].previous_output.txid == res[0].txid() {
1889 check_spends!(tx, res[0].clone());
1890 if has_htlc_tx == HTLCType::TIMEOUT {
1891 assert!(tx.lock_time != 0);
1893 assert!(tx.lock_time == 0);
1895 res.push(tx.clone());
1899 assert!(res.len() == 2 || res.len() == 3);
1901 assert_eq!(res[1], res[2]);
1905 assert!(node_txn.is_empty());
1909 /// Tests that the given node has broadcast a claim transaction against the provided revoked
1910 /// HTLC transaction.
1911 fn test_revoked_htlc_claim_txn_broadcast(node: &Node, revoked_tx: Transaction) {
1912 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
1913 assert_eq!(node_txn.len(), 1);
1914 node_txn.retain(|tx| {
1915 if tx.input.len() == 1 && tx.input[0].previous_output.txid == revoked_tx.txid() {
1916 check_spends!(tx, revoked_tx.clone());
1920 assert!(node_txn.is_empty());
1923 fn check_preimage_claim(node: &Node, prev_txn: &Vec<Transaction>) -> Vec<Transaction> {
1924 let mut node_txn = node.tx_broadcaster.txn_broadcasted.lock().unwrap();
1926 assert!(node_txn.len() >= 1);
1927 assert_eq!(node_txn[0].input.len(), 1);
1928 let mut found_prev = false;
1930 for tx in prev_txn {
1931 if node_txn[0].input[0].previous_output.txid == tx.txid() {
1932 check_spends!(node_txn[0], tx.clone());
1933 assert!(node_txn[0].input[0].witness[2].len() > 106); // must spend an htlc output
1934 assert_eq!(tx.input.len(), 1); // must spend a commitment tx
1940 assert!(found_prev);
1942 let mut res = Vec::new();
1943 mem::swap(&mut *node_txn, &mut res);
1947 fn get_announce_close_broadcast_events(nodes: &Vec<Node>, a: usize, b: usize) {
1948 let events_1 = nodes[a].node.get_and_clear_pending_msg_events();
1949 assert_eq!(events_1.len(), 1);
1950 let as_update = match events_1[0] {
1951 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
1954 _ => panic!("Unexpected event"),
1957 let events_2 = nodes[b].node.get_and_clear_pending_msg_events();
1958 assert_eq!(events_2.len(), 1);
1959 let bs_update = match events_2[0] {
1960 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
1963 _ => panic!("Unexpected event"),
1967 node.router.handle_channel_update(&as_update).unwrap();
1968 node.router.handle_channel_update(&bs_update).unwrap();
1972 macro_rules! expect_payment_received {
1973 ($node: expr, $expected_payment_hash: expr, $expected_recv_value: expr) => {
1974 let events = $node.node.get_and_clear_pending_events();
1975 assert_eq!(events.len(), 1);
1977 Event::PaymentReceived { ref payment_hash, amt } => {
1978 assert_eq!($expected_payment_hash, *payment_hash);
1979 assert_eq!($expected_recv_value, amt);
1981 _ => panic!("Unexpected event"),
1986 macro_rules! get_channel_value_stat {
1987 ($node: expr, $channel_id: expr) => {{
1988 let chan_lock = $node.node.channel_state.lock().unwrap();
1989 let chan = chan_lock.by_id.get(&$channel_id).unwrap();
1990 chan.get_value_stat()
1994 fn do_channel_reserve_test(test_recv: bool) {
1996 use std::sync::atomic::Ordering;
1997 use ln::msgs::HandleError;
1999 let mut nodes = create_network(3);
2000 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1900, 1001);
2001 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1900, 1001);
2003 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
2004 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
2006 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
2007 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
2009 macro_rules! get_route_and_payment_hash {
2010 ($recv_value: expr) => {{
2011 let route = nodes[0].router.get_route(&nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV).unwrap();
2012 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
2013 (route, payment_hash, payment_preimage)
2017 macro_rules! expect_forward {
2019 let mut events = $node.node.get_and_clear_pending_msg_events();
2020 assert_eq!(events.len(), 1);
2021 check_added_monitors!($node, 1);
2022 let payment_event = SendEvent::from_event(events.remove(0));
2027 let feemsat = 239; // somehow we know?
2028 let total_fee_msat = (nodes.len() - 2) as u64 * 239;
2030 let recv_value_0 = stat01.their_max_htlc_value_in_flight_msat - total_fee_msat;
2032 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
2034 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
2035 assert!(route.hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
2036 let err = nodes[0].node.send_payment(route, our_payment_hash).err().unwrap();
2038 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight"),
2039 _ => panic!("Unknown error variants"),
2043 let mut htlc_id = 0;
2044 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
2045 // nodes[0]'s wealth
2047 let amt_msat = recv_value_0 + total_fee_msat;
2048 if stat01.value_to_self_msat - amt_msat < stat01.channel_reserve_msat {
2051 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
2054 let (stat01_, stat11_, stat12_, stat22_) = (
2055 get_channel_value_stat!(nodes[0], chan_1.2),
2056 get_channel_value_stat!(nodes[1], chan_1.2),
2057 get_channel_value_stat!(nodes[1], chan_2.2),
2058 get_channel_value_stat!(nodes[2], chan_2.2),
2061 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
2062 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
2063 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
2064 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
2065 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
2069 let recv_value = stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat;
2070 // attempt to get channel_reserve violation
2071 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value + 1);
2072 let err = nodes[0].node.send_payment(route.clone(), our_payment_hash).err().unwrap();
2074 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
2075 _ => panic!("Unknown error variants"),
2079 // adding pending output
2080 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat)/2;
2081 let amt_msat_1 = recv_value_1 + total_fee_msat;
2083 let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
2084 let payment_event_1 = {
2085 nodes[0].node.send_payment(route_1, our_payment_hash_1).unwrap();
2086 check_added_monitors!(nodes[0], 1);
2088 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2089 assert_eq!(events.len(), 1);
2090 SendEvent::from_event(events.remove(0))
2092 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]).unwrap();
2094 // channel reserve test with htlc pending output > 0
2095 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat;
2097 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
2098 match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
2099 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
2100 _ => panic!("Unknown error variants"),
2105 // test channel_reserve test on nodes[1] side
2106 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
2108 // Need to manually create update_add_htlc message to go around the channel reserve check in send_htlc()
2109 let secp_ctx = Secp256k1::new();
2110 let session_priv = SecretKey::from_slice(&secp_ctx, &{
2111 let mut session_key = [0; 32];
2112 rng::fill_bytes(&mut session_key);
2114 }).expect("RNG is bad!");
2116 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
2117 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
2118 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
2119 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, &our_payment_hash);
2120 let msg = msgs::UpdateAddHTLC {
2121 channel_id: chan_1.2,
2123 amount_msat: htlc_msat,
2124 payment_hash: our_payment_hash,
2125 cltv_expiry: htlc_cltv,
2126 onion_routing_packet: onion_packet,
2130 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg).err().unwrap();
2132 HandleError{err, .. } => assert_eq!(err, "Remote HTLC add would put them over their reserve value"),
2134 // If we send a garbage message, the channel should get closed, making the rest of this test case fail.
2135 assert_eq!(nodes[1].node.list_channels().len(), 1);
2136 assert_eq!(nodes[1].node.list_channels().len(), 1);
2137 check_closed_broadcast!(nodes[1]);
2142 // split the rest to test holding cell
2143 let recv_value_21 = recv_value_2/2;
2144 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat;
2146 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
2147 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);
2150 // now see if they go through on both sides
2151 let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
2152 // but this will stuck in the holding cell
2153 nodes[0].node.send_payment(route_21, our_payment_hash_21).unwrap();
2154 check_added_monitors!(nodes[0], 0);
2155 let events = nodes[0].node.get_and_clear_pending_events();
2156 assert_eq!(events.len(), 0);
2158 // test with outbound holding cell amount > 0
2160 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
2161 match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
2162 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over our reserve value"),
2163 _ => panic!("Unknown error variants"),
2167 let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
2168 // this will also stuck in the holding cell
2169 nodes[0].node.send_payment(route_22, our_payment_hash_22).unwrap();
2170 check_added_monitors!(nodes[0], 0);
2171 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
2172 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2174 // flush the pending htlc
2175 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg).unwrap();
2176 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2177 check_added_monitors!(nodes[1], 1);
2179 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
2180 check_added_monitors!(nodes[0], 1);
2181 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2183 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed).unwrap();
2184 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2185 // No commitment_signed so get_event_msg's assert(len == 1) passes
2186 check_added_monitors!(nodes[0], 1);
2188 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
2189 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2190 check_added_monitors!(nodes[1], 1);
2192 expect_pending_htlcs_forwardable!(nodes[1]);
2194 let ref payment_event_11 = expect_forward!(nodes[1]);
2195 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]).unwrap();
2196 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
2198 expect_pending_htlcs_forwardable!(nodes[2]);
2199 expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
2201 // flush the htlcs in the holding cell
2202 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
2203 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]).unwrap();
2204 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]).unwrap();
2205 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
2206 expect_pending_htlcs_forwardable!(nodes[1]);
2208 let ref payment_event_3 = expect_forward!(nodes[1]);
2209 assert_eq!(payment_event_3.msgs.len(), 2);
2210 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]).unwrap();
2211 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]).unwrap();
2213 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2214 expect_pending_htlcs_forwardable!(nodes[2]);
2216 let events = nodes[2].node.get_and_clear_pending_events();
2217 assert_eq!(events.len(), 2);
2219 Event::PaymentReceived { ref payment_hash, amt } => {
2220 assert_eq!(our_payment_hash_21, *payment_hash);
2221 assert_eq!(recv_value_21, amt);
2223 _ => panic!("Unexpected event"),
2226 Event::PaymentReceived { ref payment_hash, amt } => {
2227 assert_eq!(our_payment_hash_22, *payment_hash);
2228 assert_eq!(recv_value_22, amt);
2230 _ => panic!("Unexpected event"),
2233 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2234 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2235 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2237 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);
2238 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
2239 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2240 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat);
2242 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2243 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22);
2247 fn channel_reserve_test() {
2248 do_channel_reserve_test(false);
2249 do_channel_reserve_test(true);
2253 fn channel_monitor_network_test() {
2254 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2255 // tests that ChannelMonitor is able to recover from various states.
2256 let nodes = create_network(5);
2258 // Create some initial channels
2259 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2260 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2261 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2262 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
2264 // Rebalance the network a bit by relaying one payment through all the channels...
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);
2268 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2270 // Simple case with no pending HTLCs:
2271 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2273 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2274 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2275 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
2276 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2278 get_announce_close_broadcast_events(&nodes, 0, 1);
2279 assert_eq!(nodes[0].node.list_channels().len(), 0);
2280 assert_eq!(nodes[1].node.list_channels().len(), 1);
2282 // One pending HTLC is discarded by the force-close:
2283 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2285 // Simple case of one pending HTLC to HTLC-Timeout
2286 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2288 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2289 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2290 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
2291 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2293 get_announce_close_broadcast_events(&nodes, 1, 2);
2294 assert_eq!(nodes[1].node.list_channels().len(), 0);
2295 assert_eq!(nodes[2].node.list_channels().len(), 1);
2297 macro_rules! claim_funds {
2298 ($node: expr, $prev_node: expr, $preimage: expr) => {
2300 assert!($node.node.claim_funds($preimage));
2301 check_added_monitors!($node, 1);
2303 let events = $node.node.get_and_clear_pending_msg_events();
2304 assert_eq!(events.len(), 1);
2306 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2307 assert!(update_add_htlcs.is_empty());
2308 assert!(update_fail_htlcs.is_empty());
2309 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2311 _ => panic!("Unexpected event"),
2317 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2318 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2319 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2321 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2323 // Claim the payment on nodes[3], giving it knowledge of the preimage
2324 claim_funds!(nodes[3], nodes[2], payment_preimage_1);
2326 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2327 nodes[3].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 1);
2329 check_preimage_claim(&nodes[3], &node_txn);
2331 get_announce_close_broadcast_events(&nodes, 2, 3);
2332 assert_eq!(nodes[2].node.list_channels().len(), 0);
2333 assert_eq!(nodes[3].node.list_channels().len(), 1);
2335 { // Cheat and reset nodes[4]'s height to 1
2336 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2337 nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![] }, 1);
2340 assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
2341 assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
2342 // One pending HTLC to time out:
2343 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2344 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2348 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2349 nodes[3].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
2350 for i in 3..TEST_FINAL_CLTV + 2 + HTLC_FAIL_TIMEOUT_BLOCKS + 1 {
2351 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2352 nodes[3].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
2355 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2357 // Claim the payment on nodes[4], giving it knowledge of the preimage
2358 claim_funds!(nodes[4], nodes[3], payment_preimage_2);
2360 header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2361 nodes[4].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
2362 for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
2363 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2364 nodes[4].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
2367 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2369 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2370 nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, TEST_FINAL_CLTV - 5);
2372 check_preimage_claim(&nodes[4], &node_txn);
2374 get_announce_close_broadcast_events(&nodes, 3, 4);
2375 assert_eq!(nodes[3].node.list_channels().len(), 0);
2376 assert_eq!(nodes[4].node.list_channels().len(), 0);
2380 fn test_justice_tx() {
2381 // Test justice txn built on revoked HTLC-Success tx, against both sides
2383 let nodes = create_network(2);
2384 // Create some new channels:
2385 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
2387 // A pending HTLC which will be revoked:
2388 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2389 // Get the will-be-revoked local txn from nodes[0]
2390 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
2391 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2392 assert_eq!(revoked_local_txn[0].input.len(), 1);
2393 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2394 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2395 assert_eq!(revoked_local_txn[1].input.len(), 1);
2396 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2397 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2398 // Revoke the old state
2399 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2402 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2403 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2405 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2406 assert_eq!(node_txn.len(), 3);
2407 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
2408 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2410 check_spends!(node_txn[0], revoked_local_txn[0].clone());
2411 node_txn.swap_remove(0);
2413 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2415 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2416 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2417 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2418 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2419 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone());
2421 get_announce_close_broadcast_events(&nodes, 0, 1);
2423 assert_eq!(nodes[0].node.list_channels().len(), 0);
2424 assert_eq!(nodes[1].node.list_channels().len(), 0);
2426 // We test justice_tx build by A on B's revoked HTLC-Success tx
2427 // Create some new channels:
2428 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
2430 // A pending HTLC which will be revoked:
2431 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2432 // Get the will-be-revoked local txn from B
2433 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
2434 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2435 assert_eq!(revoked_local_txn[0].input.len(), 1);
2436 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2437 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2438 // Revoke the old state
2439 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2441 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2442 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2444 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2445 assert_eq!(node_txn.len(), 3);
2446 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
2447 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2449 check_spends!(node_txn[0], revoked_local_txn[0].clone());
2450 node_txn.swap_remove(0);
2452 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2454 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2455 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2456 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2457 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2458 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone());
2460 get_announce_close_broadcast_events(&nodes, 0, 1);
2461 assert_eq!(nodes[0].node.list_channels().len(), 0);
2462 assert_eq!(nodes[1].node.list_channels().len(), 0);
2466 fn revoked_output_claim() {
2467 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2468 // transaction is broadcast by its counterparty
2469 let nodes = create_network(2);
2470 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2471 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2472 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
2473 assert_eq!(revoked_local_txn.len(), 1);
2474 // Only output is the full channel value back to nodes[0]:
2475 assert_eq!(revoked_local_txn[0].output.len(), 1);
2476 // Send a payment through, updating everyone's latest commitment txn
2477 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2479 // Inform nodes[1] that nodes[0] broadcast a stale tx
2480 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2481 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2482 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2483 assert_eq!(node_txn.len(), 3); // nodes[1] will broadcast justice tx twice, and its own local state once
2485 assert_eq!(node_txn[0], node_txn[2]);
2487 check_spends!(node_txn[0], revoked_local_txn[0].clone());
2488 check_spends!(node_txn[1], chan_1.3.clone());
2490 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2491 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2492 get_announce_close_broadcast_events(&nodes, 0, 1);
2496 fn claim_htlc_outputs_shared_tx() {
2497 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2498 let nodes = create_network(2);
2500 // Create some new channel:
2501 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2503 // Rebalance the network to generate htlc in the two directions
2504 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2505 // 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
2506 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2507 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2509 // Get the will-be-revoked local txn from node[0]
2510 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
2511 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2512 assert_eq!(revoked_local_txn[0].input.len(), 1);
2513 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2514 assert_eq!(revoked_local_txn[1].input.len(), 1);
2515 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2516 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2517 check_spends!(revoked_local_txn[1], revoked_local_txn[0].clone());
2519 //Revoke the old state
2520 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2523 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2524 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2525 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2527 let events = nodes[1].node.get_and_clear_pending_events();
2528 assert_eq!(events.len(), 1);
2530 Event::PaymentFailed { payment_hash, .. } => {
2531 assert_eq!(payment_hash, payment_hash_2);
2533 _ => panic!("Unexpected event"),
2536 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2537 assert_eq!(node_txn.len(), 4);
2539 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2540 check_spends!(node_txn[0], revoked_local_txn[0].clone());
2542 assert_eq!(node_txn[0], node_txn[3]); // justice tx is duplicated due to block re-scanning
2544 let mut witness_lens = BTreeSet::new();
2545 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2546 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2547 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2548 assert_eq!(witness_lens.len(), 3);
2549 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2550 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2551 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2553 // Next nodes[1] broadcasts its current local tx state:
2554 assert_eq!(node_txn[1].input.len(), 1);
2555 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2557 assert_eq!(node_txn[2].input.len(), 1);
2558 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
2559 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2560 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
2561 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
2562 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
2564 get_announce_close_broadcast_events(&nodes, 0, 1);
2565 assert_eq!(nodes[0].node.list_channels().len(), 0);
2566 assert_eq!(nodes[1].node.list_channels().len(), 0);
2570 fn claim_htlc_outputs_single_tx() {
2571 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2572 let nodes = create_network(2);
2574 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2576 // Rebalance the network to generate htlc in the two directions
2577 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2578 // 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
2579 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2580 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2581 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2583 // Get the will-be-revoked local txn from node[0]
2584 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
2586 //Revoke the old state
2587 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2590 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2591 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2592 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2594 let events = nodes[1].node.get_and_clear_pending_events();
2595 assert_eq!(events.len(), 1);
2597 Event::PaymentFailed { payment_hash, .. } => {
2598 assert_eq!(payment_hash, payment_hash_2);
2600 _ => panic!("Unexpected event"),
2603 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2604 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)
2606 assert_eq!(node_txn[0], node_txn[7]);
2607 assert_eq!(node_txn[1], node_txn[8]);
2608 assert_eq!(node_txn[2], node_txn[9]);
2609 assert_eq!(node_txn[3], node_txn[10]);
2610 assert_eq!(node_txn[4], node_txn[11]);
2611 assert_eq!(node_txn[3], node_txn[5]); //local commitment tx + htlc timeout tx broadcated by ChannelManger
2612 assert_eq!(node_txn[4], node_txn[6]);
2614 assert_eq!(node_txn[0].input.len(), 1);
2615 assert_eq!(node_txn[1].input.len(), 1);
2616 assert_eq!(node_txn[2].input.len(), 1);
2618 let mut revoked_tx_map = HashMap::new();
2619 revoked_tx_map.insert(revoked_local_txn[0].txid(), revoked_local_txn[0].clone());
2620 node_txn[0].verify(&revoked_tx_map).unwrap();
2621 node_txn[1].verify(&revoked_tx_map).unwrap();
2622 node_txn[2].verify(&revoked_tx_map).unwrap();
2624 let mut witness_lens = BTreeSet::new();
2625 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2626 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2627 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2628 assert_eq!(witness_lens.len(), 3);
2629 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2630 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2631 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2633 assert_eq!(node_txn[3].input.len(), 1);
2634 check_spends!(node_txn[3], chan_1.3.clone());
2636 assert_eq!(node_txn[4].input.len(), 1);
2637 let witness_script = node_txn[4].input[0].witness.last().unwrap();
2638 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2639 assert_eq!(node_txn[4].input[0].previous_output.txid, node_txn[3].txid());
2640 assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
2641 assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[1].input[0].previous_output.txid);
2643 get_announce_close_broadcast_events(&nodes, 0, 1);
2644 assert_eq!(nodes[0].node.list_channels().len(), 0);
2645 assert_eq!(nodes[1].node.list_channels().len(), 0);
2649 fn test_htlc_on_chain_success() {
2650 // Test that in case of an unilateral close onchain, we detect the state of output thanks to
2651 // ChainWatchInterface and pass the preimage backward accordingly. So here we test that ChannelManager is
2652 // broadcasting the right event to other nodes in payment path.
2653 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2654 // A --------------------> B ----------------------> C (preimage)
2655 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2656 // commitment transaction was broadcast.
2657 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2659 // B should be able to claim via preimage if A then broadcasts its local tx.
2660 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2661 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2662 // PaymentSent event).
2664 let nodes = create_network(3);
2666 // Create some initial channels
2667 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2668 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2670 // Rebalance the network a bit by relaying one payment through all the channels...
2671 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2672 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2674 let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2675 let (our_payment_preimage_2, _payment_hash_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2676 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2678 // Broadcast legit commitment tx from C on B's chain
2679 // Broadcast HTLC Success transation by C on received output from C's commitment tx on B's chain
2680 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
2681 assert_eq!(commitment_tx.len(), 1);
2682 check_spends!(commitment_tx[0], chan_2.3.clone());
2683 nodes[2].node.claim_funds(our_payment_preimage);
2684 nodes[2].node.claim_funds(our_payment_preimage_2);
2685 check_added_monitors!(nodes[2], 2);
2686 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2687 assert!(updates.update_add_htlcs.is_empty());
2688 assert!(updates.update_fail_htlcs.is_empty());
2689 assert!(updates.update_fail_malformed_htlcs.is_empty());
2690 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2692 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2693 check_closed_broadcast!(nodes[2]);
2694 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx), ChannelMonitor : 4 (2*2 * HTLC-Success tx)
2695 assert_eq!(node_txn.len(), 5);
2696 assert_eq!(node_txn[0], node_txn[3]);
2697 assert_eq!(node_txn[1], node_txn[4]);
2698 assert_eq!(node_txn[2], commitment_tx[0]);
2699 check_spends!(node_txn[0], commitment_tx[0].clone());
2700 check_spends!(node_txn[1], commitment_tx[0].clone());
2701 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2702 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2703 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2704 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2705 assert_eq!(node_txn[0].lock_time, 0);
2706 assert_eq!(node_txn[1].lock_time, 0);
2708 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2709 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: node_txn}, 1);
2710 let events = nodes[1].node.get_and_clear_pending_msg_events();
2712 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
2713 assert_eq!(added_monitors.len(), 2);
2714 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2715 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2716 added_monitors.clear();
2718 assert_eq!(events.len(), 2);
2720 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2721 _ => panic!("Unexpected event"),
2724 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, .. } } => {
2725 assert!(update_add_htlcs.is_empty());
2726 assert!(update_fail_htlcs.is_empty());
2727 assert_eq!(update_fulfill_htlcs.len(), 1);
2728 assert!(update_fail_malformed_htlcs.is_empty());
2729 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2731 _ => panic!("Unexpected event"),
2733 macro_rules! check_tx_local_broadcast {
2734 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2735 // ChannelManager : 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor : 2 (timeout tx) * 2 (block-rescan)
2736 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2737 assert_eq!(node_txn.len(), 7);
2738 assert_eq!(node_txn[0], node_txn[5]);
2739 assert_eq!(node_txn[1], node_txn[6]);
2740 check_spends!(node_txn[0], $commitment_tx.clone());
2741 check_spends!(node_txn[1], $commitment_tx.clone());
2742 assert_ne!(node_txn[0].lock_time, 0);
2743 assert_ne!(node_txn[1].lock_time, 0);
2745 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2746 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2747 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2748 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2750 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2751 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2752 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2753 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2755 check_spends!(node_txn[2], $chan_tx.clone());
2756 check_spends!(node_txn[3], node_txn[2].clone());
2757 check_spends!(node_txn[4], node_txn[2].clone());
2758 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), 71);
2759 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2760 assert_eq!(node_txn[4].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2761 assert!(node_txn[3].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2762 assert!(node_txn[4].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2763 assert_ne!(node_txn[3].lock_time, 0);
2764 assert_ne!(node_txn[4].lock_time, 0);
2768 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2769 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2770 // timeout-claim of the output that nodes[2] just claimed via success.
2771 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2773 // Broadcast legit commitment tx from A on B's chain
2774 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2775 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
2776 check_spends!(commitment_tx[0], chan_1.3.clone());
2777 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2778 check_closed_broadcast!(nodes[1]);
2779 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx), ChannelMonitor : 1 (HTLC-Success) * 2 (block-rescan)
2780 assert_eq!(node_txn.len(), 3);
2781 assert_eq!(node_txn[0], node_txn[2]);
2782 check_spends!(node_txn[0], commitment_tx[0].clone());
2783 assert_eq!(node_txn[0].input.len(), 2);
2784 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2785 assert_eq!(node_txn[0].input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2786 assert_eq!(node_txn[0].lock_time, 0);
2787 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2788 check_spends!(node_txn[1], chan_1.3.clone());
2789 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
2790 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2791 // we already checked the same situation with A.
2793 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2794 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
2795 check_closed_broadcast!(nodes[0]);
2796 let events = nodes[0].node.get_and_clear_pending_events();
2797 assert_eq!(events.len(), 2);
2798 let mut first_claimed = false;
2799 for event in events {
2801 Event::PaymentSent { payment_preimage } => {
2802 if payment_preimage == our_payment_preimage {
2803 assert!(!first_claimed);
2804 first_claimed = true;
2806 assert_eq!(payment_preimage, our_payment_preimage_2);
2809 _ => panic!("Unexpected event"),
2812 check_tx_local_broadcast!(nodes[0], true, commitment_tx[0], chan_1.3);
2816 fn test_htlc_on_chain_timeout() {
2817 // Test that in case of an unilateral close onchain, we detect the state of output thanks to
2818 // ChainWatchInterface and timeout the HTLC bacward accordingly. So here we test that ChannelManager is
2819 // broadcasting the right event to other nodes in payment path.
2820 // A ------------------> B ----------------------> C (timeout)
2821 // B's commitment tx C's commitment tx
2823 // B's HTLC timeout tx B's timeout tx
2825 let nodes = create_network(3);
2827 // Create some intial channels
2828 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2829 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2831 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2832 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2833 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2835 let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2836 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2838 // Brodacast legit commitment tx from C on B's chain
2839 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
2840 check_spends!(commitment_tx[0], chan_2.3.clone());
2841 nodes[2].node.fail_htlc_backwards(&payment_hash, 0);
2842 check_added_monitors!(nodes[2], 0);
2843 expect_pending_htlcs_forwardable!(nodes[2]);
2844 check_added_monitors!(nodes[2], 1);
2846 let events = nodes[2].node.get_and_clear_pending_msg_events();
2847 assert_eq!(events.len(), 1);
2849 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, .. } } => {
2850 assert!(update_add_htlcs.is_empty());
2851 assert!(!update_fail_htlcs.is_empty());
2852 assert!(update_fulfill_htlcs.is_empty());
2853 assert!(update_fail_malformed_htlcs.is_empty());
2854 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2856 _ => panic!("Unexpected event"),
2858 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2859 check_closed_broadcast!(nodes[2]);
2860 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2861 assert_eq!(node_txn.len(), 1);
2862 check_spends!(node_txn[0], chan_2.3.clone());
2863 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2865 // Broadcast timeout transaction by B on received output fron C's commitment tx on B's chain
2866 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2867 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
2870 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2871 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)
2872 assert_eq!(node_txn[0], node_txn[5]);
2873 assert_eq!(node_txn[1], node_txn[6]);
2874 assert_eq!(node_txn[2], node_txn[7]);
2875 check_spends!(node_txn[0], commitment_tx[0].clone());
2876 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2877 check_spends!(node_txn[1], chan_2.3.clone());
2878 check_spends!(node_txn[2], node_txn[1].clone());
2879 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
2880 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2881 check_spends!(node_txn[3], chan_2.3.clone());
2882 check_spends!(node_txn[4], node_txn[3].clone());
2883 assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2884 assert_eq!(node_txn[4].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2885 timeout_tx = node_txn[0].clone();
2889 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![timeout_tx]}, 1);
2890 check_added_monitors!(nodes[1], 0);
2891 check_closed_broadcast!(nodes[1]);
2893 expect_pending_htlcs_forwardable!(nodes[1]);
2894 check_added_monitors!(nodes[1], 1);
2895 let events = nodes[1].node.get_and_clear_pending_msg_events();
2896 assert_eq!(events.len(), 1);
2898 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, .. } } => {
2899 assert!(update_add_htlcs.is_empty());
2900 assert!(!update_fail_htlcs.is_empty());
2901 assert!(update_fulfill_htlcs.is_empty());
2902 assert!(update_fail_malformed_htlcs.is_empty());
2903 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2905 _ => panic!("Unexpected event"),
2907 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
2908 assert_eq!(node_txn.len(), 0);
2910 // Broadcast legit commitment tx from B on A's chain
2911 let commitment_tx = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
2912 check_spends!(commitment_tx[0], chan_1.3.clone());
2914 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
2915 check_closed_broadcast!(nodes[0]);
2916 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
2917 assert_eq!(node_txn.len(), 4);
2918 assert_eq!(node_txn[0], node_txn[3]);
2919 check_spends!(node_txn[0], commitment_tx[0].clone());
2920 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2921 check_spends!(node_txn[1], chan_1.3.clone());
2922 check_spends!(node_txn[2], node_txn[1].clone());
2923 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
2924 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2928 fn test_simple_commitment_revoked_fail_backward() {
2929 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
2930 // and fail backward accordingly.
2932 let nodes = create_network(3);
2934 // Create some initial channels
2935 create_announced_chan_between_nodes(&nodes, 0, 1);
2936 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2938 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2939 // Get the will-be-revoked local txn from nodes[2]
2940 let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
2941 // Revoke the old state
2942 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
2944 route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2946 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2947 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2948 check_added_monitors!(nodes[1], 0);
2949 check_closed_broadcast!(nodes[1]);
2951 expect_pending_htlcs_forwardable!(nodes[1]);
2952 check_added_monitors!(nodes[1], 1);
2953 let events = nodes[1].node.get_and_clear_pending_msg_events();
2954 assert_eq!(events.len(), 1);
2956 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, .. } } => {
2957 assert!(update_add_htlcs.is_empty());
2958 assert_eq!(update_fail_htlcs.len(), 1);
2959 assert!(update_fulfill_htlcs.is_empty());
2960 assert!(update_fail_malformed_htlcs.is_empty());
2961 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2963 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]).unwrap();
2964 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
2966 let events = nodes[0].node.get_and_clear_pending_msg_events();
2967 assert_eq!(events.len(), 1);
2969 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
2970 _ => panic!("Unexpected event"),
2972 let events = nodes[0].node.get_and_clear_pending_events();
2973 assert_eq!(events.len(), 1);
2975 Event::PaymentFailed { .. } => {},
2976 _ => panic!("Unexpected event"),
2979 _ => panic!("Unexpected event"),
2983 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
2984 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
2985 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
2986 // commitment transaction anymore.
2987 // To do this, we have the peer which will broadcast a revoked commitment transaction send
2988 // a number of update_fail/commitment_signed updates without ever sending the RAA in
2989 // response to our commitment_signed. This is somewhat misbehavior-y, though not
2990 // technically disallowed and we should probably handle it reasonably.
2991 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
2992 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
2994 // * Once we move it out of our holding cell/add it, we will immediately include it in a
2995 // commitment_signed (implying it will be in the latest remote commitment transaction).
2996 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
2997 // and once they revoke the previous commitment transaction (allowing us to send a new
2998 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
2999 let mut nodes = create_network(3);
3001 // Create some initial channels
3002 create_announced_chan_between_nodes(&nodes, 0, 1);
3003 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3005 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3006 // Get the will-be-revoked local txn from nodes[2]
3007 let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
3008 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3009 // Revoke the old state
3010 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3012 let value = if use_dust {
3013 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3014 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3015 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().our_dust_limit_satoshis * 1000
3018 let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3019 let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3020 let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3022 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, 0));
3023 expect_pending_htlcs_forwardable!(nodes[2]);
3024 check_added_monitors!(nodes[2], 1);
3025 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3026 assert!(updates.update_add_htlcs.is_empty());
3027 assert!(updates.update_fulfill_htlcs.is_empty());
3028 assert!(updates.update_fail_malformed_htlcs.is_empty());
3029 assert_eq!(updates.update_fail_htlcs.len(), 1);
3030 assert!(updates.update_fee.is_none());
3031 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
3032 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3033 // Drop the last RAA from 3 -> 2
3035 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, 0));
3036 expect_pending_htlcs_forwardable!(nodes[2]);
3037 check_added_monitors!(nodes[2], 1);
3038 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3039 assert!(updates.update_add_htlcs.is_empty());
3040 assert!(updates.update_fulfill_htlcs.is_empty());
3041 assert!(updates.update_fail_malformed_htlcs.is_empty());
3042 assert_eq!(updates.update_fail_htlcs.len(), 1);
3043 assert!(updates.update_fee.is_none());
3044 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
3045 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed).unwrap();
3046 check_added_monitors!(nodes[1], 1);
3047 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3048 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3049 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
3050 check_added_monitors!(nodes[2], 1);
3052 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, 0));
3053 expect_pending_htlcs_forwardable!(nodes[2]);
3054 check_added_monitors!(nodes[2], 1);
3055 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3056 assert!(updates.update_add_htlcs.is_empty());
3057 assert!(updates.update_fulfill_htlcs.is_empty());
3058 assert!(updates.update_fail_malformed_htlcs.is_empty());
3059 assert_eq!(updates.update_fail_htlcs.len(), 1);
3060 assert!(updates.update_fee.is_none());
3061 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
3062 // At this point first_payment_hash has dropped out of the latest two commitment
3063 // transactions that nodes[1] is tracking...
3064 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed).unwrap();
3065 check_added_monitors!(nodes[1], 1);
3066 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3067 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3068 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
3069 check_added_monitors!(nodes[2], 1);
3071 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3072 // on nodes[2]'s RAA.
3073 let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
3074 let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3075 nodes[1].node.send_payment(route, fourth_payment_hash).unwrap();
3076 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3077 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3078 check_added_monitors!(nodes[1], 0);
3081 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa).unwrap();
3082 // One monitor for the new revocation preimage, no second on as we won't generate a new
3083 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3084 check_added_monitors!(nodes[1], 1);
3085 let events = nodes[1].node.get_and_clear_pending_events();
3086 assert_eq!(events.len(), 1);
3088 Event::PendingHTLCsForwardable { .. } => { },
3089 _ => panic!("Unexpected event"),
3091 // Deliberately don't process the pending fail-back so they all fail back at once after
3092 // block connection just like the !deliver_bs_raa case
3095 let mut failed_htlcs = HashSet::new();
3096 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3098 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
3099 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3101 let events = nodes[1].node.get_and_clear_pending_events();
3102 assert_eq!(events.len(), if deliver_bs_raa { 1 } else { 2 });
3104 Event::PaymentFailed { ref payment_hash, .. } => {
3105 assert_eq!(*payment_hash, fourth_payment_hash);
3107 _ => panic!("Unexpected event"),
3109 if !deliver_bs_raa {
3111 Event::PendingHTLCsForwardable { .. } => { },
3112 _ => panic!("Unexpected event"),
3115 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
3116 nodes[1].node.process_pending_htlc_forwards();
3117 check_added_monitors!(nodes[1], 1);
3119 let events = nodes[1].node.get_and_clear_pending_msg_events();
3120 assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
3121 match events[if deliver_bs_raa { 1 } else { 0 }] {
3122 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3123 _ => panic!("Unexpected event"),
3127 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, .. } } => {
3128 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3129 assert_eq!(update_add_htlcs.len(), 1);
3130 assert!(update_fulfill_htlcs.is_empty());
3131 assert!(update_fail_htlcs.is_empty());
3132 assert!(update_fail_malformed_htlcs.is_empty());
3134 _ => panic!("Unexpected event"),
3137 match events[if deliver_bs_raa { 2 } else { 1 }] {
3138 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, .. } } => {
3139 assert!(update_add_htlcs.is_empty());
3140 assert_eq!(update_fail_htlcs.len(), 3);
3141 assert!(update_fulfill_htlcs.is_empty());
3142 assert!(update_fail_malformed_htlcs.is_empty());
3143 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3145 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]).unwrap();
3146 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]).unwrap();
3147 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]).unwrap();
3149 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3151 let events = nodes[0].node.get_and_clear_pending_msg_events();
3152 // If we delievered B's RAA we got an unknown preimage error, not something
3153 // that we should update our routing table for.
3154 assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
3155 for event in events {
3157 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3158 _ => panic!("Unexpected event"),
3161 let events = nodes[0].node.get_and_clear_pending_events();
3162 assert_eq!(events.len(), 3);
3164 Event::PaymentFailed { ref payment_hash, .. } => {
3165 assert!(failed_htlcs.insert(payment_hash.0));
3167 _ => panic!("Unexpected event"),
3170 Event::PaymentFailed { ref payment_hash, .. } => {
3171 assert!(failed_htlcs.insert(payment_hash.0));
3173 _ => panic!("Unexpected event"),
3176 Event::PaymentFailed { ref payment_hash, .. } => {
3177 assert!(failed_htlcs.insert(payment_hash.0));
3179 _ => panic!("Unexpected event"),
3182 _ => panic!("Unexpected event"),
3185 assert!(failed_htlcs.contains(&first_payment_hash.0));
3186 assert!(failed_htlcs.contains(&second_payment_hash.0));
3187 assert!(failed_htlcs.contains(&third_payment_hash.0));
3191 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3192 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3193 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3194 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3195 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3199 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3200 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3201 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3202 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3203 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3207 fn test_htlc_ignore_latest_remote_commitment() {
3208 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3209 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3210 let nodes = create_network(2);
3211 create_announced_chan_between_nodes(&nodes, 0, 1);
3213 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3214 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
3215 check_closed_broadcast!(nodes[0]);
3217 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3218 assert_eq!(node_txn.len(), 2);
3220 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3221 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
3222 check_closed_broadcast!(nodes[1]);
3224 // Duplicate the block_connected call since this may happen due to other listeners
3225 // registering new transactions
3226 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
3230 fn test_force_close_fail_back() {
3231 // Check which HTLCs are failed-backwards on channel force-closure
3232 let mut nodes = create_network(3);
3233 create_announced_chan_between_nodes(&nodes, 0, 1);
3234 create_announced_chan_between_nodes(&nodes, 1, 2);
3236 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, 42).unwrap();
3238 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3240 let mut payment_event = {
3241 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
3242 check_added_monitors!(nodes[0], 1);
3244 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3245 assert_eq!(events.len(), 1);
3246 SendEvent::from_event(events.remove(0))
3249 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
3250 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3252 expect_pending_htlcs_forwardable!(nodes[1]);
3254 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3255 assert_eq!(events_2.len(), 1);
3256 payment_event = SendEvent::from_event(events_2.remove(0));
3257 assert_eq!(payment_event.msgs.len(), 1);
3259 check_added_monitors!(nodes[1], 1);
3260 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
3261 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
3262 check_added_monitors!(nodes[2], 1);
3263 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3265 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3266 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3267 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3269 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
3270 check_closed_broadcast!(nodes[2]);
3272 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3273 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3274 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3275 // back to nodes[1] upon timeout otherwise.
3276 assert_eq!(node_txn.len(), 1);
3280 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3281 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
3283 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3284 check_closed_broadcast!(nodes[1]);
3286 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3288 let mut monitors = nodes[2].chan_monitor.simple_monitor.monitors.lock().unwrap();
3289 monitors.get_mut(&OutPoint::new(Sha256dHash::from(&payment_event.commitment_msg.channel_id[..]), 0)).unwrap()
3290 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
3292 nodes[2].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
3293 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3294 assert_eq!(node_txn.len(), 1);
3295 assert_eq!(node_txn[0].input.len(), 1);
3296 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3297 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3298 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3300 check_spends!(node_txn[0], tx);
3304 fn test_unconf_chan() {
3305 // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
3306 let nodes = create_network(2);
3307 create_announced_chan_between_nodes(&nodes, 0, 1);
3309 let channel_state = nodes[0].node.channel_state.lock().unwrap();
3310 assert_eq!(channel_state.by_id.len(), 1);
3311 assert_eq!(channel_state.short_to_id.len(), 1);
3312 mem::drop(channel_state);
3314 let mut headers = Vec::new();
3315 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3316 headers.push(header.clone());
3318 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3319 headers.push(header.clone());
3321 while !headers.is_empty() {
3322 nodes[0].node.block_disconnected(&headers.pop().unwrap());
3324 check_closed_broadcast!(nodes[0]);
3325 let channel_state = nodes[0].node.channel_state.lock().unwrap();
3326 assert_eq!(channel_state.by_id.len(), 0);
3327 assert_eq!(channel_state.short_to_id.len(), 0);
3330 macro_rules! get_chan_reestablish_msgs {
3331 ($src_node: expr, $dst_node: expr) => {
3333 let mut res = Vec::with_capacity(1);
3334 for msg in $src_node.node.get_and_clear_pending_msg_events() {
3335 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
3336 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
3337 res.push(msg.clone());
3339 panic!("Unexpected event")
3347 macro_rules! handle_chan_reestablish_msgs {
3348 ($src_node: expr, $dst_node: expr) => {
3350 let msg_events = $src_node.node.get_and_clear_pending_msg_events();
3352 let funding_locked = if let Some(&MessageSendEvent::SendFundingLocked { ref node_id, ref msg }) = msg_events.get(0) {
3354 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
3360 let mut revoke_and_ack = None;
3361 let mut commitment_update = None;
3362 let order = if let Some(ev) = msg_events.get(idx) {
3365 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
3366 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
3367 revoke_and_ack = Some(msg.clone());
3368 RAACommitmentOrder::RevokeAndACKFirst
3370 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3371 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
3372 commitment_update = Some(updates.clone());
3373 RAACommitmentOrder::CommitmentFirst
3375 _ => panic!("Unexpected event"),
3378 RAACommitmentOrder::CommitmentFirst
3381 if let Some(ev) = msg_events.get(idx) {
3383 &MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
3384 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
3385 assert!(revoke_and_ack.is_none());
3386 revoke_and_ack = Some(msg.clone());
3388 &MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3389 assert_eq!(*node_id, $dst_node.node.get_our_node_id());
3390 assert!(commitment_update.is_none());
3391 commitment_update = Some(updates.clone());
3393 _ => panic!("Unexpected event"),
3397 (funding_locked, revoke_and_ack, commitment_update, order)
3402 /// pending_htlc_adds includes both the holding cell and in-flight update_add_htlcs, whereas
3403 /// for claims/fails they are separated out.
3404 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)) {
3405 node_a.node.peer_connected(&node_b.node.get_our_node_id());
3406 let reestablish_1 = get_chan_reestablish_msgs!(node_a, node_b);
3407 node_b.node.peer_connected(&node_a.node.get_our_node_id());
3408 let reestablish_2 = get_chan_reestablish_msgs!(node_b, node_a);
3410 if send_funding_locked.0 {
3411 // If a expects a funding_locked, it better not think it has received a revoke_and_ack
3413 for reestablish in reestablish_1.iter() {
3414 assert_eq!(reestablish.next_remote_commitment_number, 0);
3417 if send_funding_locked.1 {
3418 // If b expects a funding_locked, it better not think it has received a revoke_and_ack
3420 for reestablish in reestablish_2.iter() {
3421 assert_eq!(reestablish.next_remote_commitment_number, 0);
3424 if send_funding_locked.0 || send_funding_locked.1 {
3425 // If we expect any funding_locked's, both sides better have set
3426 // next_local_commitment_number to 1
3427 for reestablish in reestablish_1.iter() {
3428 assert_eq!(reestablish.next_local_commitment_number, 1);
3430 for reestablish in reestablish_2.iter() {
3431 assert_eq!(reestablish.next_local_commitment_number, 1);
3435 let mut resp_1 = Vec::new();
3436 for msg in reestablish_1 {
3437 node_b.node.handle_channel_reestablish(&node_a.node.get_our_node_id(), &msg).unwrap();
3438 resp_1.push(handle_chan_reestablish_msgs!(node_b, node_a));
3440 if pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
3441 check_added_monitors!(node_b, 1);
3443 check_added_monitors!(node_b, 0);
3446 let mut resp_2 = Vec::new();
3447 for msg in reestablish_2 {
3448 node_a.node.handle_channel_reestablish(&node_b.node.get_our_node_id(), &msg).unwrap();
3449 resp_2.push(handle_chan_reestablish_msgs!(node_a, node_b));
3451 if pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
3452 check_added_monitors!(node_a, 1);
3454 check_added_monitors!(node_a, 0);
3457 // We dont yet support both needing updates, as that would require a different commitment dance:
3458 assert!((pending_htlc_adds.0 == 0 && pending_htlc_claims.0 == 0 && pending_cell_htlc_claims.0 == 0 && pending_cell_htlc_fails.0 == 0) ||
3459 (pending_htlc_adds.1 == 0 && pending_htlc_claims.1 == 0 && pending_cell_htlc_claims.1 == 0 && pending_cell_htlc_fails.1 == 0));
3461 for chan_msgs in resp_1.drain(..) {
3462 if send_funding_locked.0 {
3463 node_a.node.handle_funding_locked(&node_b.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
3464 let announcement_event = node_a.node.get_and_clear_pending_msg_events();
3465 if !announcement_event.is_empty() {
3466 assert_eq!(announcement_event.len(), 1);
3467 if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
3468 //TODO: Test announcement_sigs re-sending
3469 } else { panic!("Unexpected event!"); }
3472 assert!(chan_msgs.0.is_none());
3475 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
3476 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
3477 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
3478 check_added_monitors!(node_a, 1);
3480 assert!(chan_msgs.1.is_none());
3482 if pending_htlc_adds.0 != 0 || pending_htlc_claims.0 != 0 || pending_cell_htlc_claims.0 != 0 || pending_cell_htlc_fails.0 != 0 {
3483 let commitment_update = chan_msgs.2.unwrap();
3484 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
3485 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.0 as usize);
3487 assert!(commitment_update.update_add_htlcs.is_empty());
3489 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
3490 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
3491 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
3492 for update_add in commitment_update.update_add_htlcs {
3493 node_a.node.handle_update_add_htlc(&node_b.node.get_our_node_id(), &update_add).unwrap();
3495 for update_fulfill in commitment_update.update_fulfill_htlcs {
3496 node_a.node.handle_update_fulfill_htlc(&node_b.node.get_our_node_id(), &update_fulfill).unwrap();
3498 for update_fail in commitment_update.update_fail_htlcs {
3499 node_a.node.handle_update_fail_htlc(&node_b.node.get_our_node_id(), &update_fail).unwrap();
3502 if pending_htlc_adds.0 != -1 { // We use -1 to denote a response commitment_signed
3503 commitment_signed_dance!(node_a, node_b, commitment_update.commitment_signed, false);
3505 node_a.node.handle_commitment_signed(&node_b.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
3506 check_added_monitors!(node_a, 1);
3507 let as_revoke_and_ack = get_event_msg!(node_a, MessageSendEvent::SendRevokeAndACK, node_b.node.get_our_node_id());
3508 // No commitment_signed so get_event_msg's assert(len == 1) passes
3509 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &as_revoke_and_ack).unwrap();
3510 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
3511 check_added_monitors!(node_b, 1);
3514 assert!(chan_msgs.2.is_none());
3518 for chan_msgs in resp_2.drain(..) {
3519 if send_funding_locked.1 {
3520 node_b.node.handle_funding_locked(&node_a.node.get_our_node_id(), &chan_msgs.0.unwrap()).unwrap();
3521 let announcement_event = node_b.node.get_and_clear_pending_msg_events();
3522 if !announcement_event.is_empty() {
3523 assert_eq!(announcement_event.len(), 1);
3524 if let MessageSendEvent::SendAnnouncementSignatures { .. } = announcement_event[0] {
3525 //TODO: Test announcement_sigs re-sending
3526 } else { panic!("Unexpected event!"); }
3529 assert!(chan_msgs.0.is_none());
3532 assert!(chan_msgs.3 == RAACommitmentOrder::RevokeAndACKFirst);
3533 node_b.node.handle_revoke_and_ack(&node_a.node.get_our_node_id(), &chan_msgs.1.unwrap()).unwrap();
3534 assert!(node_b.node.get_and_clear_pending_msg_events().is_empty());
3535 check_added_monitors!(node_b, 1);
3537 assert!(chan_msgs.1.is_none());
3539 if pending_htlc_adds.1 != 0 || pending_htlc_claims.1 != 0 || pending_cell_htlc_claims.1 != 0 || pending_cell_htlc_fails.1 != 0 {
3540 let commitment_update = chan_msgs.2.unwrap();
3541 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
3542 assert_eq!(commitment_update.update_add_htlcs.len(), pending_htlc_adds.1 as usize);
3544 assert_eq!(commitment_update.update_fulfill_htlcs.len(), pending_htlc_claims.0 + pending_cell_htlc_claims.0);
3545 assert_eq!(commitment_update.update_fail_htlcs.len(), pending_cell_htlc_fails.0);
3546 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
3547 for update_add in commitment_update.update_add_htlcs {
3548 node_b.node.handle_update_add_htlc(&node_a.node.get_our_node_id(), &update_add).unwrap();
3550 for update_fulfill in commitment_update.update_fulfill_htlcs {
3551 node_b.node.handle_update_fulfill_htlc(&node_a.node.get_our_node_id(), &update_fulfill).unwrap();
3553 for update_fail in commitment_update.update_fail_htlcs {
3554 node_b.node.handle_update_fail_htlc(&node_a.node.get_our_node_id(), &update_fail).unwrap();
3557 if pending_htlc_adds.1 != -1 { // We use -1 to denote a response commitment_signed
3558 commitment_signed_dance!(node_b, node_a, commitment_update.commitment_signed, false);
3560 node_b.node.handle_commitment_signed(&node_a.node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
3561 check_added_monitors!(node_b, 1);
3562 let bs_revoke_and_ack = get_event_msg!(node_b, MessageSendEvent::SendRevokeAndACK, node_a.node.get_our_node_id());
3563 // No commitment_signed so get_event_msg's assert(len == 1) passes
3564 node_a.node.handle_revoke_and_ack(&node_b.node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
3565 assert!(node_a.node.get_and_clear_pending_msg_events().is_empty());
3566 check_added_monitors!(node_a, 1);
3569 assert!(chan_msgs.2.is_none());
3575 fn test_simple_peer_disconnect() {
3576 // Test that we can reconnect when there are no lost messages
3577 let nodes = create_network(3);
3578 create_announced_chan_between_nodes(&nodes, 0, 1);
3579 create_announced_chan_between_nodes(&nodes, 1, 2);
3581 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3582 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3583 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3585 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3586 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3587 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3588 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3590 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3591 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3592 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3594 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3595 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3596 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3597 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3599 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3600 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3602 claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3);
3603 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
3605 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3607 let events = nodes[0].node.get_and_clear_pending_events();
3608 assert_eq!(events.len(), 2);
3610 Event::PaymentSent { payment_preimage } => {
3611 assert_eq!(payment_preimage, payment_preimage_3);
3613 _ => panic!("Unexpected event"),
3616 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
3617 assert_eq!(payment_hash, payment_hash_5);
3618 assert!(rejected_by_dest);
3620 _ => panic!("Unexpected event"),
3624 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3625 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3628 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
3629 // Test that we can reconnect when in-flight HTLC updates get dropped
3630 let mut nodes = create_network(2);
3631 if messages_delivered == 0 {
3632 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3633 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3635 create_announced_chan_between_nodes(&nodes, 0, 1);
3638 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();
3639 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
3641 let payment_event = {
3642 nodes[0].node.send_payment(route.clone(), payment_hash_1).unwrap();
3643 check_added_monitors!(nodes[0], 1);
3645 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3646 assert_eq!(events.len(), 1);
3647 SendEvent::from_event(events.remove(0))
3649 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3651 if messages_delivered < 2 {
3652 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3654 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
3655 if messages_delivered >= 3 {
3656 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
3657 check_added_monitors!(nodes[1], 1);
3658 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3660 if messages_delivered >= 4 {
3661 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
3662 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3663 check_added_monitors!(nodes[0], 1);
3665 if messages_delivered >= 5 {
3666 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
3667 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3668 // No commitment_signed so get_event_msg's assert(len == 1) passes
3669 check_added_monitors!(nodes[0], 1);
3671 if messages_delivered >= 6 {
3672 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
3673 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3674 check_added_monitors!(nodes[1], 1);
3681 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3682 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3683 if messages_delivered < 3 {
3684 // Even if the funding_locked messages get exchanged, as long as nothing further was
3685 // received on either side, both sides will need to resend them.
3686 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
3687 } else if messages_delivered == 3 {
3688 // nodes[0] still wants its RAA + commitment_signed
3689 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
3690 } else if messages_delivered == 4 {
3691 // nodes[0] still wants its commitment_signed
3692 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3693 } else if messages_delivered == 5 {
3694 // nodes[1] still wants its final RAA
3695 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3696 } else if messages_delivered == 6 {
3697 // Everything was delivered...
3698 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3701 let events_1 = nodes[1].node.get_and_clear_pending_events();
3702 assert_eq!(events_1.len(), 1);
3704 Event::PendingHTLCsForwardable { .. } => { },
3705 _ => panic!("Unexpected event"),
3708 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3709 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3710 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3712 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
3713 nodes[1].node.process_pending_htlc_forwards();
3715 let events_2 = nodes[1].node.get_and_clear_pending_events();
3716 assert_eq!(events_2.len(), 1);
3718 Event::PaymentReceived { ref payment_hash, amt } => {
3719 assert_eq!(payment_hash_1, *payment_hash);
3720 assert_eq!(amt, 1000000);
3722 _ => panic!("Unexpected event"),
3725 nodes[1].node.claim_funds(payment_preimage_1);
3726 check_added_monitors!(nodes[1], 1);
3728 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3729 assert_eq!(events_3.len(), 1);
3730 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3731 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3732 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3733 assert!(updates.update_add_htlcs.is_empty());
3734 assert!(updates.update_fail_htlcs.is_empty());
3735 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3736 assert!(updates.update_fail_malformed_htlcs.is_empty());
3737 assert!(updates.update_fee.is_none());
3738 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3740 _ => panic!("Unexpected event"),
3743 if messages_delivered >= 1 {
3744 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc).unwrap();
3746 let events_4 = nodes[0].node.get_and_clear_pending_events();
3747 assert_eq!(events_4.len(), 1);
3749 Event::PaymentSent { ref payment_preimage } => {
3750 assert_eq!(payment_preimage_1, *payment_preimage);
3752 _ => panic!("Unexpected event"),
3755 if messages_delivered >= 2 {
3756 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
3757 check_added_monitors!(nodes[0], 1);
3758 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3760 if messages_delivered >= 3 {
3761 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
3762 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3763 check_added_monitors!(nodes[1], 1);
3765 if messages_delivered >= 4 {
3766 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed).unwrap();
3767 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3768 // No commitment_signed so get_event_msg's assert(len == 1) passes
3769 check_added_monitors!(nodes[1], 1);
3771 if messages_delivered >= 5 {
3772 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
3773 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3774 check_added_monitors!(nodes[0], 1);
3781 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3782 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3783 if messages_delivered < 2 {
3784 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
3785 //TODO: Deduplicate PaymentSent events, then enable this if:
3786 //if messages_delivered < 1 {
3787 let events_4 = nodes[0].node.get_and_clear_pending_events();
3788 assert_eq!(events_4.len(), 1);
3790 Event::PaymentSent { ref payment_preimage } => {
3791 assert_eq!(payment_preimage_1, *payment_preimage);
3793 _ => panic!("Unexpected event"),
3796 } else if messages_delivered == 2 {
3797 // nodes[0] still wants its RAA + commitment_signed
3798 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
3799 } else if messages_delivered == 3 {
3800 // nodes[0] still wants its commitment_signed
3801 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
3802 } else if messages_delivered == 4 {
3803 // nodes[1] still wants its final RAA
3804 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3805 } else if messages_delivered == 5 {
3806 // Everything was delivered...
3807 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3810 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3811 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3812 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3814 // Channel should still work fine...
3815 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3816 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3820 fn test_drop_messages_peer_disconnect_a() {
3821 do_test_drop_messages_peer_disconnect(0);
3822 do_test_drop_messages_peer_disconnect(1);
3823 do_test_drop_messages_peer_disconnect(2);
3824 do_test_drop_messages_peer_disconnect(3);
3828 fn test_drop_messages_peer_disconnect_b() {
3829 do_test_drop_messages_peer_disconnect(4);
3830 do_test_drop_messages_peer_disconnect(5);
3831 do_test_drop_messages_peer_disconnect(6);
3835 fn test_funding_peer_disconnect() {
3836 // Test that we can lock in our funding tx while disconnected
3837 let nodes = create_network(2);
3838 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001);
3840 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3841 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3843 confirm_transaction(&nodes[0].chain_monitor, &tx, tx.version);
3844 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3845 assert_eq!(events_1.len(), 1);
3847 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3848 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3850 _ => panic!("Unexpected event"),
3853 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3855 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3856 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3858 confirm_transaction(&nodes[1].chain_monitor, &tx, tx.version);
3859 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3860 assert_eq!(events_2.len(), 2);
3862 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3863 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3865 _ => panic!("Unexpected event"),
3868 MessageSendEvent::SendAnnouncementSignatures { ref node_id, msg: _ } => {
3869 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3871 _ => panic!("Unexpected event"),
3874 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3876 // TODO: We shouldn't need to manually pass list_usable_chanels here once we support
3877 // rebroadcasting announcement_signatures upon reconnect.
3879 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();
3880 let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3881 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
3885 fn test_drop_messages_peer_disconnect_dual_htlc() {
3886 // Test that we can handle reconnecting when both sides of a channel have pending
3887 // commitment_updates when we disconnect.
3888 let mut nodes = create_network(2);
3889 create_announced_chan_between_nodes(&nodes, 0, 1);
3891 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3893 // Now try to send a second payment which will fail to send
3894 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
3895 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
3897 nodes[0].node.send_payment(route.clone(), payment_hash_2).unwrap();
3898 check_added_monitors!(nodes[0], 1);
3900 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3901 assert_eq!(events_1.len(), 1);
3903 MessageSendEvent::UpdateHTLCs { .. } => {},
3904 _ => panic!("Unexpected event"),
3907 assert!(nodes[1].node.claim_funds(payment_preimage_1));
3908 check_added_monitors!(nodes[1], 1);
3910 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3911 assert_eq!(events_2.len(), 1);
3913 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 } } => {
3914 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3915 assert!(update_add_htlcs.is_empty());
3916 assert_eq!(update_fulfill_htlcs.len(), 1);
3917 assert!(update_fail_htlcs.is_empty());
3918 assert!(update_fail_malformed_htlcs.is_empty());
3919 assert!(update_fee.is_none());
3921 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
3922 let events_3 = nodes[0].node.get_and_clear_pending_events();
3923 assert_eq!(events_3.len(), 1);
3925 Event::PaymentSent { ref payment_preimage } => {
3926 assert_eq!(*payment_preimage, payment_preimage_1);
3928 _ => panic!("Unexpected event"),
3931 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
3932 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3933 // No commitment_signed so get_event_msg's assert(len == 1) passes
3934 check_added_monitors!(nodes[0], 1);
3936 _ => panic!("Unexpected event"),
3939 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3940 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3942 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
3943 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3944 assert_eq!(reestablish_1.len(), 1);
3945 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
3946 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3947 assert_eq!(reestablish_2.len(), 1);
3949 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
3950 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3951 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
3952 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3954 assert!(as_resp.0.is_none());
3955 assert!(bs_resp.0.is_none());
3957 assert!(bs_resp.1.is_none());
3958 assert!(bs_resp.2.is_none());
3960 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3962 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3963 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3964 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3965 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3966 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3967 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();
3968 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed).unwrap();
3969 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3970 // No commitment_signed so get_event_msg's assert(len == 1) passes
3971 check_added_monitors!(nodes[1], 1);
3973 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap()).unwrap();
3974 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3975 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3976 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3977 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3978 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3979 assert!(bs_second_commitment_signed.update_fee.is_none());
3980 check_added_monitors!(nodes[1], 1);
3982 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
3983 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3984 assert!(as_commitment_signed.update_add_htlcs.is_empty());
3985 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
3986 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
3987 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
3988 assert!(as_commitment_signed.update_fee.is_none());
3989 check_added_monitors!(nodes[0], 1);
3991 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed).unwrap();
3992 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3993 // No commitment_signed so get_event_msg's assert(len == 1) passes
3994 check_added_monitors!(nodes[0], 1);
3996 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed).unwrap();
3997 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3998 // No commitment_signed so get_event_msg's assert(len == 1) passes
3999 check_added_monitors!(nodes[1], 1);
4001 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
4002 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4003 check_added_monitors!(nodes[1], 1);
4005 expect_pending_htlcs_forwardable!(nodes[1]);
4007 let events_5 = nodes[1].node.get_and_clear_pending_events();
4008 assert_eq!(events_5.len(), 1);
4010 Event::PaymentReceived { ref payment_hash, amt: _ } => {
4011 assert_eq!(payment_hash_2, *payment_hash);
4013 _ => panic!("Unexpected event"),
4016 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap();
4017 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4018 check_added_monitors!(nodes[0], 1);
4020 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4024 fn test_simple_monitor_permanent_update_fail() {
4025 // Test that we handle a simple permanent monitor update failure
4026 let mut nodes = create_network(2);
4027 create_announced_chan_between_nodes(&nodes, 0, 1);
4029 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
4030 let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
4032 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::PermanentFailure);
4033 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route, payment_hash_1) {} else { panic!(); }
4034 check_added_monitors!(nodes[0], 1);
4036 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4037 assert_eq!(events_1.len(), 2);
4039 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4040 _ => panic!("Unexpected event"),
4043 MessageSendEvent::HandleError { node_id, .. } => assert_eq!(node_id, nodes[1].node.get_our_node_id()),
4044 _ => panic!("Unexpected event"),
4047 // TODO: Once we hit the chain with the failure transaction we should check that we get a
4048 // PaymentFailed event
4050 assert_eq!(nodes[0].node.list_channels().len(), 0);
4053 fn do_test_simple_monitor_temporary_update_fail(disconnect: bool) {
4054 // Test that we can recover from a simple temporary monitor update failure optionally with
4055 // a disconnect in between
4056 let mut nodes = create_network(2);
4057 create_announced_chan_between_nodes(&nodes, 0, 1);
4059 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
4060 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
4062 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
4063 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route.clone(), payment_hash_1) {} else { panic!(); }
4064 check_added_monitors!(nodes[0], 1);
4066 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4067 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4068 assert_eq!(nodes[0].node.list_channels().len(), 1);
4071 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4072 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4073 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4076 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
4077 nodes[0].node.test_restore_channel_monitor();
4078 check_added_monitors!(nodes[0], 1);
4080 let mut events_2 = nodes[0].node.get_and_clear_pending_msg_events();
4081 assert_eq!(events_2.len(), 1);
4082 let payment_event = SendEvent::from_event(events_2.pop().unwrap());
4083 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
4084 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4085 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4087 expect_pending_htlcs_forwardable!(nodes[1]);
4089 let events_3 = nodes[1].node.get_and_clear_pending_events();
4090 assert_eq!(events_3.len(), 1);
4092 Event::PaymentReceived { ref payment_hash, amt } => {
4093 assert_eq!(payment_hash_1, *payment_hash);
4094 assert_eq!(amt, 1000000);
4096 _ => panic!("Unexpected event"),
4099 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_1);
4101 // Now set it to failed again...
4102 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
4103 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
4104 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route, payment_hash_2) {} else { panic!(); }
4105 check_added_monitors!(nodes[0], 1);
4107 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4108 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4109 assert_eq!(nodes[0].node.list_channels().len(), 1);
4112 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4113 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4114 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4117 // ...and make sure we can force-close a TemporaryFailure channel with a PermanentFailure
4118 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::PermanentFailure);
4119 nodes[0].node.test_restore_channel_monitor();
4120 check_added_monitors!(nodes[0], 1);
4121 check_closed_broadcast!(nodes[0]);
4123 // TODO: Once we hit the chain with the failure transaction we should check that we get a
4124 // PaymentFailed event
4126 assert_eq!(nodes[0].node.list_channels().len(), 0);
4130 fn test_simple_monitor_temporary_update_fail() {
4131 do_test_simple_monitor_temporary_update_fail(false);
4132 do_test_simple_monitor_temporary_update_fail(true);
4135 fn do_test_monitor_temporary_update_fail(disconnect_count: usize) {
4136 let disconnect_flags = 8 | 16;
4138 // Test that we can recover from a temporary monitor update failure with some in-flight
4139 // HTLCs going on at the same time potentially with some disconnection thrown in.
4140 // * First we route a payment, then get a temporary monitor update failure when trying to
4141 // route a second payment. We then claim the first payment.
4142 // * If disconnect_count is set, we will disconnect at this point (which is likely as
4143 // TemporaryFailure likely indicates net disconnect which resulted in failing to update
4144 // the ChannelMonitor on a watchtower).
4145 // * If !(disconnect_count & 16) we deliver a update_fulfill_htlc/CS for the first payment
4146 // immediately, otherwise we wait sconnect and deliver them via the reconnect
4147 // channel_reestablish processing (ie disconnect_count & 16 makes no sense if
4148 // disconnect_count & !disconnect_flags is 0).
4149 // * We then update the channel monitor, reconnecting if disconnect_count is set and walk
4150 // through message sending, potentially disconnect/reconnecting multiple times based on
4151 // disconnect_count, to get the update_fulfill_htlc through.
4152 // * We then walk through more message exchanges to get the original update_add_htlc
4153 // through, swapping message ordering based on disconnect_count & 8 and optionally
4154 // disconnect/reconnecting based on disconnect_count.
4155 let mut nodes = create_network(2);
4156 create_announced_chan_between_nodes(&nodes, 0, 1);
4158 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4160 // Now try to send a second payment which will fail to send
4161 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
4162 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
4164 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
4165 if let Err(APIError::MonitorUpdateFailed) = nodes[0].node.send_payment(route.clone(), payment_hash_2) {} else { panic!(); }
4166 check_added_monitors!(nodes[0], 1);
4168 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4169 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4170 assert_eq!(nodes[0].node.list_channels().len(), 1);
4172 // Claim the previous payment, which will result in a update_fulfill_htlc/CS from nodes[1]
4173 // but nodes[0] won't respond since it is frozen.
4174 assert!(nodes[1].node.claim_funds(payment_preimage_1));
4175 check_added_monitors!(nodes[1], 1);
4176 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4177 assert_eq!(events_2.len(), 1);
4178 let (bs_initial_fulfill, bs_initial_commitment_signed) = match events_2[0] {
4179 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 } } => {
4180 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4181 assert!(update_add_htlcs.is_empty());
4182 assert_eq!(update_fulfill_htlcs.len(), 1);
4183 assert!(update_fail_htlcs.is_empty());
4184 assert!(update_fail_malformed_htlcs.is_empty());
4185 assert!(update_fee.is_none());
4187 if (disconnect_count & 16) == 0 {
4188 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
4189 let events_3 = nodes[0].node.get_and_clear_pending_events();
4190 assert_eq!(events_3.len(), 1);
4192 Event::PaymentSent { ref payment_preimage } => {
4193 assert_eq!(*payment_preimage, payment_preimage_1);
4195 _ => panic!("Unexpected event"),
4198 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) {
4199 assert_eq!(err, "Previous monitor update failure prevented generation of RAA");
4200 } else { panic!(); }
4203 (update_fulfill_htlcs[0].clone(), commitment_signed.clone())
4205 _ => panic!("Unexpected event"),
4208 if disconnect_count & !disconnect_flags > 0 {
4209 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4210 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4213 // Now fix monitor updating...
4214 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
4215 nodes[0].node.test_restore_channel_monitor();
4216 check_added_monitors!(nodes[0], 1);
4218 macro_rules! disconnect_reconnect_peers { () => { {
4219 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4220 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4222 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
4223 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4224 assert_eq!(reestablish_1.len(), 1);
4225 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
4226 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4227 assert_eq!(reestablish_2.len(), 1);
4229 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
4230 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4231 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
4232 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4234 assert!(as_resp.0.is_none());
4235 assert!(bs_resp.0.is_none());
4237 (reestablish_1, reestablish_2, as_resp, bs_resp)
4240 let (payment_event, initial_revoke_and_ack) = if disconnect_count & !disconnect_flags > 0 {
4241 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4242 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4244 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
4245 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4246 assert_eq!(reestablish_1.len(), 1);
4247 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
4248 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4249 assert_eq!(reestablish_2.len(), 1);
4251 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
4252 check_added_monitors!(nodes[0], 0);
4253 let mut as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4254 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
4255 check_added_monitors!(nodes[1], 0);
4256 let mut bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4258 assert!(as_resp.0.is_none());
4259 assert!(bs_resp.0.is_none());
4261 assert!(bs_resp.1.is_none());
4262 if (disconnect_count & 16) == 0 {
4263 assert!(bs_resp.2.is_none());
4265 assert!(as_resp.1.is_some());
4266 assert!(as_resp.2.is_some());
4267 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4269 assert!(bs_resp.2.as_ref().unwrap().update_add_htlcs.is_empty());
4270 assert!(bs_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4271 assert!(bs_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4272 assert!(bs_resp.2.as_ref().unwrap().update_fee.is_none());
4273 assert!(bs_resp.2.as_ref().unwrap().update_fulfill_htlcs == vec![bs_initial_fulfill]);
4274 assert!(bs_resp.2.as_ref().unwrap().commitment_signed == bs_initial_commitment_signed);
4276 assert!(as_resp.1.is_none());
4278 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();
4279 let events_3 = nodes[0].node.get_and_clear_pending_events();
4280 assert_eq!(events_3.len(), 1);
4282 Event::PaymentSent { ref payment_preimage } => {
4283 assert_eq!(*payment_preimage, payment_preimage_1);
4285 _ => panic!("Unexpected event"),
4288 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_resp.2.as_ref().unwrap().commitment_signed).unwrap();
4289 let as_resp_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4290 // No commitment_signed so get_event_msg's assert(len == 1) passes
4291 check_added_monitors!(nodes[0], 1);
4293 as_resp.1 = Some(as_resp_raa);
4297 if disconnect_count & !disconnect_flags > 1 {
4298 let (second_reestablish_1, second_reestablish_2, second_as_resp, second_bs_resp) = disconnect_reconnect_peers!();
4300 if (disconnect_count & 16) == 0 {
4301 assert!(reestablish_1 == second_reestablish_1);
4302 assert!(reestablish_2 == second_reestablish_2);
4304 assert!(as_resp == second_as_resp);
4305 assert!(bs_resp == second_bs_resp);
4308 (SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), as_resp.2.unwrap()), as_resp.1.unwrap())
4310 let mut events_4 = nodes[0].node.get_and_clear_pending_msg_events();
4311 assert_eq!(events_4.len(), 2);
4312 (SendEvent::from_event(events_4.remove(0)), match events_4[0] {
4313 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
4314 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
4317 _ => panic!("Unexpected event"),
4321 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
4323 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4324 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
4325 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4326 // nodes[1] is awaiting an RAA from nodes[0] still so get_event_msg's assert(len == 1) passes
4327 check_added_monitors!(nodes[1], 1);
4329 if disconnect_count & !disconnect_flags > 2 {
4330 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
4332 assert!(as_resp.1.unwrap() == initial_revoke_and_ack);
4333 assert!(bs_resp.1.unwrap() == bs_revoke_and_ack);
4335 assert!(as_resp.2.is_none());
4336 assert!(bs_resp.2.is_none());
4339 let as_commitment_update;
4340 let bs_second_commitment_update;
4342 macro_rules! handle_bs_raa { () => {
4343 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
4344 as_commitment_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4345 assert!(as_commitment_update.update_add_htlcs.is_empty());
4346 assert!(as_commitment_update.update_fulfill_htlcs.is_empty());
4347 assert!(as_commitment_update.update_fail_htlcs.is_empty());
4348 assert!(as_commitment_update.update_fail_malformed_htlcs.is_empty());
4349 assert!(as_commitment_update.update_fee.is_none());
4350 check_added_monitors!(nodes[0], 1);
4353 macro_rules! handle_initial_raa { () => {
4354 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &initial_revoke_and_ack).unwrap();
4355 bs_second_commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4356 assert!(bs_second_commitment_update.update_add_htlcs.is_empty());
4357 assert!(bs_second_commitment_update.update_fulfill_htlcs.is_empty());
4358 assert!(bs_second_commitment_update.update_fail_htlcs.is_empty());
4359 assert!(bs_second_commitment_update.update_fail_malformed_htlcs.is_empty());
4360 assert!(bs_second_commitment_update.update_fee.is_none());
4361 check_added_monitors!(nodes[1], 1);
4364 if (disconnect_count & 8) == 0 {
4367 if disconnect_count & !disconnect_flags > 3 {
4368 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
4370 assert!(as_resp.1.unwrap() == initial_revoke_and_ack);
4371 assert!(bs_resp.1.is_none());
4373 assert!(as_resp.2.unwrap() == as_commitment_update);
4374 assert!(bs_resp.2.is_none());
4376 assert!(as_resp.3 == RAACommitmentOrder::RevokeAndACKFirst);
4379 handle_initial_raa!();
4381 if disconnect_count & !disconnect_flags > 4 {
4382 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
4384 assert!(as_resp.1.is_none());
4385 assert!(bs_resp.1.is_none());
4387 assert!(as_resp.2.unwrap() == as_commitment_update);
4388 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
4391 handle_initial_raa!();
4393 if disconnect_count & !disconnect_flags > 3 {
4394 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
4396 assert!(as_resp.1.is_none());
4397 assert!(bs_resp.1.unwrap() == bs_revoke_and_ack);
4399 assert!(as_resp.2.is_none());
4400 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
4402 assert!(bs_resp.3 == RAACommitmentOrder::RevokeAndACKFirst);
4407 if disconnect_count & !disconnect_flags > 4 {
4408 let (_, _, as_resp, bs_resp) = disconnect_reconnect_peers!();
4410 assert!(as_resp.1.is_none());
4411 assert!(bs_resp.1.is_none());
4413 assert!(as_resp.2.unwrap() == as_commitment_update);
4414 assert!(bs_resp.2.unwrap() == bs_second_commitment_update);
4418 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_update.commitment_signed).unwrap();
4419 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4420 // No commitment_signed so get_event_msg's assert(len == 1) passes
4421 check_added_monitors!(nodes[0], 1);
4423 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_update.commitment_signed).unwrap();
4424 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4425 // No commitment_signed so get_event_msg's assert(len == 1) passes
4426 check_added_monitors!(nodes[1], 1);
4428 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
4429 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4430 check_added_monitors!(nodes[1], 1);
4432 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap();
4433 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4434 check_added_monitors!(nodes[0], 1);
4436 expect_pending_htlcs_forwardable!(nodes[1]);
4438 let events_5 = nodes[1].node.get_and_clear_pending_events();
4439 assert_eq!(events_5.len(), 1);
4441 Event::PaymentReceived { ref payment_hash, amt } => {
4442 assert_eq!(payment_hash_2, *payment_hash);
4443 assert_eq!(amt, 1000000);
4445 _ => panic!("Unexpected event"),
4448 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4452 fn test_monitor_temporary_update_fail_a() {
4453 do_test_monitor_temporary_update_fail(0);
4454 do_test_monitor_temporary_update_fail(1);
4455 do_test_monitor_temporary_update_fail(2);
4456 do_test_monitor_temporary_update_fail(3);
4457 do_test_monitor_temporary_update_fail(4);
4458 do_test_monitor_temporary_update_fail(5);
4462 fn test_monitor_temporary_update_fail_b() {
4463 do_test_monitor_temporary_update_fail(2 | 8);
4464 do_test_monitor_temporary_update_fail(3 | 8);
4465 do_test_monitor_temporary_update_fail(4 | 8);
4466 do_test_monitor_temporary_update_fail(5 | 8);
4470 fn test_monitor_temporary_update_fail_c() {
4471 do_test_monitor_temporary_update_fail(1 | 16);
4472 do_test_monitor_temporary_update_fail(2 | 16);
4473 do_test_monitor_temporary_update_fail(3 | 16);
4474 do_test_monitor_temporary_update_fail(2 | 8 | 16);
4475 do_test_monitor_temporary_update_fail(3 | 8 | 16);
4479 fn test_monitor_update_fail_cs() {
4480 // Tests handling of a monitor update failure when processing an incoming commitment_signed
4481 let mut nodes = create_network(2);
4482 create_announced_chan_between_nodes(&nodes, 0, 1);
4484 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
4485 let (payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4486 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
4487 check_added_monitors!(nodes[0], 1);
4489 let send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4490 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
4492 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
4493 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() {
4494 assert_eq!(err, "Failed to update ChannelMonitor");
4495 } else { panic!(); }
4496 check_added_monitors!(nodes[1], 1);
4497 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4499 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
4500 nodes[1].node.test_restore_channel_monitor();
4501 check_added_monitors!(nodes[1], 1);
4502 let responses = nodes[1].node.get_and_clear_pending_msg_events();
4503 assert_eq!(responses.len(), 2);
4505 match responses[0] {
4506 MessageSendEvent::SendRevokeAndACK { ref msg, ref node_id } => {
4507 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4508 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &msg).unwrap();
4509 check_added_monitors!(nodes[0], 1);
4511 _ => panic!("Unexpected event"),
4513 match responses[1] {
4514 MessageSendEvent::UpdateHTLCs { ref updates, ref node_id } => {
4515 assert!(updates.update_add_htlcs.is_empty());
4516 assert!(updates.update_fulfill_htlcs.is_empty());
4517 assert!(updates.update_fail_htlcs.is_empty());
4518 assert!(updates.update_fail_malformed_htlcs.is_empty());
4519 assert!(updates.update_fee.is_none());
4520 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4522 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
4523 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() {
4524 assert_eq!(err, "Failed to update ChannelMonitor");
4525 } else { panic!(); }
4526 check_added_monitors!(nodes[0], 1);
4527 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4529 _ => panic!("Unexpected event"),
4532 *nodes[0].chan_monitor.update_ret.lock().unwrap() = Ok(());
4533 nodes[0].node.test_restore_channel_monitor();
4534 check_added_monitors!(nodes[0], 1);
4536 let final_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4537 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &final_raa).unwrap();
4538 check_added_monitors!(nodes[1], 1);
4540 expect_pending_htlcs_forwardable!(nodes[1]);
4542 let events = nodes[1].node.get_and_clear_pending_events();
4543 assert_eq!(events.len(), 1);
4545 Event::PaymentReceived { payment_hash, amt } => {
4546 assert_eq!(payment_hash, our_payment_hash);
4547 assert_eq!(amt, 1000000);
4549 _ => panic!("Unexpected event"),
4552 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
4555 fn do_test_monitor_update_fail_raa(test_ignore_second_cs: bool) {
4556 // Tests handling of a monitor update failure when processing an incoming RAA
4557 let mut nodes = create_network(3);
4558 create_announced_chan_between_nodes(&nodes, 0, 1);
4559 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4561 // Rebalance a bit so that we can send backwards from 2 to 1.
4562 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 5000000);
4564 // Route a first payment that we'll fail backwards
4565 let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
4567 // Fail the payment backwards, failing the monitor update on nodes[1]'s receipt of the RAA
4568 assert!(nodes[2].node.fail_htlc_backwards(&payment_hash_1, 0));
4569 expect_pending_htlcs_forwardable!(nodes[2]);
4570 check_added_monitors!(nodes[2], 1);
4572 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4573 assert!(updates.update_add_htlcs.is_empty());
4574 assert!(updates.update_fulfill_htlcs.is_empty());
4575 assert_eq!(updates.update_fail_htlcs.len(), 1);
4576 assert!(updates.update_fail_malformed_htlcs.is_empty());
4577 assert!(updates.update_fee.is_none());
4578 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
4580 let bs_revoke_and_ack = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
4581 check_added_monitors!(nodes[0], 0);
4583 // While the second channel is AwaitingRAA, forward a second payment to get it into the
4585 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
4586 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
4587 nodes[0].node.send_payment(route, payment_hash_2).unwrap();
4588 check_added_monitors!(nodes[0], 1);
4590 let mut send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4591 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
4592 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false);
4594 expect_pending_htlcs_forwardable!(nodes[1]);
4595 check_added_monitors!(nodes[1], 0);
4596 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4598 // Now fail monitor updating.
4599 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
4600 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() {
4601 assert_eq!(err, "Failed to update ChannelMonitor");
4602 } else { panic!(); }
4603 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4604 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4605 check_added_monitors!(nodes[1], 1);
4607 // Attempt to forward a third payment but fail due to the second channel being unavailable
4610 let (_, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
4611 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
4612 nodes[0].node.send_payment(route, payment_hash_3).unwrap();
4613 check_added_monitors!(nodes[0], 1);
4615 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(()); // We succeed in updating the monitor for the first channel
4616 send_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4617 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
4618 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false, true);
4619 check_added_monitors!(nodes[1], 0);
4621 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4622 assert_eq!(events_2.len(), 1);
4623 match events_2.remove(0) {
4624 MessageSendEvent::UpdateHTLCs { node_id, updates } => {
4625 assert_eq!(node_id, nodes[0].node.get_our_node_id());
4626 assert!(updates.update_fulfill_htlcs.is_empty());
4627 assert_eq!(updates.update_fail_htlcs.len(), 1);
4628 assert!(updates.update_fail_malformed_htlcs.is_empty());
4629 assert!(updates.update_add_htlcs.is_empty());
4630 assert!(updates.update_fee.is_none());
4632 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
4633 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
4635 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4636 assert_eq!(msg_events.len(), 1);
4637 match msg_events[0] {
4638 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
4639 assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
4640 assert_eq!(msg.contents.flags & 2, 2); // temp disabled
4642 _ => panic!("Unexpected event"),
4645 let events = nodes[0].node.get_and_clear_pending_events();
4646 assert_eq!(events.len(), 1);
4647 if let Event::PaymentFailed { payment_hash, rejected_by_dest, .. } = events[0] {
4648 assert_eq!(payment_hash, payment_hash_3);
4649 assert!(!rejected_by_dest);
4650 } else { panic!("Unexpected event!"); }
4652 _ => panic!("Unexpected event type!"),
4655 let (payment_preimage_4, payment_hash_4) = if test_ignore_second_cs {
4656 // Try to route another payment backwards from 2 to make sure 1 holds off on responding
4657 let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[0]);
4658 let route = nodes[2].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
4659 nodes[2].node.send_payment(route, payment_hash_4).unwrap();
4660 check_added_monitors!(nodes[2], 1);
4662 send_event = SendEvent::from_event(nodes[2].node.get_and_clear_pending_msg_events().remove(0));
4663 nodes[1].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
4664 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) {
4665 assert_eq!(err, "Previous monitor update failure prevented generation of RAA");
4666 } else { panic!(); }
4667 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4668 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4669 (Some(payment_preimage_4), Some(payment_hash_4))
4670 } else { (None, None) };
4672 // Restore monitor updating, ensuring we immediately get a fail-back update and a
4673 // update_add update.
4674 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
4675 nodes[1].node.test_restore_channel_monitor();
4676 check_added_monitors!(nodes[1], 1);
4677 expect_pending_htlcs_forwardable!(nodes[1]);
4678 check_added_monitors!(nodes[1], 1);
4680 let mut events_3 = nodes[1].node.get_and_clear_pending_msg_events();
4681 if test_ignore_second_cs {
4682 assert_eq!(events_3.len(), 3);
4684 assert_eq!(events_3.len(), 2);
4687 // Note that the ordering of the events for different nodes is non-prescriptive, though the
4688 // ordering of the two events that both go to nodes[2] have to stay in the same order.
4689 let messages_a = match events_3.pop().unwrap() {
4690 MessageSendEvent::UpdateHTLCs { node_id, mut updates } => {
4691 assert_eq!(node_id, nodes[0].node.get_our_node_id());
4692 assert!(updates.update_fulfill_htlcs.is_empty());
4693 assert_eq!(updates.update_fail_htlcs.len(), 1);
4694 assert!(updates.update_fail_malformed_htlcs.is_empty());
4695 assert!(updates.update_add_htlcs.is_empty());
4696 assert!(updates.update_fee.is_none());
4697 (updates.update_fail_htlcs.remove(0), updates.commitment_signed)
4699 _ => panic!("Unexpected event type!"),
4701 let raa = if test_ignore_second_cs {
4702 match events_3.remove(1) {
4703 MessageSendEvent::SendRevokeAndACK { node_id, msg } => {
4704 assert_eq!(node_id, nodes[2].node.get_our_node_id());
4707 _ => panic!("Unexpected event"),
4710 let send_event_b = SendEvent::from_event(events_3.remove(0));
4711 assert_eq!(send_event_b.node_id, nodes[2].node.get_our_node_id());
4713 // Now deliver the new messages...
4715 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &messages_a.0).unwrap();
4716 commitment_signed_dance!(nodes[0], nodes[1], messages_a.1, false);
4717 let events_4 = nodes[0].node.get_and_clear_pending_events();
4718 assert_eq!(events_4.len(), 1);
4719 if let Event::PaymentFailed { payment_hash, rejected_by_dest, .. } = events_4[0] {
4720 assert_eq!(payment_hash, payment_hash_1);
4721 assert!(rejected_by_dest);
4722 } else { panic!("Unexpected event!"); }
4724 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event_b.msgs[0]).unwrap();
4725 if test_ignore_second_cs {
4726 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_event_b.commitment_msg).unwrap();
4727 check_added_monitors!(nodes[2], 1);
4728 let bs_revoke_and_ack = get_event_msg!(nodes[2], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4729 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa.unwrap()).unwrap();
4730 check_added_monitors!(nodes[2], 1);
4731 let bs_cs = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4732 assert!(bs_cs.update_add_htlcs.is_empty());
4733 assert!(bs_cs.update_fail_htlcs.is_empty());
4734 assert!(bs_cs.update_fail_malformed_htlcs.is_empty());
4735 assert!(bs_cs.update_fulfill_htlcs.is_empty());
4736 assert!(bs_cs.update_fee.is_none());
4738 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
4739 check_added_monitors!(nodes[1], 1);
4740 let as_cs = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
4741 assert!(as_cs.update_add_htlcs.is_empty());
4742 assert!(as_cs.update_fail_htlcs.is_empty());
4743 assert!(as_cs.update_fail_malformed_htlcs.is_empty());
4744 assert!(as_cs.update_fulfill_htlcs.is_empty());
4745 assert!(as_cs.update_fee.is_none());
4747 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_cs.commitment_signed).unwrap();
4748 check_added_monitors!(nodes[1], 1);
4749 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
4751 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_cs.commitment_signed).unwrap();
4752 check_added_monitors!(nodes[2], 1);
4753 let bs_second_raa = get_event_msg!(nodes[2], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4755 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
4756 check_added_monitors!(nodes[2], 1);
4757 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
4759 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_second_raa).unwrap();
4760 check_added_monitors!(nodes[1], 1);
4761 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4763 commitment_signed_dance!(nodes[2], nodes[1], send_event_b.commitment_msg, false);
4766 expect_pending_htlcs_forwardable!(nodes[2]);
4768 let events_6 = nodes[2].node.get_and_clear_pending_events();
4769 assert_eq!(events_6.len(), 1);
4771 Event::PaymentReceived { payment_hash, .. } => { assert_eq!(payment_hash, payment_hash_2); },
4772 _ => panic!("Unexpected event"),
4775 if test_ignore_second_cs {
4776 expect_pending_htlcs_forwardable!(nodes[1]);
4777 check_added_monitors!(nodes[1], 1);
4779 send_event = SendEvent::from_node(&nodes[1]);
4780 assert_eq!(send_event.node_id, nodes[0].node.get_our_node_id());
4781 assert_eq!(send_event.msgs.len(), 1);
4782 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event.msgs[0]).unwrap();
4783 commitment_signed_dance!(nodes[0], nodes[1], send_event.commitment_msg, false);
4785 expect_pending_htlcs_forwardable!(nodes[0]);
4787 let events_9 = nodes[0].node.get_and_clear_pending_events();
4788 assert_eq!(events_9.len(), 1);
4790 Event::PaymentReceived { payment_hash, .. } => assert_eq!(payment_hash, payment_hash_4.unwrap()),
4791 _ => panic!("Unexpected event"),
4793 claim_payment(&nodes[2], &[&nodes[1], &nodes[0]], payment_preimage_4.unwrap());
4796 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
4800 fn test_monitor_update_fail_raa() {
4801 do_test_monitor_update_fail_raa(false);
4802 do_test_monitor_update_fail_raa(true);
4806 fn test_monitor_update_fail_reestablish() {
4807 // Simple test for message retransmission after monitor update failure on
4808 // channel_reestablish generating a monitor update (which comes from freeing holding cell
4810 let mut nodes = create_network(3);
4811 create_announced_chan_between_nodes(&nodes, 0, 1);
4812 create_announced_chan_between_nodes(&nodes, 1, 2);
4814 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
4816 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4817 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4819 assert!(nodes[2].node.claim_funds(our_payment_preimage));
4820 check_added_monitors!(nodes[2], 1);
4821 let mut updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4822 assert!(updates.update_add_htlcs.is_empty());
4823 assert!(updates.update_fail_htlcs.is_empty());
4824 assert!(updates.update_fail_malformed_htlcs.is_empty());
4825 assert!(updates.update_fee.is_none());
4826 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4827 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
4828 check_added_monitors!(nodes[1], 1);
4829 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4830 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
4832 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Err(ChannelMonitorUpdateErr::TemporaryFailure);
4833 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
4834 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
4836 let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
4837 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4839 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish).unwrap();
4841 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() {
4842 assert_eq!(err, "Failed to update ChannelMonitor");
4843 } else { panic!(); }
4844 check_added_monitors!(nodes[1], 1);
4846 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4847 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4849 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
4850 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
4852 assert!(as_reestablish == get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id()));
4853 assert!(bs_reestablish == get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id()));
4855 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish).unwrap();
4857 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish).unwrap();
4858 check_added_monitors!(nodes[1], 0);
4859 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4861 *nodes[1].chan_monitor.update_ret.lock().unwrap() = Ok(());
4862 nodes[1].node.test_restore_channel_monitor();
4863 check_added_monitors!(nodes[1], 1);
4865 updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4866 assert!(updates.update_add_htlcs.is_empty());
4867 assert!(updates.update_fail_htlcs.is_empty());
4868 assert!(updates.update_fail_malformed_htlcs.is_empty());
4869 assert!(updates.update_fee.is_none());
4870 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4871 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
4872 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
4874 let events = nodes[0].node.get_and_clear_pending_events();
4875 assert_eq!(events.len(), 1);
4877 Event::PaymentSent { payment_preimage, .. } => assert_eq!(payment_preimage, our_payment_preimage),
4878 _ => panic!("Unexpected event"),
4883 fn test_invalid_channel_announcement() {
4884 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
4885 let secp_ctx = Secp256k1::new();
4886 let nodes = create_network(2);
4888 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1]);
4890 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
4891 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
4892 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4893 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4895 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 } );
4897 let as_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &as_chan.get_local_keys().funding_key);
4898 let bs_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &bs_chan.get_local_keys().funding_key);
4900 let as_network_key = nodes[0].node.get_our_node_id();
4901 let bs_network_key = nodes[1].node.get_our_node_id();
4903 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
4905 let mut chan_announcement;
4907 macro_rules! dummy_unsigned_msg {
4909 msgs::UnsignedChannelAnnouncement {
4910 features: msgs::GlobalFeatures::new(),
4911 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
4912 short_channel_id: as_chan.get_short_channel_id().unwrap(),
4913 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
4914 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
4915 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
4916 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
4917 excess_data: Vec::new(),
4922 macro_rules! sign_msg {
4923 ($unsigned_msg: expr) => {
4924 let msghash = Message::from_slice(&Sha256dHash::from_data(&$unsigned_msg.encode()[..])[..]).unwrap();
4925 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_local_keys().funding_key);
4926 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_local_keys().funding_key);
4927 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
4928 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
4929 chan_announcement = msgs::ChannelAnnouncement {
4930 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
4931 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
4932 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
4933 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
4934 contents: $unsigned_msg
4939 let unsigned_msg = dummy_unsigned_msg!();
4940 sign_msg!(unsigned_msg);
4941 assert_eq!(nodes[0].router.handle_channel_announcement(&chan_announcement).unwrap(), true);
4942 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 } );
4944 // Configured with Network::Testnet
4945 let mut unsigned_msg = dummy_unsigned_msg!();
4946 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.bitcoin_hash();
4947 sign_msg!(unsigned_msg);
4948 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
4950 let mut unsigned_msg = dummy_unsigned_msg!();
4951 unsigned_msg.chain_hash = Sha256dHash::from_data(&[1,2,3,4,5,6,7,8,9]);
4952 sign_msg!(unsigned_msg);
4953 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
4956 struct VecWriter(Vec<u8>);
4957 impl Writer for VecWriter {
4958 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
4959 self.0.extend_from_slice(buf);
4962 fn size_hint(&mut self, size: usize) {
4963 self.0.reserve_exact(size);
4968 fn test_no_txn_manager_serialize_deserialize() {
4969 let mut nodes = create_network(2);
4971 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001);
4973 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4975 let nodes_0_serialized = nodes[0].node.encode();
4976 let mut chan_0_monitor_serialized = VecWriter(Vec::new());
4977 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
4979 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())));
4980 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4981 let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
4982 assert!(chan_0_monitor_read.is_empty());
4984 let mut nodes_0_read = &nodes_0_serialized[..];
4985 let config = UserConfig::new();
4986 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
4987 let (_, nodes_0_deserialized) = {
4988 let mut channel_monitors = HashMap::new();
4989 channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
4990 <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4991 default_config: config,
4993 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
4994 monitor: nodes[0].chan_monitor.clone(),
4995 chain_monitor: nodes[0].chain_monitor.clone(),
4996 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4997 logger: Arc::new(test_utils::TestLogger::new()),
4998 channel_monitors: &channel_monitors,
5001 assert!(nodes_0_read.is_empty());
5003 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
5004 nodes[0].node = Arc::new(nodes_0_deserialized);
5005 let nodes_0_as_listener: Arc<ChainListener> = nodes[0].node.clone();
5006 nodes[0].chain_monitor.register_listener(Arc::downgrade(&nodes_0_as_listener));
5007 assert_eq!(nodes[0].node.list_channels().len(), 1);
5008 check_added_monitors!(nodes[0], 1);
5010 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
5011 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
5012 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
5013 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
5015 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
5016 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5017 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
5018 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5020 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
5021 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
5022 for node in nodes.iter() {
5023 assert!(node.router.handle_channel_announcement(&announcement).unwrap());
5024 node.router.handle_channel_update(&as_update).unwrap();
5025 node.router.handle_channel_update(&bs_update).unwrap();
5028 send_payment(&nodes[0], &[&nodes[1]], 1000000);
5032 fn test_simple_manager_serialize_deserialize() {
5033 let mut nodes = create_network(2);
5034 create_announced_chan_between_nodes(&nodes, 0, 1);
5036 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
5037 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
5039 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5041 let nodes_0_serialized = nodes[0].node.encode();
5042 let mut chan_0_monitor_serialized = VecWriter(Vec::new());
5043 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
5045 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())));
5046 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
5047 let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
5048 assert!(chan_0_monitor_read.is_empty());
5050 let mut nodes_0_read = &nodes_0_serialized[..];
5051 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
5052 let (_, nodes_0_deserialized) = {
5053 let mut channel_monitors = HashMap::new();
5054 channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
5055 <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
5056 default_config: UserConfig::new(),
5058 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
5059 monitor: nodes[0].chan_monitor.clone(),
5060 chain_monitor: nodes[0].chain_monitor.clone(),
5061 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
5062 logger: Arc::new(test_utils::TestLogger::new()),
5063 channel_monitors: &channel_monitors,
5066 assert!(nodes_0_read.is_empty());
5068 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
5069 nodes[0].node = Arc::new(nodes_0_deserialized);
5070 check_added_monitors!(nodes[0], 1);
5072 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5074 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
5075 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
5079 fn test_manager_serialize_deserialize_inconsistent_monitor() {
5080 // Test deserializing a ChannelManager with a out-of-date ChannelMonitor
5081 let mut nodes = create_network(4);
5082 create_announced_chan_between_nodes(&nodes, 0, 1);
5083 create_announced_chan_between_nodes(&nodes, 2, 0);
5084 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3);
5086 let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
5088 // Serialize the ChannelManager here, but the monitor we keep up-to-date
5089 let nodes_0_serialized = nodes[0].node.encode();
5091 route_payment(&nodes[0], &[&nodes[3]], 1000000);
5092 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5093 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5094 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5096 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
5098 let mut node_0_monitors_serialized = Vec::new();
5099 for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
5100 let mut writer = VecWriter(Vec::new());
5101 monitor.1.write_for_disk(&mut writer).unwrap();
5102 node_0_monitors_serialized.push(writer.0);
5105 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())));
5106 let mut node_0_monitors = Vec::new();
5107 for serialized in node_0_monitors_serialized.iter() {
5108 let mut read = &serialized[..];
5109 let (_, monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut read, Arc::new(test_utils::TestLogger::new())).unwrap();
5110 assert!(read.is_empty());
5111 node_0_monitors.push(monitor);
5114 let mut nodes_0_read = &nodes_0_serialized[..];
5115 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
5116 let (_, nodes_0_deserialized) = <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
5117 default_config: UserConfig::new(),
5119 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
5120 monitor: nodes[0].chan_monitor.clone(),
5121 chain_monitor: nodes[0].chain_monitor.clone(),
5122 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
5123 logger: Arc::new(test_utils::TestLogger::new()),
5124 channel_monitors: &node_0_monitors.iter().map(|monitor| { (monitor.get_funding_txo().unwrap(), monitor) }).collect(),
5126 assert!(nodes_0_read.is_empty());
5128 { // Channel close should result in a commitment tx and an HTLC tx
5129 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5130 assert_eq!(txn.len(), 2);
5131 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
5132 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
5135 for monitor in node_0_monitors.drain(..) {
5136 assert!(nodes[0].chan_monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor).is_ok());
5137 check_added_monitors!(nodes[0], 1);
5139 nodes[0].node = Arc::new(nodes_0_deserialized);
5141 // nodes[1] and nodes[2] have no lost state with nodes[0]...
5142 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5143 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5144 //... and we can even still claim the payment!
5145 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
5147 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id());
5148 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
5149 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id());
5150 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) {
5151 assert_eq!(msg.channel_id, channel_id);
5152 } else { panic!("Unexpected result"); }
5155 macro_rules! check_spendable_outputs {
5156 ($node: expr, $der_idx: expr) => {
5158 let events = $node.chan_monitor.simple_monitor.get_and_clear_pending_events();
5159 let mut txn = Vec::new();
5160 for event in events {
5162 Event::SpendableOutputs { ref outputs } => {
5163 for outp in outputs {
5165 SpendableOutputDescriptor::DynamicOutputP2WPKH { ref outpoint, ref key, ref output } => {
5167 previous_output: outpoint.clone(),
5168 script_sig: Script::new(),
5170 witness: Vec::new(),
5173 script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
5174 value: output.value,
5176 let mut spend_tx = Transaction {
5182 let secp_ctx = Secp256k1::new();
5183 let remotepubkey = PublicKey::from_secret_key(&secp_ctx, &key);
5184 let witness_script = Address::p2pkh(&remotepubkey, Network::Testnet).script_pubkey();
5185 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
5186 let remotesig = secp_ctx.sign(&sighash, key);
5187 spend_tx.input[0].witness.push(remotesig.serialize_der(&secp_ctx).to_vec());
5188 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
5189 spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
5192 SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref key, ref witness_script, ref to_self_delay, ref output } => {
5194 previous_output: outpoint.clone(),
5195 script_sig: Script::new(),
5196 sequence: *to_self_delay as u32,
5197 witness: Vec::new(),
5200 script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
5201 value: output.value,
5203 let mut spend_tx = Transaction {
5209 let secp_ctx = Secp256k1::new();
5210 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], witness_script, output.value)[..]).unwrap();
5211 let local_delaysig = secp_ctx.sign(&sighash, key);
5212 spend_tx.input[0].witness.push(local_delaysig.serialize_der(&secp_ctx).to_vec());
5213 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
5214 spend_tx.input[0].witness.push(vec!(0));
5215 spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
5218 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
5219 let secp_ctx = Secp256k1::new();
5221 previous_output: outpoint.clone(),
5222 script_sig: Script::new(),
5224 witness: Vec::new(),
5227 script_pubkey: Builder::new().push_opcode(opcodes::All::OP_RETURN).into_script(),
5228 value: output.value,
5230 let mut spend_tx = Transaction {
5234 output: vec![outp.clone()],
5237 match ExtendedPrivKey::new_master(&secp_ctx, Network::Testnet, &$node.node_seed) {
5239 match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx)) {
5241 Err(_) => panic!("Your RNG is busted"),
5244 Err(_) => panic!("Your rng is busted"),
5247 let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
5248 let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
5249 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
5250 let sig = secp_ctx.sign(&sighash, &secret.secret_key);
5251 spend_tx.input[0].witness.push(sig.serialize_der(&secp_ctx).to_vec());
5252 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
5253 spend_tx.input[0].witness.push(pubkey.serialize().to_vec());
5259 _ => panic!("Unexpected event"),
5268 fn test_claim_sizeable_push_msat() {
5269 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
5270 let nodes = create_network(2);
5272 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000);
5273 nodes[1].node.force_close_channel(&chan.2);
5274 check_closed_broadcast!(nodes[1]);
5275 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5276 assert_eq!(node_txn.len(), 1);
5277 check_spends!(node_txn[0], chan.3.clone());
5278 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
5280 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5281 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
5282 let spend_txn = check_spendable_outputs!(nodes[1], 1);
5283 assert_eq!(spend_txn.len(), 1);
5284 check_spends!(spend_txn[0], node_txn[0].clone());
5288 fn test_claim_on_remote_sizeable_push_msat() {
5289 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
5290 // to_remote output is encumbered by a P2WPKH
5292 let nodes = create_network(2);
5294 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000);
5295 nodes[0].node.force_close_channel(&chan.2);
5296 check_closed_broadcast!(nodes[0]);
5298 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5299 assert_eq!(node_txn.len(), 1);
5300 check_spends!(node_txn[0], chan.3.clone());
5301 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
5303 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5304 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
5305 check_closed_broadcast!(nodes[1]);
5306 let spend_txn = check_spendable_outputs!(nodes[1], 1);
5307 assert_eq!(spend_txn.len(), 2);
5308 assert_eq!(spend_txn[0], spend_txn[1]);
5309 check_spends!(spend_txn[0], node_txn[0].clone());
5313 fn test_claim_on_remote_revoked_sizeable_push_msat() {
5314 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
5315 // to_remote output is encumbered by a P2WPKH
5317 let nodes = create_network(2);
5319 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
5320 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5321 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
5322 assert_eq!(revoked_local_txn[0].input.len(), 1);
5323 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
5325 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5326 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5327 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5328 check_closed_broadcast!(nodes[1]);
5330 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5331 let spend_txn = check_spendable_outputs!(nodes[1], 1);
5332 assert_eq!(spend_txn.len(), 4);
5333 assert_eq!(spend_txn[0], spend_txn[2]); // to_remote output on revoked remote commitment_tx
5334 check_spends!(spend_txn[0], revoked_local_txn[0].clone());
5335 assert_eq!(spend_txn[1], spend_txn[3]); // to_local output on local commitment tx
5336 check_spends!(spend_txn[1], node_txn[0].clone());
5340 fn test_static_spendable_outputs_preimage_tx() {
5341 let nodes = create_network(2);
5343 // Create some initial channels
5344 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5346 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5348 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
5349 assert_eq!(commitment_tx[0].input.len(), 1);
5350 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
5352 // Settle A's commitment tx on B's chain
5353 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5354 assert!(nodes[1].node.claim_funds(payment_preimage));
5355 check_added_monitors!(nodes[1], 1);
5356 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
5357 let events = nodes[1].node.get_and_clear_pending_msg_events();
5359 MessageSendEvent::UpdateHTLCs { .. } => {},
5360 _ => panic!("Unexpected event"),
5363 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5364 _ => panic!("Unexepected event"),
5367 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
5368 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 1 (local commitment tx), ChannelMonitor: 2 (1 preimage tx) * 2 (block-rescan)
5369 check_spends!(node_txn[0], commitment_tx[0].clone());
5370 assert_eq!(node_txn[0], node_txn[2]);
5371 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5372 check_spends!(node_txn[1], chan_1.3.clone());
5374 let spend_txn = check_spendable_outputs!(nodes[1], 1); // , 0, 0, 1, 1);
5375 assert_eq!(spend_txn.len(), 2);
5376 assert_eq!(spend_txn[0], spend_txn[1]);
5377 check_spends!(spend_txn[0], node_txn[0].clone());
5381 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
5382 let nodes = create_network(2);
5384 // Create some initial channels
5385 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5387 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5388 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
5389 assert_eq!(revoked_local_txn[0].input.len(), 1);
5390 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5392 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5394 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5395 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5396 check_closed_broadcast!(nodes[1]);
5398 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5399 assert_eq!(node_txn.len(), 3);
5400 assert_eq!(node_txn.pop().unwrap(), node_txn[0]);
5401 assert_eq!(node_txn[0].input.len(), 2);
5402 check_spends!(node_txn[0], revoked_local_txn[0].clone());
5404 let spend_txn = check_spendable_outputs!(nodes[1], 1);
5405 assert_eq!(spend_txn.len(), 2);
5406 assert_eq!(spend_txn[0], spend_txn[1]);
5407 check_spends!(spend_txn[0], node_txn[0].clone());
5411 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
5412 let nodes = create_network(2);
5414 // Create some initial channels
5415 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5417 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5418 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
5419 assert_eq!(revoked_local_txn[0].input.len(), 1);
5420 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5422 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5424 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5425 // A will generate HTLC-Timeout from revoked commitment tx
5426 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5427 check_closed_broadcast!(nodes[0]);
5429 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5430 assert_eq!(revoked_htlc_txn.len(), 3);
5431 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
5432 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5433 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5434 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
5435 check_spends!(revoked_htlc_txn[1], chan_1.3.clone());
5437 // B will generate justice tx from A's revoked commitment/HTLC tx
5438 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
5439 check_closed_broadcast!(nodes[1]);
5441 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5442 assert_eq!(node_txn.len(), 4);
5443 assert_eq!(node_txn[3].input.len(), 1);
5444 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
5446 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
5447 let spend_txn = check_spendable_outputs!(nodes[1], 1);
5448 assert_eq!(spend_txn.len(), 3);
5449 assert_eq!(spend_txn[0], spend_txn[1]);
5450 check_spends!(spend_txn[0], node_txn[0].clone());
5451 check_spends!(spend_txn[2], node_txn[3].clone());
5455 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
5456 let nodes = create_network(2);
5458 // Create some initial channels
5459 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5461 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5462 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
5463 assert_eq!(revoked_local_txn[0].input.len(), 1);
5464 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5466 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5468 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5469 // B will generate HTLC-Success from revoked commitment tx
5470 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5471 check_closed_broadcast!(nodes[1]);
5472 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5474 assert_eq!(revoked_htlc_txn.len(), 3);
5475 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
5476 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5477 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5478 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
5480 // A will generate justice tx from B's revoked commitment/HTLC tx
5481 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
5482 check_closed_broadcast!(nodes[0]);
5484 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5485 assert_eq!(node_txn.len(), 4);
5486 assert_eq!(node_txn[3].input.len(), 1);
5487 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
5489 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5490 let spend_txn = check_spendable_outputs!(nodes[0], 1);
5491 assert_eq!(spend_txn.len(), 5);
5492 assert_eq!(spend_txn[0], spend_txn[2]);
5493 assert_eq!(spend_txn[1], spend_txn[3]);
5494 check_spends!(spend_txn[0], revoked_local_txn[0].clone()); // spending to_remote output from revoked local tx
5495 check_spends!(spend_txn[1], node_txn[2].clone()); // spending justice tx output from revoked local tx htlc received output
5496 check_spends!(spend_txn[4], node_txn[3].clone()); // spending justice tx output on htlc success tx
5500 fn test_onchain_to_onchain_claim() {
5501 // Test that in case of channel closure, we detect the state of output thanks to
5502 // ChainWatchInterface and claim HTLC on downstream peer's remote commitment tx.
5503 // First, have C claim an HTLC against its own latest commitment transaction.
5504 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5506 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5509 let nodes = create_network(3);
5511 // Create some initial channels
5512 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5513 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5515 // Rebalance the network a bit by relaying one payment through all the channels ...
5516 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5517 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5519 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5520 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5521 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
5522 check_spends!(commitment_tx[0], chan_2.3.clone());
5523 nodes[2].node.claim_funds(payment_preimage);
5524 check_added_monitors!(nodes[2], 1);
5525 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5526 assert!(updates.update_add_htlcs.is_empty());
5527 assert!(updates.update_fail_htlcs.is_empty());
5528 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5529 assert!(updates.update_fail_malformed_htlcs.is_empty());
5531 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
5532 check_closed_broadcast!(nodes[2]);
5534 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5535 assert_eq!(c_txn.len(), 3);
5536 assert_eq!(c_txn[0], c_txn[2]);
5537 assert_eq!(commitment_tx[0], c_txn[1]);
5538 check_spends!(c_txn[1], chan_2.3.clone());
5539 check_spends!(c_txn[2], c_txn[1].clone());
5540 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5541 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5542 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5543 assert_eq!(c_txn[0].lock_time, 0); // Success tx
5545 // 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
5546 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
5548 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5549 assert_eq!(b_txn.len(), 4);
5550 assert_eq!(b_txn[0], b_txn[3]);
5551 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
5552 check_spends!(b_txn[2], b_txn[1].clone()); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
5553 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5554 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5555 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5556 check_spends!(b_txn[0], c_txn[1].clone()); // timeout tx on C remote commitment tx, issued by ChannelMonitor, * 2 due to block rescan
5557 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5558 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5559 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5562 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5563 check_added_monitors!(nodes[1], 1);
5564 match msg_events[0] {
5565 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5566 _ => panic!("Unexpected event"),
5568 match msg_events[1] {
5569 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, .. } } => {
5570 assert!(update_add_htlcs.is_empty());
5571 assert!(update_fail_htlcs.is_empty());
5572 assert_eq!(update_fulfill_htlcs.len(), 1);
5573 assert!(update_fail_malformed_htlcs.is_empty());
5574 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5576 _ => panic!("Unexpected event"),
5578 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5579 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
5580 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
5581 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5582 assert_eq!(b_txn.len(), 3);
5583 check_spends!(b_txn[1], chan_1.3); // Local commitment tx, issued by ChannelManager
5584 assert_eq!(b_txn[0], b_txn[2]); // HTLC-Success tx, issued by ChannelMonitor, * 2 due to block rescan
5585 check_spends!(b_txn[0], commitment_tx[0].clone());
5586 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5587 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5588 assert_eq!(b_txn[2].lock_time, 0); // Success tx
5590 check_closed_broadcast!(nodes[1]);
5594 fn test_duplicate_payment_hash_one_failure_one_success() {
5595 // Topology : A --> B --> C
5596 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5597 let mut nodes = create_network(3);
5599 create_announced_chan_between_nodes(&nodes, 0, 1);
5600 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5602 let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5603 *nodes[0].network_payment_count.borrow_mut() -= 1;
5604 assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
5606 let commitment_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
5607 assert_eq!(commitment_txn[0].input.len(), 1);
5608 check_spends!(commitment_txn[0], chan_2.3.clone());
5610 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5611 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
5612 check_closed_broadcast!(nodes[1]);
5614 let htlc_timeout_tx;
5615 { // Extract one of the two HTLC-Timeout transaction
5616 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5617 assert_eq!(node_txn.len(), 7);
5618 assert_eq!(node_txn[0], node_txn[5]);
5619 assert_eq!(node_txn[1], node_txn[6]);
5620 check_spends!(node_txn[0], commitment_txn[0].clone());
5621 assert_eq!(node_txn[0].input.len(), 1);
5622 check_spends!(node_txn[1], commitment_txn[0].clone());
5623 assert_eq!(node_txn[1].input.len(), 1);
5624 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
5625 check_spends!(node_txn[2], chan_2.3.clone());
5626 check_spends!(node_txn[3], node_txn[2].clone());
5627 check_spends!(node_txn[4], node_txn[2].clone());
5628 htlc_timeout_tx = node_txn[1].clone();
5631 nodes[2].node.claim_funds(our_payment_preimage);
5632 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
5633 check_added_monitors!(nodes[2], 2);
5634 let events = nodes[2].node.get_and_clear_pending_msg_events();
5636 MessageSendEvent::UpdateHTLCs { .. } => {},
5637 _ => panic!("Unexpected event"),
5640 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5641 _ => panic!("Unexepected event"),
5643 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5644 assert_eq!(htlc_success_txn.len(), 5);
5645 check_spends!(htlc_success_txn[2], chan_2.3.clone());
5646 assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
5647 assert_eq!(htlc_success_txn[0].input.len(), 1);
5648 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5649 assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
5650 assert_eq!(htlc_success_txn[1].input.len(), 1);
5651 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5652 assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
5653 check_spends!(htlc_success_txn[0], commitment_txn[0].clone());
5654 check_spends!(htlc_success_txn[1], commitment_txn[0].clone());
5656 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![htlc_timeout_tx] }, 200);
5657 expect_pending_htlcs_forwardable!(nodes[1]);
5658 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5659 assert!(htlc_updates.update_add_htlcs.is_empty());
5660 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5661 assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
5662 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5663 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5664 check_added_monitors!(nodes[1], 1);
5666 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]).unwrap();
5667 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5669 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5670 let events = nodes[0].node.get_and_clear_pending_msg_events();
5671 assert_eq!(events.len(), 1);
5673 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. } } => {
5675 _ => { panic!("Unexpected event"); }
5678 let events = nodes[0].node.get_and_clear_pending_events();
5680 Event::PaymentFailed { ref payment_hash, .. } => {
5681 assert_eq!(*payment_hash, duplicate_payment_hash);
5683 _ => panic!("Unexpected event"),
5686 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5687 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
5688 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5689 assert!(updates.update_add_htlcs.is_empty());
5690 assert!(updates.update_fail_htlcs.is_empty());
5691 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5692 assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
5693 assert!(updates.update_fail_malformed_htlcs.is_empty());
5694 check_added_monitors!(nodes[1], 1);
5696 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
5697 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5699 let events = nodes[0].node.get_and_clear_pending_events();
5701 Event::PaymentSent { ref payment_preimage } => {
5702 assert_eq!(*payment_preimage, our_payment_preimage);
5704 _ => panic!("Unexpected event"),
5709 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5710 let nodes = create_network(2);
5712 // Create some initial channels
5713 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5715 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5716 let local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
5717 assert_eq!(local_txn[0].input.len(), 1);
5718 check_spends!(local_txn[0], chan_1.3.clone());
5720 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5721 nodes[1].node.claim_funds(payment_preimage);
5722 check_added_monitors!(nodes[1], 1);
5723 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5724 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 1);
5725 let events = nodes[1].node.get_and_clear_pending_msg_events();
5727 MessageSendEvent::UpdateHTLCs { .. } => {},
5728 _ => panic!("Unexpected event"),
5731 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5732 _ => panic!("Unexepected event"),
5734 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5735 assert_eq!(node_txn[0].input.len(), 1);
5736 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5737 check_spends!(node_txn[0], local_txn[0].clone());
5739 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5740 let spend_txn = check_spendable_outputs!(nodes[1], 1);
5741 assert_eq!(spend_txn.len(), 2);
5742 check_spends!(spend_txn[0], node_txn[0].clone());
5743 check_spends!(spend_txn[1], node_txn[2].clone());
5746 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5747 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5748 // unrevoked commitment transaction.
5749 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5750 // a remote RAA before they could be failed backwards (and combinations thereof).
5751 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5752 // use the same payment hashes.
5753 // Thus, we use a six-node network:
5758 // And test where C fails back to A/B when D announces its latest commitment transaction
5759 let nodes = create_network(6);
5761 create_announced_chan_between_nodes(&nodes, 0, 2);
5762 create_announced_chan_between_nodes(&nodes, 1, 2);
5763 let chan = create_announced_chan_between_nodes(&nodes, 2, 3);
5764 create_announced_chan_between_nodes(&nodes, 3, 4);
5765 create_announced_chan_between_nodes(&nodes, 3, 5);
5767 // Rebalance and check output sanity...
5768 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5769 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5770 assert_eq!(nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn[0].output.len(), 2);
5772 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
5774 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
5776 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
5777 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();
5779 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
5781 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
5783 let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5785 let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5786 let route = nodes[1].router.get_route(&nodes[5].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
5788 send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_3);
5790 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_4);
5793 let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5795 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();
5796 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
5799 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
5801 let route = nodes[1].router.get_route(&nodes[5].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
5802 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_6);
5804 // Double-check that six of the new HTLC were added
5805 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5806 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5807 assert_eq!(nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.len(), 1);
5808 assert_eq!(nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn[0].output.len(), 8);
5810 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5811 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5812 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1, ds_dust_limit*1000));
5813 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3, 1000000));
5814 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5, 1000000));
5815 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6, ds_dust_limit*1000));
5816 check_added_monitors!(nodes[4], 0);
5817 expect_pending_htlcs_forwardable!(nodes[4]);
5818 check_added_monitors!(nodes[4], 1);
5820 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5821 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]).unwrap();
5822 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]).unwrap();
5823 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]).unwrap();
5824 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]).unwrap();
5825 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5827 // Fail 3rd below-dust and 7th above-dust HTLCs
5828 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2, ds_dust_limit*1000));
5829 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4, 1000000));
5830 check_added_monitors!(nodes[5], 0);
5831 expect_pending_htlcs_forwardable!(nodes[5]);
5832 check_added_monitors!(nodes[5], 1);
5834 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5835 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]).unwrap();
5836 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]).unwrap();
5837 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5839 let ds_prev_commitment_tx = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
5841 expect_pending_htlcs_forwardable!(nodes[3]);
5842 check_added_monitors!(nodes[3], 1);
5843 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5844 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]).unwrap();
5845 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]).unwrap();
5846 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]).unwrap();
5847 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]).unwrap();
5848 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]).unwrap();
5849 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]).unwrap();
5850 if deliver_last_raa {
5851 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5853 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5856 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5857 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5858 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5859 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5861 // We now broadcast the latest commitment transaction, which *should* result in failures for
5862 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5863 // the non-broadcast above-dust HTLCs.
5865 // Alternatively, we may broadcast the previous commitment transaction, which should only
5866 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5867 let ds_last_commitment_tx = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
5869 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5870 if announce_latest {
5871 nodes[2].chain_monitor.block_connected_checked(&header, 1, &[&ds_last_commitment_tx[0]], &[1; 1]);
5873 nodes[2].chain_monitor.block_connected_checked(&header, 1, &[&ds_prev_commitment_tx[0]], &[1; 1]);
5875 check_closed_broadcast!(nodes[2]);
5876 expect_pending_htlcs_forwardable!(nodes[2]);
5877 check_added_monitors!(nodes[2], 2);
5879 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5880 assert_eq!(cs_msgs.len(), 2);
5881 let mut a_done = false;
5882 for msg in cs_msgs {
5884 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5885 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5886 // should be failed-backwards here.
5887 let target = if *node_id == nodes[0].node.get_our_node_id() {
5888 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5889 for htlc in &updates.update_fail_htlcs {
5890 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 });
5892 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5897 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5898 for htlc in &updates.update_fail_htlcs {
5899 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5901 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5902 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5905 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
5906 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]).unwrap();
5907 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]).unwrap();
5908 if announce_latest {
5909 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]).unwrap();
5910 if *node_id == nodes[0].node.get_our_node_id() {
5911 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]).unwrap();
5914 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5916 _ => panic!("Unexpected event"),
5920 let as_events = nodes[0].node.get_and_clear_pending_events();
5921 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5922 let mut as_failds = HashSet::new();
5923 for event in as_events.iter() {
5924 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5925 assert!(as_failds.insert(*payment_hash));
5926 if *payment_hash != payment_hash_2 {
5927 assert_eq!(*rejected_by_dest, deliver_last_raa);
5929 assert!(!rejected_by_dest);
5931 } else { panic!("Unexpected event"); }
5933 assert!(as_failds.contains(&payment_hash_1));
5934 assert!(as_failds.contains(&payment_hash_2));
5935 if announce_latest {
5936 assert!(as_failds.contains(&payment_hash_3));
5937 assert!(as_failds.contains(&payment_hash_5));
5939 assert!(as_failds.contains(&payment_hash_6));
5941 let bs_events = nodes[1].node.get_and_clear_pending_events();
5942 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5943 let mut bs_failds = HashSet::new();
5944 for event in bs_events.iter() {
5945 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5946 assert!(bs_failds.insert(*payment_hash));
5947 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5948 assert_eq!(*rejected_by_dest, deliver_last_raa);
5950 assert!(!rejected_by_dest);
5952 } else { panic!("Unexpected event"); }
5954 assert!(bs_failds.contains(&payment_hash_1));
5955 assert!(bs_failds.contains(&payment_hash_2));
5956 if announce_latest {
5957 assert!(bs_failds.contains(&payment_hash_4));
5959 assert!(bs_failds.contains(&payment_hash_5));
5961 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5962 // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
5963 // to unknown-preimage-etc, B should have gotten 2. Thus, in the
5964 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
5965 // PaymentFailureNetworkUpdates.
5966 let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
5967 assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5968 let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5969 assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5970 for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
5972 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
5973 _ => panic!("Unexpected event"),
5979 fn test_fail_backwards_latest_remote_announce_a() {
5980 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5984 fn test_fail_backwards_latest_remote_announce_b() {
5985 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5989 fn test_fail_backwards_previous_remote_announce() {
5990 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5991 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5992 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5996 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5997 let nodes = create_network(2);
5999 // Create some initial channels
6000 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
6002 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
6003 let local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
6004 assert_eq!(local_txn[0].input.len(), 1);
6005 check_spends!(local_txn[0], chan_1.3.clone());
6007 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
6008 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6009 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 200);
6010 check_closed_broadcast!(nodes[0]);
6012 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
6013 assert_eq!(node_txn[0].input.len(), 1);
6014 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6015 check_spends!(node_txn[0], local_txn[0].clone());
6017 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
6018 let spend_txn = check_spendable_outputs!(nodes[0], 1);
6019 assert_eq!(spend_txn.len(), 8);
6020 assert_eq!(spend_txn[0], spend_txn[2]);
6021 assert_eq!(spend_txn[0], spend_txn[4]);
6022 assert_eq!(spend_txn[0], spend_txn[6]);
6023 assert_eq!(spend_txn[1], spend_txn[3]);
6024 assert_eq!(spend_txn[1], spend_txn[5]);
6025 assert_eq!(spend_txn[1], spend_txn[7]);
6026 check_spends!(spend_txn[0], local_txn[0].clone());
6027 check_spends!(spend_txn[1], node_txn[0].clone());
6031 fn test_static_output_closing_tx() {
6032 let nodes = create_network(2);
6034 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6036 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
6037 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
6039 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6040 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
6041 let spend_txn = check_spendable_outputs!(nodes[0], 2);
6042 assert_eq!(spend_txn.len(), 1);
6043 check_spends!(spend_txn[0], closing_tx.clone());
6045 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
6046 let spend_txn = check_spendable_outputs!(nodes[1], 2);
6047 assert_eq!(spend_txn.len(), 1);
6048 check_spends!(spend_txn[0], closing_tx);
6051 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
6052 let nodes = create_network(2);
6053 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6055 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
6057 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
6058 // present in B's local commitment transaction, but none of A's commitment transactions.
6059 assert!(nodes[1].node.claim_funds(our_payment_preimage));
6060 check_added_monitors!(nodes[1], 1);
6062 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6063 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]).unwrap();
6064 let events = nodes[0].node.get_and_clear_pending_events();
6065 assert_eq!(events.len(), 1);
6067 Event::PaymentSent { payment_preimage } => {
6068 assert_eq!(payment_preimage, our_payment_preimage);
6070 _ => panic!("Unexpected event"),
6073 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed).unwrap();
6074 check_added_monitors!(nodes[0], 1);
6075 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6076 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0).unwrap();
6077 check_added_monitors!(nodes[1], 1);
6079 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6080 for i in 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + CHAN_CONFIRM_DEPTH + 1 {
6081 nodes[1].chain_monitor.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
6082 header.prev_blockhash = header.bitcoin_hash();
6084 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
6085 check_closed_broadcast!(nodes[1]);
6088 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
6089 let mut nodes = create_network(2);
6090 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6092 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();
6093 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
6094 nodes[0].node.send_payment(route, payment_hash).unwrap();
6095 check_added_monitors!(nodes[0], 1);
6097 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6099 // As far as A is concerened, the HTLC is now present only in the latest remote commitment
6100 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
6101 // to "time out" the HTLC.
6103 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6104 for i in 1..TEST_FINAL_CLTV + HTLC_FAIL_TIMEOUT_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
6105 nodes[0].chain_monitor.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
6106 header.prev_blockhash = header.bitcoin_hash();
6108 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
6109 check_closed_broadcast!(nodes[0]);
6112 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
6113 let nodes = create_network(3);
6114 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6116 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
6117 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
6118 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
6119 // actually revoked.
6120 let htlc_value = if use_dust { 50000 } else { 3000000 };
6121 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
6122 assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash, htlc_value));
6123 expect_pending_htlcs_forwardable!(nodes[1]);
6124 check_added_monitors!(nodes[1], 1);
6126 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6127 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]).unwrap();
6128 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed).unwrap();
6129 check_added_monitors!(nodes[0], 1);
6130 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6131 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0).unwrap();
6132 check_added_monitors!(nodes[1], 1);
6133 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1).unwrap();
6134 check_added_monitors!(nodes[1], 1);
6135 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6137 if check_revoke_no_close {
6138 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
6139 check_added_monitors!(nodes[0], 1);
6142 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6143 for i in 1..TEST_FINAL_CLTV + HTLC_FAIL_TIMEOUT_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
6144 nodes[0].chain_monitor.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
6145 header.prev_blockhash = header.bitcoin_hash();
6147 if !check_revoke_no_close {
6148 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
6149 check_closed_broadcast!(nodes[0]);
6151 let events = nodes[0].node.get_and_clear_pending_events();
6152 assert_eq!(events.len(), 1);
6154 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
6155 assert_eq!(payment_hash, our_payment_hash);
6156 assert!(rejected_by_dest);
6158 _ => panic!("Unexpected event"),
6163 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
6164 // There are only a few cases to test here:
6165 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
6166 // broadcastable commitment transactions result in channel closure,
6167 // * its included in an unrevoked-but-previous remote commitment transaction,
6168 // * its included in the latest remote or local commitment transactions.
6169 // We test each of the three possible commitment transactions individually and use both dust and
6171 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
6172 // assume they are handled the same across all six cases, as both outbound and inbound failures are
6173 // tested for at least one of the cases in other tests.
6175 fn htlc_claim_single_commitment_only_a() {
6176 do_htlc_claim_local_commitment_only(true);
6177 do_htlc_claim_local_commitment_only(false);
6179 do_htlc_claim_current_remote_commitment_only(true);
6180 do_htlc_claim_current_remote_commitment_only(false);
6184 fn htlc_claim_single_commitment_only_b() {
6185 do_htlc_claim_previous_remote_commitment_only(true, false);
6186 do_htlc_claim_previous_remote_commitment_only(false, false);
6187 do_htlc_claim_previous_remote_commitment_only(true, true);
6188 do_htlc_claim_previous_remote_commitment_only(false, true);
6191 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>)
6192 where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
6195 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);
6199 // 0: node1 fail backward
6200 // 1: final node fail backward
6201 // 2: payment completed but the user reject the payment
6202 // 3: final node fail backward (but tamper onion payloads from node0)
6203 // 100: trigger error in the intermediate node and tamper returnning fail_htlc
6204 // 200: trigger error in the final node and tamper returnning fail_htlc
6205 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>)
6206 where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
6207 F2: for <'a> FnMut(&'a mut msgs::UpdateFailHTLC),
6210 use ln::msgs::HTLCFailChannelUpdate;
6212 // reset block height
6213 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6214 for ix in 0..nodes.len() {
6215 nodes[ix].chain_monitor.block_connected_checked(&header, 1, &Vec::new()[..], &[0; 0]);
6218 macro_rules! expect_event {
6219 ($node: expr, $event_type: path) => {{
6220 let events = $node.node.get_and_clear_pending_events();
6221 assert_eq!(events.len(), 1);
6223 $event_type { .. } => {},
6224 _ => panic!("Unexpected event"),
6229 macro_rules! expect_htlc_forward {
6231 expect_event!($node, Event::PendingHTLCsForwardable);
6232 $node.node.channel_state.lock().unwrap().next_forward = Instant::now();
6233 $node.node.process_pending_htlc_forwards();
6237 // 0 ~~> 2 send payment
6238 nodes[0].node.send_payment(route.clone(), payment_hash.clone()).unwrap();
6239 check_added_monitors!(nodes[0], 1);
6240 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6241 // temper update_add (0 => 1)
6242 let mut update_add_0 = update_0.update_add_htlcs[0].clone();
6243 if test_case == 0 || test_case == 3 || test_case == 100 {
6244 callback_msg(&mut update_add_0);
6247 // 0 => 1 update_add & CS
6248 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_0).unwrap();
6249 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
6251 let update_1_0 = match test_case {
6252 0|100 => { // intermediate node failure; fail backward to 0
6253 let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6254 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));
6257 1|2|3|200 => { // final node failure; forwarding to 2
6258 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
6260 if test_case != 200 {
6263 expect_htlc_forward!(&nodes[1]);
6265 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
6266 check_added_monitors!(&nodes[1], 1);
6267 assert_eq!(update_1.update_add_htlcs.len(), 1);
6268 // tamper update_add (1 => 2)
6269 let mut update_add_1 = update_1.update_add_htlcs[0].clone();
6270 if test_case != 3 && test_case != 200 {
6271 callback_msg(&mut update_add_1);
6275 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_1).unwrap();
6276 commitment_signed_dance!(nodes[2], nodes[1], update_1.commitment_signed, false, true);
6278 if test_case == 2 || test_case == 200 {
6279 expect_htlc_forward!(&nodes[2]);
6280 expect_event!(&nodes[2], Event::PaymentReceived);
6282 expect_pending_htlcs_forwardable!(nodes[2]);
6285 let update_2_1 = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6286 if test_case == 2 || test_case == 200 {
6287 check_added_monitors!(&nodes[2], 1);
6289 assert!(update_2_1.update_fail_htlcs.len() == 1);
6291 let mut fail_msg = update_2_1.update_fail_htlcs[0].clone();
6292 if test_case == 200 {
6293 callback_fail(&mut fail_msg);
6297 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_msg).unwrap();
6298 commitment_signed_dance!(nodes[1], nodes[2], update_2_1.commitment_signed, true);
6300 // backward fail on 1
6301 let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6302 assert!(update_1_0.update_fail_htlcs.len() == 1);
6305 _ => unreachable!(),
6308 // 1 => 0 commitment_signed_dance
6309 if update_1_0.update_fail_htlcs.len() > 0 {
6310 let mut fail_msg = update_1_0.update_fail_htlcs[0].clone();
6311 if test_case == 100 {
6312 callback_fail(&mut fail_msg);
6314 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg).unwrap();
6316 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_1_0.update_fail_malformed_htlcs[0]).unwrap();
6319 commitment_signed_dance!(nodes[0], nodes[1], update_1_0.commitment_signed, false, true);
6321 let events = nodes[0].node.get_and_clear_pending_events();
6322 assert_eq!(events.len(), 1);
6323 if let &Event::PaymentFailed { payment_hash:_, ref rejected_by_dest, ref error_code } = &events[0] {
6324 assert_eq!(*rejected_by_dest, !expected_retryable);
6325 assert_eq!(*error_code, expected_error_code);
6327 panic!("Uexpected event");
6330 let events = nodes[0].node.get_and_clear_pending_msg_events();
6331 if expected_channel_update.is_some() {
6332 assert_eq!(events.len(), 1);
6334 MessageSendEvent::PaymentFailureNetworkUpdate { ref update } => {
6336 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {
6337 if let HTLCFailChannelUpdate::ChannelUpdateMessage { .. } = expected_channel_update.unwrap() {} else {
6338 panic!("channel_update not found!");
6341 &HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id, ref is_permanent } => {
6342 if let HTLCFailChannelUpdate::ChannelClosed { short_channel_id: ref expected_short_channel_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
6343 assert!(*short_channel_id == *expected_short_channel_id);
6344 assert!(*is_permanent == *expected_is_permanent);
6346 panic!("Unexpected message event");
6349 &HTLCFailChannelUpdate::NodeFailure { ref node_id, ref is_permanent } => {
6350 if let HTLCFailChannelUpdate::NodeFailure { node_id: ref expected_node_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
6351 assert!(*node_id == *expected_node_id);
6352 assert!(*is_permanent == *expected_is_permanent);
6354 panic!("Unexpected message event");
6359 _ => panic!("Unexpected message event"),
6362 assert_eq!(events.len(), 0);
6366 impl msgs::ChannelUpdate {
6367 fn dummy() -> msgs::ChannelUpdate {
6368 use secp256k1::ffi::Signature as FFISignature;
6369 use secp256k1::Signature;
6370 msgs::ChannelUpdate {
6371 signature: Signature::from(FFISignature::new()),
6372 contents: msgs::UnsignedChannelUpdate {
6373 chain_hash: Sha256dHash::from_data(&vec![0u8][..]),
6374 short_channel_id: 0,
6377 cltv_expiry_delta: 0,
6378 htlc_minimum_msat: 0,
6380 fee_proportional_millionths: 0,
6381 excess_data: vec![],
6388 fn test_onion_failure() {
6389 use ln::msgs::ChannelUpdate;
6390 use ln::channelmanager::CLTV_FAR_FAR_AWAY;
6393 const BADONION: u16 = 0x8000;
6394 const PERM: u16 = 0x4000;
6395 const NODE: u16 = 0x2000;
6396 const UPDATE: u16 = 0x1000;
6398 let mut nodes = create_network(3);
6399 for node in nodes.iter() {
6400 *node.keys_manager.override_session_priv.lock().unwrap() = Some(SecretKey::from_slice(&Secp256k1::without_caps(), &[3; 32]).unwrap());
6402 let channels = [create_announced_chan_between_nodes(&nodes, 0, 1), create_announced_chan_between_nodes(&nodes, 1, 2)];
6403 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
6404 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV).unwrap();
6406 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 40000);
6408 // intermediate node failure
6409 run_onion_failure_test("invalid_realm", 0, &nodes, &route, &payment_hash, |msg| {
6410 let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
6411 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
6412 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
6413 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
6414 onion_payloads[0].realm = 3;
6415 msg.onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
6416 }, ||{}, 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
6418 // final node failure
6419 run_onion_failure_test("invalid_realm", 3, &nodes, &route, &payment_hash, |msg| {
6420 let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
6421 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
6422 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
6423 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
6424 onion_payloads[1].realm = 3;
6425 msg.onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
6426 }, ||{}, false, Some(PERM|1), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
6428 // the following three with run_onion_failure_test_with_fail_intercept() test only the origin node
6429 // receiving simulated fail messages
6430 // intermediate node failure
6431 run_onion_failure_test_with_fail_intercept("temporary_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
6433 msg.amount_msat -= 1;
6435 // and tamper returing error message
6436 let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
6437 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
6438 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], NODE|2, &[0;0]);
6439 }, ||{}, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: false}));
6441 // final node failure
6442 run_onion_failure_test_with_fail_intercept("temporary_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
6443 // and tamper returing error message
6444 let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
6445 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
6446 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], NODE|2, &[0;0]);
6448 nodes[2].node.fail_htlc_backwards(&payment_hash, 0);
6449 }, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: false}));
6451 // intermediate node failure
6452 run_onion_failure_test_with_fail_intercept("permanent_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
6453 msg.amount_msat -= 1;
6455 let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
6456 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
6457 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|2, &[0;0]);
6458 }, ||{}, true, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: true}));
6460 // final node failure
6461 run_onion_failure_test_with_fail_intercept("permanent_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
6462 let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
6463 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
6464 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|2, &[0;0]);
6466 nodes[2].node.fail_htlc_backwards(&payment_hash, 0);
6467 }, false, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: true}));
6469 // intermediate node failure
6470 run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
6471 msg.amount_msat -= 1;
6473 let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
6474 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
6475 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|3, &[0;0]);
6477 nodes[2].node.fail_htlc_backwards(&payment_hash, 0);
6478 }, true, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: true}));
6480 // final node failure
6481 run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
6482 let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
6483 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
6484 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|3, &[0;0]);
6486 nodes[2].node.fail_htlc_backwards(&payment_hash, 0);
6487 }, false, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: true}));
6489 run_onion_failure_test("invalid_onion_version", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.version = 1; }, ||{}, true,
6490 Some(BADONION|PERM|4), None);
6492 run_onion_failure_test("invalid_onion_hmac", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.hmac = [3; 32]; }, ||{}, true,
6493 Some(BADONION|PERM|5), None);
6495 run_onion_failure_test("invalid_onion_key", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.public_key = Err(secp256k1::Error::InvalidPublicKey);}, ||{}, true,
6496 Some(BADONION|PERM|6), None);
6498 run_onion_failure_test_with_fail_intercept("temporary_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
6499 msg.amount_msat -= 1;
6501 let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
6502 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
6503 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], UPDATE|7, &ChannelUpdate::dummy().encode_with_len()[..]);
6504 }, ||{}, true, Some(UPDATE|7), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
6506 run_onion_failure_test_with_fail_intercept("permanent_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
6507 msg.amount_msat -= 1;
6509 let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
6510 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
6511 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|8, &[0;0]);
6512 // short_channel_id from the processing node
6513 }, ||{}, true, Some(PERM|8), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
6515 run_onion_failure_test_with_fail_intercept("required_channel_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
6516 msg.amount_msat -= 1;
6518 let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
6519 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
6520 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|9, &[0;0]);
6521 // short_channel_id from the processing node
6522 }, ||{}, true, Some(PERM|9), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
6524 let mut bogus_route = route.clone();
6525 bogus_route.hops[1].short_channel_id -= 1;
6526 run_onion_failure_test("unknown_next_peer", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(PERM|10),
6527 Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: bogus_route.hops[1].short_channel_id, is_permanent:true}));
6529 let amt_to_forward = nodes[1].node.channel_state.lock().unwrap().by_id.get(&channels[1].2).unwrap().get_their_htlc_minimum_msat() - 1;
6530 let mut bogus_route = route.clone();
6531 let route_len = bogus_route.hops.len();
6532 bogus_route.hops[route_len-1].fee_msat = amt_to_forward;
6533 run_onion_failure_test("amount_below_minimum", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(UPDATE|11), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
6535 //TODO: with new config API, we will be able to generate both valid and
6536 //invalid channel_update cases.
6537 run_onion_failure_test("fee_insufficient", 0, &nodes, &route, &payment_hash, |msg| {
6538 msg.amount_msat -= 1;
6539 }, || {}, true, Some(UPDATE|12), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
6541 run_onion_failure_test("incorrect_cltv_expiry", 0, &nodes, &route, &payment_hash, |msg| {
6542 // need to violate: cltv_expiry - cltv_expiry_delta >= outgoing_cltv_value
6543 msg.cltv_expiry -= 1;
6544 }, || {}, true, Some(UPDATE|13), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
6546 run_onion_failure_test("expiry_too_soon", 0, &nodes, &route, &payment_hash, |msg| {
6547 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - HTLC_FAIL_TIMEOUT_BLOCKS + 1;
6548 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6549 nodes[1].chain_monitor.block_connected_checked(&header, height, &Vec::new()[..], &[0; 0]);
6550 }, ||{}, true, Some(UPDATE|14), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
6552 run_onion_failure_test("unknown_payment_hash", 2, &nodes, &route, &payment_hash, |_| {}, || {
6553 nodes[2].node.fail_htlc_backwards(&payment_hash, 0);
6554 }, false, Some(PERM|15), None);
6556 run_onion_failure_test("final_expiry_too_soon", 1, &nodes, &route, &payment_hash, |msg| {
6557 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - HTLC_FAIL_TIMEOUT_BLOCKS + 1;
6558 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6559 nodes[2].chain_monitor.block_connected_checked(&header, height, &Vec::new()[..], &[0; 0]);
6560 }, || {}, true, Some(17), None);
6562 run_onion_failure_test("final_incorrect_cltv_expiry", 1, &nodes, &route, &payment_hash, |_| {}, || {
6563 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().borrow_parts().forward_htlcs.iter_mut() {
6564 for f in pending_forwards.iter_mut() {
6566 &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
6567 forward_info.outgoing_cltv_value += 1,
6572 }, true, Some(18), None);
6574 run_onion_failure_test("final_incorrect_htlc_amount", 1, &nodes, &route, &payment_hash, |_| {}, || {
6575 // violate amt_to_forward > msg.amount_msat
6576 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().borrow_parts().forward_htlcs.iter_mut() {
6577 for f in pending_forwards.iter_mut() {
6579 &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
6580 forward_info.amt_to_forward -= 1,
6585 }, true, Some(19), None);
6587 run_onion_failure_test("channel_disabled", 0, &nodes, &route, &payment_hash, |_| {}, || {
6588 // disconnect event to the channel between nodes[1] ~ nodes[2]
6589 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
6590 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6591 }, true, Some(UPDATE|20), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
6592 reconnect_nodes(&nodes[1], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
6594 run_onion_failure_test("expiry_too_far", 0, &nodes, &route, &payment_hash, |msg| {
6595 let session_priv = SecretKey::from_slice(&::secp256k1::Secp256k1::without_caps(), &[3; 32]).unwrap();
6596 let mut route = route.clone();
6598 route.hops[1].cltv_expiry_delta += CLTV_FAR_FAR_AWAY + route.hops[0].cltv_expiry_delta + 1;
6599 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
6600 let (onion_payloads, _, htlc_cltv) = onion_utils::build_onion_payloads(&route, height).unwrap();
6601 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
6602 msg.cltv_expiry = htlc_cltv;
6603 msg.onion_routing_packet = onion_packet;
6604 }, ||{}, true, Some(21), None);
6607 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6608 // 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.
6609 //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.
6612 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6613 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6614 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6615 let mut nodes = create_network(2);
6616 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6617 let mut route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
6618 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6620 route.hops[0].fee_msat = 0;
6622 let err = nodes[0].node.send_payment(route, our_payment_hash);
6624 if let Err(APIError::ChannelUnavailable{err}) = err {
6625 assert_eq!(err, "Cannot send less than their minimum HTLC value");
6632 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6633 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6634 //TODO: This is not currently explicitly checked when sending an HTLC and exists as TODO in the channel::send_htlc(...) function
6635 //It is enforced when constructing a route.
6636 let mut nodes = create_network(2);
6637 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 0);
6638 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000000, 500000001).unwrap();
6639 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6641 let err = nodes[0].node.send_payment(route, our_payment_hash);
6643 if let Err(APIError::RouteError{err}) = err {
6644 assert_eq!(err, "Channel CLTV overflowed?!");
6651 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6652 //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.
6653 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6654 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6655 let mut nodes = create_network(2);
6656 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6657 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().their_max_accepted_htlcs as u64;
6659 for i in 0..max_accepted_htlcs {
6660 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
6661 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6662 let mut payment_event = {
6663 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
6664 check_added_monitors!(nodes[0], 1);
6666 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6667 assert_eq!(events.len(), 1);
6668 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6669 assert_eq!(htlcs[0].htlc_id, i);
6673 SendEvent::from_event(events.remove(0))
6675 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
6676 check_added_monitors!(nodes[1], 0);
6677 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6679 expect_pending_htlcs_forwardable!(nodes[1]);
6680 expect_payment_received!(nodes[1], our_payment_hash, 100000);
6682 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
6683 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6684 let err = nodes[0].node.send_payment(route, our_payment_hash);
6686 if let Err(APIError::ChannelUnavailable{err}) = err {
6687 assert_eq!(err, "Cannot push more than their max accepted HTLCs");
6694 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6695 //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.
6696 let mut nodes = create_network(2);
6697 let channel_value = 100000;
6698 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6699 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).their_max_htlc_value_in_flight_msat;
6701 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6703 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], max_in_flight+1, TEST_FINAL_CLTV).unwrap();
6704 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6705 let err = nodes[0].node.send_payment(route, our_payment_hash);
6707 if let Err(APIError::ChannelUnavailable{err}) = err {
6708 assert_eq!(err, "Cannot send value that would put us over our max HTLC value in flight");
6714 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6716 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6717 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6718 let mut nodes = create_network(2);
6719 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6720 let htlc_minimum_msat: u64;
6722 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6723 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6724 htlc_minimum_msat = channel.get_our_htlc_minimum_msat();
6726 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], htlc_minimum_msat+1, TEST_FINAL_CLTV).unwrap();
6727 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6728 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
6729 check_added_monitors!(nodes[0], 1);
6730 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6731 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6732 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6733 if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
6734 assert_eq!(err, "Remote side tried to send less than our minimum HTLC value");
6738 assert!(nodes[1].node.list_channels().is_empty());
6739 check_closed_broadcast!(nodes[1]);
6743 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6744 //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
6745 let mut nodes = create_network(2);
6746 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6748 let their_channel_reserve = get_channel_value_stat!(nodes[0], chan.2).channel_reserve_msat;
6750 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 5000000-their_channel_reserve, TEST_FINAL_CLTV).unwrap();
6751 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6752 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
6753 check_added_monitors!(nodes[0], 1);
6754 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6756 updates.update_add_htlcs[0].amount_msat = 5000000-their_channel_reserve+1;
6757 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6759 if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
6760 assert_eq!(err, "Remote HTLC add would put them over their reserve value");
6765 assert!(nodes[1].node.list_channels().is_empty());
6766 check_closed_broadcast!(nodes[1]);
6770 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);