1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
15 use crate::chain::{ChannelMonitorUpdateStatus, Confirm, Listen, Watch};
16 use crate::chain::chaininterface::LowerBoundedFeeEstimator;
17 use crate::chain::channelmonitor;
18 use crate::chain::channelmonitor::{CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
19 use crate::chain::transaction::OutPoint;
20 use crate::sign::{ChannelSigner, EcdsaChannelSigner, EntropySource};
21 use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentPurpose, ClosureReason, HTLCDestination, PaymentFailureReason};
22 use crate::ln::{PaymentPreimage, PaymentSecret, PaymentHash};
23 use crate::ln::channel::{commitment_tx_base_weight, COMMITMENT_TX_WEIGHT_PER_HTLC, CONCURRENT_INBOUND_HTLC_FEE_BUFFER, FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE, MIN_AFFORDABLE_HTLC_COUNT, get_holder_selected_channel_reserve_satoshis, OutboundV1Channel, InboundV1Channel};
24 use crate::ln::channelmanager::{self, PaymentId, RAACommitmentOrder, PaymentSendFailure, RecipientOnionFields, BREAKDOWN_TIMEOUT, ENABLE_GOSSIP_TICKS, DISABLE_GOSSIP_TICKS, MIN_CLTV_EXPIRY_DELTA};
25 use crate::ln::channel::{DISCONNECT_PEER_AWAITING_RESPONSE_TICKS, ChannelError};
26 use crate::ln::{chan_utils, onion_utils};
27 use crate::ln::chan_utils::{OFFERED_HTLC_SCRIPT_WEIGHT, htlc_success_tx_weight, htlc_timeout_tx_weight, HTLCOutputInCommitment};
28 use crate::routing::gossip::{NetworkGraph, NetworkUpdate};
29 use crate::routing::router::{Path, PaymentParameters, Route, RouteHop, get_route};
30 use crate::ln::features::{ChannelFeatures, ChannelTypeFeatures, NodeFeatures};
32 use crate::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction};
33 use crate::util::enforcing_trait_impls::EnforcingSigner;
34 use crate::util::test_utils;
35 use crate::util::errors::APIError;
36 use crate::util::ser::{Writeable, ReadableArgs};
37 use crate::util::string::UntrustedString;
38 use crate::util::config::{UserConfig, MaxDustHTLCExposure};
40 use bitcoin::hash_types::BlockHash;
41 use bitcoin::blockdata::script::{Builder, Script};
42 use bitcoin::blockdata::opcodes;
43 use bitcoin::blockdata::constants::genesis_block;
44 use bitcoin::network::constants::Network;
45 use bitcoin::{PackedLockTime, Sequence, Transaction, TxIn, TxOut, Witness};
46 use bitcoin::OutPoint as BitcoinOutPoint;
48 use bitcoin::secp256k1::Secp256k1;
49 use bitcoin::secp256k1::{PublicKey,SecretKey};
54 use crate::prelude::*;
55 use alloc::collections::BTreeSet;
56 use core::default::Default;
57 use core::iter::repeat;
58 use bitcoin::hashes::Hash;
59 use crate::sync::{Arc, Mutex};
61 use crate::ln::functional_test_utils::*;
62 use crate::ln::chan_utils::CommitmentTransaction;
64 use super::channel::UNFUNDED_CHANNEL_AGE_LIMIT_TICKS;
67 fn test_insane_channel_opens() {
68 // Stand up a network of 2 nodes
69 use crate::ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
70 let mut cfg = UserConfig::default();
71 cfg.channel_handshake_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
72 let chanmon_cfgs = create_chanmon_cfgs(2);
73 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
74 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
75 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
77 // Instantiate channel parameters where we push the maximum msats given our
79 let channel_value_sat = 31337; // same as funding satoshis
80 let channel_reserve_satoshis = get_holder_selected_channel_reserve_satoshis(channel_value_sat, &cfg);
81 let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
83 // Have node0 initiate a channel to node1 with aforementioned parameters
84 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
86 // Extract the channel open message from node0 to node1
87 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
89 // Test helper that asserts we get the correct error string given a mutator
90 // that supposedly makes the channel open message insane
91 let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
92 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &message_mutator(open_channel_message.clone()));
93 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
94 assert_eq!(msg_events.len(), 1);
95 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
96 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
98 &ErrorAction::SendErrorMessage { .. } => {
99 nodes[1].logger.assert_log_regex("lightning::ln::channelmanager", expected_regex, 1);
101 _ => panic!("unexpected event!"),
103 } else { assert!(false); }
106 use crate::ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
108 // Test all mutations that would make the channel open message insane
109 insane_open_helper(format!("Per our config, funding must be at most {}. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1, TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2; msg });
110 insane_open_helper(format!("Funding must be smaller than the total bitcoin supply. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS; msg });
112 insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
114 insane_open_helper(r"push_msat \d+ was larger than channel amount minus reserve \(\d+\)", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
116 insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
118 insane_open_helper(r"Minimum htlc value \(\d+\) was larger than full channel value \(\d+\)", |mut msg| { msg.htlc_minimum_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000; msg });
120 insane_open_helper("They wanted our payments to be delayed by a needlessly long period", |mut msg| { msg.to_self_delay = MAX_LOCAL_BREAKDOWN_TIMEOUT + 1; msg });
122 insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
124 insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
128 fn test_funding_exceeds_no_wumbo_limit() {
129 // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
131 use crate::ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
132 let chanmon_cfgs = create_chanmon_cfgs(2);
133 let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
134 *node_cfgs[1].override_init_features.borrow_mut() = Some(channelmanager::provided_init_features(&test_default_channel_config()).clear_wumbo());
135 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
136 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
138 match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None) {
139 Err(APIError::APIMisuseError { err }) => {
140 assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
146 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
147 // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
148 // but only for them. Because some LSPs do it with some level of trust of the clients (for a
149 // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
150 // in normal testing, we test it explicitly here.
151 let chanmon_cfgs = create_chanmon_cfgs(2);
152 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
153 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
154 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
155 let default_config = UserConfig::default();
157 // Have node0 initiate a channel to node1 with aforementioned parameters
158 let mut push_amt = 100_000_000;
159 let feerate_per_kw = 253;
160 let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
161 push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(&channel_type_features) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
162 push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
164 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, if send_from_initiator { 0 } else { push_amt }, 42, None).unwrap();
165 let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
166 if !send_from_initiator {
167 open_channel_message.channel_reserve_satoshis = 0;
168 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
170 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
172 // Extract the channel accept message from node1 to node0
173 let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
174 if send_from_initiator {
175 accept_channel_message.channel_reserve_satoshis = 0;
176 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
178 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
180 let sender_node = if send_from_initiator { &nodes[1] } else { &nodes[0] };
181 let counterparty_node = if send_from_initiator { &nodes[0] } else { &nodes[1] };
182 let mut sender_node_per_peer_lock;
183 let mut sender_node_peer_state_lock;
184 if send_from_initiator {
185 let chan = get_inbound_v1_channel_ref!(sender_node, counterparty_node, sender_node_per_peer_lock, sender_node_peer_state_lock, temp_channel_id);
186 chan.context.holder_selected_channel_reserve_satoshis = 0;
187 chan.context.holder_max_htlc_value_in_flight_msat = 100_000_000;
189 let chan = get_outbound_v1_channel_ref!(sender_node, counterparty_node, sender_node_per_peer_lock, sender_node_peer_state_lock, temp_channel_id);
190 chan.context.holder_selected_channel_reserve_satoshis = 0;
191 chan.context.holder_max_htlc_value_in_flight_msat = 100_000_000;
195 let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
196 let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
197 create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
199 // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
200 // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
201 if send_from_initiator {
202 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
203 // Note that for outbound channels we have to consider the commitment tx fee and the
204 // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
205 // well as an additional HTLC.
206 - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, &channel_type_features));
208 send_payment(&nodes[1], &[&nodes[0]], push_amt);
213 fn test_counterparty_no_reserve() {
214 do_test_counterparty_no_reserve(true);
215 do_test_counterparty_no_reserve(false);
219 fn test_async_inbound_update_fee() {
220 let chanmon_cfgs = create_chanmon_cfgs(2);
221 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
222 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
223 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
224 create_announced_chan_between_nodes(&nodes, 0, 1);
227 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
231 // send (1) commitment_signed -.
232 // <- update_add_htlc/commitment_signed
233 // send (2) RAA (awaiting remote revoke) -.
234 // (1) commitment_signed is delivered ->
235 // .- send (3) RAA (awaiting remote revoke)
236 // (2) RAA is delivered ->
237 // .- send (4) commitment_signed
238 // <- (3) RAA is delivered
239 // send (5) commitment_signed -.
240 // <- (4) commitment_signed is delivered
242 // (5) commitment_signed is delivered ->
244 // (6) RAA is delivered ->
246 // First nodes[0] generates an update_fee
248 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
251 nodes[0].node.timer_tick_occurred();
252 check_added_monitors!(nodes[0], 1);
254 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
255 assert_eq!(events_0.len(), 1);
256 let (update_msg, commitment_signed) = match events_0[0] { // (1)
257 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
258 (update_fee.as_ref(), commitment_signed)
260 _ => panic!("Unexpected event"),
263 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
265 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
266 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
267 nodes[1].node.send_payment_with_route(&route, our_payment_hash,
268 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
269 check_added_monitors!(nodes[1], 1);
271 let payment_event = {
272 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
273 assert_eq!(events_1.len(), 1);
274 SendEvent::from_event(events_1.remove(0))
276 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
277 assert_eq!(payment_event.msgs.len(), 1);
279 // ...now when the messages get delivered everyone should be happy
280 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
281 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
282 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
283 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
284 check_added_monitors!(nodes[0], 1);
286 // deliver(1), generate (3):
287 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
288 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
289 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
290 check_added_monitors!(nodes[1], 1);
292 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
293 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
294 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
295 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
296 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
297 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
298 assert!(bs_update.update_fee.is_none()); // (4)
299 check_added_monitors!(nodes[1], 1);
301 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
302 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
303 assert!(as_update.update_add_htlcs.is_empty()); // (5)
304 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
305 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
306 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
307 assert!(as_update.update_fee.is_none()); // (5)
308 check_added_monitors!(nodes[0], 1);
310 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
311 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
312 // only (6) so get_event_msg's assert(len == 1) passes
313 check_added_monitors!(nodes[0], 1);
315 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
316 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
317 check_added_monitors!(nodes[1], 1);
319 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
320 check_added_monitors!(nodes[0], 1);
322 let events_2 = nodes[0].node.get_and_clear_pending_events();
323 assert_eq!(events_2.len(), 1);
325 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
326 _ => panic!("Unexpected event"),
329 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
330 check_added_monitors!(nodes[1], 1);
334 fn test_update_fee_unordered_raa() {
335 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
336 // crash in an earlier version of the update_fee patch)
337 let chanmon_cfgs = create_chanmon_cfgs(2);
338 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
339 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
340 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
341 create_announced_chan_between_nodes(&nodes, 0, 1);
344 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
346 // First nodes[0] generates an update_fee
348 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
351 nodes[0].node.timer_tick_occurred();
352 check_added_monitors!(nodes[0], 1);
354 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
355 assert_eq!(events_0.len(), 1);
356 let update_msg = match events_0[0] { // (1)
357 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
360 _ => panic!("Unexpected event"),
363 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
365 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
366 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
367 nodes[1].node.send_payment_with_route(&route, our_payment_hash,
368 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
369 check_added_monitors!(nodes[1], 1);
371 let payment_event = {
372 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
373 assert_eq!(events_1.len(), 1);
374 SendEvent::from_event(events_1.remove(0))
376 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
377 assert_eq!(payment_event.msgs.len(), 1);
379 // ...now when the messages get delivered everyone should be happy
380 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
381 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
382 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
383 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
384 check_added_monitors!(nodes[0], 1);
386 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
387 check_added_monitors!(nodes[1], 1);
389 // We can't continue, sadly, because our (1) now has a bogus signature
393 fn test_multi_flight_update_fee() {
394 let chanmon_cfgs = create_chanmon_cfgs(2);
395 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
396 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
397 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
398 create_announced_chan_between_nodes(&nodes, 0, 1);
401 // update_fee/commitment_signed ->
402 // .- send (1) RAA and (2) commitment_signed
403 // update_fee (never committed) ->
405 // We have to manually generate the above update_fee, it is allowed by the protocol but we
406 // don't track which updates correspond to which revoke_and_ack responses so we're in
407 // AwaitingRAA mode and will not generate the update_fee yet.
408 // <- (1) RAA delivered
409 // (3) is generated and send (4) CS -.
410 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
411 // know the per_commitment_point to use for it.
412 // <- (2) commitment_signed delivered
414 // B should send no response here
415 // (4) commitment_signed delivered ->
416 // <- RAA/commitment_signed delivered
419 // First nodes[0] generates an update_fee
422 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
423 initial_feerate = *feerate_lock;
424 *feerate_lock = initial_feerate + 20;
426 nodes[0].node.timer_tick_occurred();
427 check_added_monitors!(nodes[0], 1);
429 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
430 assert_eq!(events_0.len(), 1);
431 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
432 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
433 (update_fee.as_ref().unwrap(), commitment_signed)
435 _ => panic!("Unexpected event"),
438 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
439 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
440 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
441 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
442 check_added_monitors!(nodes[1], 1);
444 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
447 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
448 *feerate_lock = initial_feerate + 40;
450 nodes[0].node.timer_tick_occurred();
451 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
452 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
454 // Create the (3) update_fee message that nodes[0] will generate before it does...
455 let mut update_msg_2 = msgs::UpdateFee {
456 channel_id: update_msg_1.channel_id.clone(),
457 feerate_per_kw: (initial_feerate + 30) as u32,
460 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
462 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
464 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
466 // Deliver (1), generating (3) and (4)
467 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
468 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
469 check_added_monitors!(nodes[0], 1);
470 assert!(as_second_update.update_add_htlcs.is_empty());
471 assert!(as_second_update.update_fulfill_htlcs.is_empty());
472 assert!(as_second_update.update_fail_htlcs.is_empty());
473 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
474 // Check that the update_fee newly generated matches what we delivered:
475 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
476 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
478 // Deliver (2) commitment_signed
479 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
480 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
481 check_added_monitors!(nodes[0], 1);
482 // No commitment_signed so get_event_msg's assert(len == 1) passes
484 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
485 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
486 check_added_monitors!(nodes[1], 1);
489 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
490 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
491 check_added_monitors!(nodes[1], 1);
493 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
494 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
495 check_added_monitors!(nodes[0], 1);
497 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
498 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
499 // No commitment_signed so get_event_msg's assert(len == 1) passes
500 check_added_monitors!(nodes[0], 1);
502 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
503 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
504 check_added_monitors!(nodes[1], 1);
507 fn do_test_sanity_on_in_flight_opens(steps: u8) {
508 // Previously, we had issues deserializing channels when we hadn't connected the first block
509 // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
510 // serialization round-trips and simply do steps towards opening a channel and then drop the
513 let chanmon_cfgs = create_chanmon_cfgs(2);
514 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
515 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
516 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
518 if steps & 0b1000_0000 != 0{
519 let block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
520 connect_block(&nodes[0], &block);
521 connect_block(&nodes[1], &block);
524 if steps & 0x0f == 0 { return; }
525 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
526 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
528 if steps & 0x0f == 1 { return; }
529 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
530 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
532 if steps & 0x0f == 2 { return; }
533 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
535 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
537 if steps & 0x0f == 3 { return; }
538 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
539 check_added_monitors!(nodes[0], 0);
540 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
542 if steps & 0x0f == 4 { return; }
543 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
545 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
546 assert_eq!(added_monitors.len(), 1);
547 assert_eq!(added_monitors[0].0, funding_output);
548 added_monitors.clear();
550 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
552 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
554 if steps & 0x0f == 5 { return; }
555 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
557 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
558 assert_eq!(added_monitors.len(), 1);
559 assert_eq!(added_monitors[0].0, funding_output);
560 added_monitors.clear();
563 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
564 let events_4 = nodes[0].node.get_and_clear_pending_events();
565 assert_eq!(events_4.len(), 0);
567 if steps & 0x0f == 6 { return; }
568 create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
570 if steps & 0x0f == 7 { return; }
571 confirm_transaction_at(&nodes[0], &tx, 2);
572 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
573 create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
574 expect_channel_ready_event(&nodes[0], &nodes[1].node.get_our_node_id());
578 fn test_sanity_on_in_flight_opens() {
579 do_test_sanity_on_in_flight_opens(0);
580 do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
581 do_test_sanity_on_in_flight_opens(1);
582 do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
583 do_test_sanity_on_in_flight_opens(2);
584 do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
585 do_test_sanity_on_in_flight_opens(3);
586 do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
587 do_test_sanity_on_in_flight_opens(4);
588 do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
589 do_test_sanity_on_in_flight_opens(5);
590 do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
591 do_test_sanity_on_in_flight_opens(6);
592 do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
593 do_test_sanity_on_in_flight_opens(7);
594 do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
595 do_test_sanity_on_in_flight_opens(8);
596 do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
600 fn test_update_fee_vanilla() {
601 let chanmon_cfgs = create_chanmon_cfgs(2);
602 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
603 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
604 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
605 create_announced_chan_between_nodes(&nodes, 0, 1);
608 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
611 nodes[0].node.timer_tick_occurred();
612 check_added_monitors!(nodes[0], 1);
614 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
615 assert_eq!(events_0.len(), 1);
616 let (update_msg, commitment_signed) = match events_0[0] {
617 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 } } => {
618 (update_fee.as_ref(), commitment_signed)
620 _ => panic!("Unexpected event"),
622 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
624 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
625 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
626 check_added_monitors!(nodes[1], 1);
628 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
629 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
630 check_added_monitors!(nodes[0], 1);
632 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
633 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
634 // No commitment_signed so get_event_msg's assert(len == 1) passes
635 check_added_monitors!(nodes[0], 1);
637 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
638 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
639 check_added_monitors!(nodes[1], 1);
643 fn test_update_fee_that_funder_cannot_afford() {
644 let chanmon_cfgs = create_chanmon_cfgs(2);
645 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
646 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
647 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
648 let channel_value = 5000;
650 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000);
651 let channel_id = chan.2;
652 let secp_ctx = Secp256k1::new();
653 let default_config = UserConfig::default();
654 let bs_channel_reserve_sats = get_holder_selected_channel_reserve_satoshis(channel_value, &default_config);
656 let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
658 // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
659 // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
660 // calculate two different feerates here - the expected local limit as well as the expected
662 let feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / (commitment_tx_base_weight(&channel_type_features) + CONCURRENT_INBOUND_HTLC_FEE_BUFFER as u64 * COMMITMENT_TX_WEIGHT_PER_HTLC)) as u32;
663 let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(&channel_type_features)) as u32;
665 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
666 *feerate_lock = feerate;
668 nodes[0].node.timer_tick_occurred();
669 check_added_monitors!(nodes[0], 1);
670 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
672 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
674 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
676 // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
678 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
680 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
681 assert_eq!(commitment_tx.output.len(), 2);
682 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, &channel_type_features) / 1000;
683 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
684 actual_fee = channel_value - actual_fee;
685 assert_eq!(total_fee, actual_fee);
689 // Increment the feerate by a small constant, accounting for rounding errors
690 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
693 nodes[0].node.timer_tick_occurred();
694 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
695 check_added_monitors!(nodes[0], 0);
697 const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
699 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
700 // needed to sign the new commitment tx and (2) sign the new commitment tx.
701 let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
702 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
703 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
704 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
705 let chan_signer = local_chan.get_signer();
706 let pubkeys = chan_signer.pubkeys();
707 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
708 pubkeys.funding_pubkey)
710 let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
711 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
712 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
713 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
714 let chan_signer = remote_chan.get_signer();
715 let pubkeys = chan_signer.pubkeys();
716 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
717 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
718 pubkeys.funding_pubkey)
721 // Assemble the set of keys we can use for signatures for our commitment_signed message.
722 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
723 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
726 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
727 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
728 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
729 let local_chan_signer = local_chan.get_signer();
730 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
731 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
732 INITIAL_COMMITMENT_NUMBER - 1,
734 channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, &channel_type_features) / 1000,
735 local_funding, remote_funding,
736 commit_tx_keys.clone(),
737 non_buffer_feerate + 4,
739 &local_chan.context.channel_transaction_parameters.as_counterparty_broadcastable()
741 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
744 let commit_signed_msg = msgs::CommitmentSigned {
747 htlc_signatures: res.1,
749 partial_signature_with_nonce: None,
752 let update_fee = msgs::UpdateFee {
754 feerate_per_kw: non_buffer_feerate + 4,
757 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
759 //While producing the commitment_signed response after handling a received update_fee request the
760 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
761 //Should produce and error.
762 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
763 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
764 check_added_monitors!(nodes[1], 1);
765 check_closed_broadcast!(nodes[1], true);
766 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") },
767 [nodes[0].node.get_our_node_id()], channel_value);
771 fn test_update_fee_with_fundee_update_add_htlc() {
772 let chanmon_cfgs = create_chanmon_cfgs(2);
773 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
774 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
775 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
776 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
779 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
782 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
785 nodes[0].node.timer_tick_occurred();
786 check_added_monitors!(nodes[0], 1);
788 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
789 assert_eq!(events_0.len(), 1);
790 let (update_msg, commitment_signed) = match events_0[0] {
791 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 } } => {
792 (update_fee.as_ref(), commitment_signed)
794 _ => panic!("Unexpected event"),
796 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
797 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
798 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
799 check_added_monitors!(nodes[1], 1);
801 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
803 // nothing happens since node[1] is in AwaitingRemoteRevoke
804 nodes[1].node.send_payment_with_route(&route, our_payment_hash,
805 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
807 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
808 assert_eq!(added_monitors.len(), 0);
809 added_monitors.clear();
811 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
812 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
813 // node[1] has nothing to do
815 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
816 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
817 check_added_monitors!(nodes[0], 1);
819 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
820 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
821 // No commitment_signed so get_event_msg's assert(len == 1) passes
822 check_added_monitors!(nodes[0], 1);
823 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
824 check_added_monitors!(nodes[1], 1);
825 // AwaitingRemoteRevoke ends here
827 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
828 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
829 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
830 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
831 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
832 assert_eq!(commitment_update.update_fee.is_none(), true);
834 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
835 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
836 check_added_monitors!(nodes[0], 1);
837 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
839 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
840 check_added_monitors!(nodes[1], 1);
841 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
843 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
844 check_added_monitors!(nodes[1], 1);
845 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
846 // No commitment_signed so get_event_msg's assert(len == 1) passes
848 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
849 check_added_monitors!(nodes[0], 1);
850 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
852 expect_pending_htlcs_forwardable!(nodes[0]);
854 let events = nodes[0].node.get_and_clear_pending_events();
855 assert_eq!(events.len(), 1);
857 Event::PaymentClaimable { .. } => { },
858 _ => panic!("Unexpected event"),
861 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
863 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
864 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
865 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
866 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
867 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
871 fn test_update_fee() {
872 let chanmon_cfgs = create_chanmon_cfgs(2);
873 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
874 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
875 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
876 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
877 let channel_id = chan.2;
880 // (1) update_fee/commitment_signed ->
881 // <- (2) revoke_and_ack
882 // .- send (3) commitment_signed
883 // (4) update_fee/commitment_signed ->
884 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
885 // <- (3) commitment_signed delivered
886 // send (6) revoke_and_ack -.
887 // <- (5) deliver revoke_and_ack
888 // (6) deliver revoke_and_ack ->
889 // .- send (7) commitment_signed in response to (4)
890 // <- (7) deliver commitment_signed
893 // Create and deliver (1)...
896 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
897 feerate = *feerate_lock;
898 *feerate_lock = feerate + 20;
900 nodes[0].node.timer_tick_occurred();
901 check_added_monitors!(nodes[0], 1);
903 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
904 assert_eq!(events_0.len(), 1);
905 let (update_msg, commitment_signed) = match events_0[0] {
906 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 } } => {
907 (update_fee.as_ref(), commitment_signed)
909 _ => panic!("Unexpected event"),
911 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
913 // Generate (2) and (3):
914 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
915 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
916 check_added_monitors!(nodes[1], 1);
919 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
920 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
921 check_added_monitors!(nodes[0], 1);
923 // Create and deliver (4)...
925 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
926 *feerate_lock = feerate + 30;
928 nodes[0].node.timer_tick_occurred();
929 check_added_monitors!(nodes[0], 1);
930 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
931 assert_eq!(events_0.len(), 1);
932 let (update_msg, commitment_signed) = match events_0[0] {
933 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 } } => {
934 (update_fee.as_ref(), commitment_signed)
936 _ => panic!("Unexpected event"),
939 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
940 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
941 check_added_monitors!(nodes[1], 1);
943 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
944 // No commitment_signed so get_event_msg's assert(len == 1) passes
946 // Handle (3), creating (6):
947 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
948 check_added_monitors!(nodes[0], 1);
949 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
950 // No commitment_signed so get_event_msg's assert(len == 1) passes
953 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
954 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
955 check_added_monitors!(nodes[0], 1);
957 // Deliver (6), creating (7):
958 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
959 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
960 assert!(commitment_update.update_add_htlcs.is_empty());
961 assert!(commitment_update.update_fulfill_htlcs.is_empty());
962 assert!(commitment_update.update_fail_htlcs.is_empty());
963 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
964 assert!(commitment_update.update_fee.is_none());
965 check_added_monitors!(nodes[1], 1);
968 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
969 check_added_monitors!(nodes[0], 1);
970 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
971 // No commitment_signed so get_event_msg's assert(len == 1) passes
973 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
974 check_added_monitors!(nodes[1], 1);
975 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
977 assert_eq!(get_feerate!(nodes[0], nodes[1], channel_id), feerate + 30);
978 assert_eq!(get_feerate!(nodes[1], nodes[0], channel_id), feerate + 30);
979 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
980 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
981 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
985 fn fake_network_test() {
986 // Simple test which builds a network of ChannelManagers, connects them to each other, and
987 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
988 let chanmon_cfgs = create_chanmon_cfgs(4);
989 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
990 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
991 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
993 // Create some initial channels
994 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
995 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
996 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
998 // Rebalance the network a bit by relaying one payment through all the channels...
999 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1000 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1001 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1002 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1004 // Send some more payments
1005 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
1006 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
1007 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
1009 // Test failure packets
1010 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1011 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1013 // Add a new channel that skips 3
1014 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
1016 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
1017 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
1018 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1019 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1020 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1021 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1022 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1024 // Do some rebalance loop payments, simultaneously
1025 let mut hops = Vec::with_capacity(3);
1026 hops.push(RouteHop {
1027 pubkey: nodes[2].node.get_our_node_id(),
1028 node_features: NodeFeatures::empty(),
1029 short_channel_id: chan_2.0.contents.short_channel_id,
1030 channel_features: ChannelFeatures::empty(),
1032 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1034 hops.push(RouteHop {
1035 pubkey: nodes[3].node.get_our_node_id(),
1036 node_features: NodeFeatures::empty(),
1037 short_channel_id: chan_3.0.contents.short_channel_id,
1038 channel_features: ChannelFeatures::empty(),
1040 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1042 hops.push(RouteHop {
1043 pubkey: nodes[1].node.get_our_node_id(),
1044 node_features: nodes[1].node.node_features(),
1045 short_channel_id: chan_4.0.contents.short_channel_id,
1046 channel_features: nodes[1].node.channel_features(),
1048 cltv_expiry_delta: TEST_FINAL_CLTV,
1050 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;
1051 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;
1052 let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![Path { hops, blinded_tail: None }], payment_params: None }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1054 let mut hops = Vec::with_capacity(3);
1055 hops.push(RouteHop {
1056 pubkey: nodes[3].node.get_our_node_id(),
1057 node_features: NodeFeatures::empty(),
1058 short_channel_id: chan_4.0.contents.short_channel_id,
1059 channel_features: ChannelFeatures::empty(),
1061 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1063 hops.push(RouteHop {
1064 pubkey: nodes[2].node.get_our_node_id(),
1065 node_features: NodeFeatures::empty(),
1066 short_channel_id: chan_3.0.contents.short_channel_id,
1067 channel_features: ChannelFeatures::empty(),
1069 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1071 hops.push(RouteHop {
1072 pubkey: nodes[1].node.get_our_node_id(),
1073 node_features: nodes[1].node.node_features(),
1074 short_channel_id: chan_2.0.contents.short_channel_id,
1075 channel_features: nodes[1].node.channel_features(),
1077 cltv_expiry_delta: TEST_FINAL_CLTV,
1079 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;
1080 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;
1081 let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![Path { hops, blinded_tail: None }], payment_params: None }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1083 // Claim the rebalances...
1084 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1085 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1087 // Close down the channels...
1088 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1089 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1090 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
1091 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1092 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[2].node.get_our_node_id()], 100000);
1093 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1094 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1095 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure, [nodes[3].node.get_our_node_id()], 100000);
1096 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure, [nodes[2].node.get_our_node_id()], 100000);
1097 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1098 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[3].node.get_our_node_id()], 100000);
1099 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1103 fn holding_cell_htlc_counting() {
1104 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1105 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1106 // commitment dance rounds.
1107 let chanmon_cfgs = create_chanmon_cfgs(3);
1108 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1109 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1110 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1111 create_announced_chan_between_nodes(&nodes, 0, 1);
1112 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1114 // Fetch a route in advance as we will be unable to once we're unable to send.
1115 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1117 let mut payments = Vec::new();
1119 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1120 nodes[1].node.send_payment_with_route(&route, payment_hash,
1121 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1122 payments.push((payment_preimage, payment_hash));
1124 check_added_monitors!(nodes[1], 1);
1126 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1127 assert_eq!(events.len(), 1);
1128 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1129 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1131 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1132 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1135 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, payment_hash_1,
1136 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)
1137 ), true, APIError::ChannelUnavailable { .. }, {});
1138 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1141 // This should also be true if we try to forward a payment.
1142 let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1144 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1145 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1146 check_added_monitors!(nodes[0], 1);
1149 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1150 assert_eq!(events.len(), 1);
1151 let payment_event = SendEvent::from_event(events.pop().unwrap());
1152 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1154 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1155 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1156 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1157 // fails), the second will process the resulting failure and fail the HTLC backward.
1158 expect_pending_htlcs_forwardable!(nodes[1]);
1159 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
1160 check_added_monitors!(nodes[1], 1);
1162 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1163 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1164 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1166 expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1168 // Now forward all the pending HTLCs and claim them back
1169 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1170 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1171 check_added_monitors!(nodes[2], 1);
1173 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1174 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1175 check_added_monitors!(nodes[1], 1);
1176 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1178 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1179 check_added_monitors!(nodes[1], 1);
1180 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1182 for ref update in as_updates.update_add_htlcs.iter() {
1183 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1185 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1186 check_added_monitors!(nodes[2], 1);
1187 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1188 check_added_monitors!(nodes[2], 1);
1189 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1191 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1192 check_added_monitors!(nodes[1], 1);
1193 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1194 check_added_monitors!(nodes[1], 1);
1195 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1197 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1198 check_added_monitors!(nodes[2], 1);
1200 expect_pending_htlcs_forwardable!(nodes[2]);
1202 let events = nodes[2].node.get_and_clear_pending_events();
1203 assert_eq!(events.len(), payments.len());
1204 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1206 &Event::PaymentClaimable { ref payment_hash, .. } => {
1207 assert_eq!(*payment_hash, *hash);
1209 _ => panic!("Unexpected event"),
1213 for (preimage, _) in payments.drain(..) {
1214 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1217 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1221 fn duplicate_htlc_test() {
1222 // Test that we accept duplicate payment_hash HTLCs across the network and that
1223 // claiming/failing them are all separate and don't affect each other
1224 let chanmon_cfgs = create_chanmon_cfgs(6);
1225 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1226 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1227 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1229 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1230 create_announced_chan_between_nodes(&nodes, 0, 3);
1231 create_announced_chan_between_nodes(&nodes, 1, 3);
1232 create_announced_chan_between_nodes(&nodes, 2, 3);
1233 create_announced_chan_between_nodes(&nodes, 3, 4);
1234 create_announced_chan_between_nodes(&nodes, 3, 5);
1236 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1238 *nodes[0].network_payment_count.borrow_mut() -= 1;
1239 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1241 *nodes[0].network_payment_count.borrow_mut() -= 1;
1242 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1244 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1245 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1246 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1250 fn test_duplicate_htlc_different_direction_onchain() {
1251 // Test that ChannelMonitor doesn't generate 2 preimage txn
1252 // when we have 2 HTLCs with same preimage that go across a node
1253 // in opposite directions, even with the same payment secret.
1254 let chanmon_cfgs = create_chanmon_cfgs(2);
1255 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1256 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1257 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1259 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1262 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1264 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1266 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1267 let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
1268 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1270 // Provide preimage to node 0 by claiming payment
1271 nodes[0].node.claim_funds(payment_preimage);
1272 expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1273 check_added_monitors!(nodes[0], 1);
1275 // Broadcast node 1 commitment txn
1276 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1278 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1279 let mut has_both_htlcs = 0; // check htlcs match ones committed
1280 for outp in remote_txn[0].output.iter() {
1281 if outp.value == 800_000 / 1000 {
1282 has_both_htlcs += 1;
1283 } else if outp.value == 900_000 / 1000 {
1284 has_both_htlcs += 1;
1287 assert_eq!(has_both_htlcs, 2);
1289 mine_transaction(&nodes[0], &remote_txn[0]);
1290 check_added_monitors!(nodes[0], 1);
1291 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
1292 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
1294 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1295 assert_eq!(claim_txn.len(), 3);
1297 check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1298 check_spends!(claim_txn[1], remote_txn[0]);
1299 check_spends!(claim_txn[2], remote_txn[0]);
1300 let preimage_tx = &claim_txn[0];
1301 let (preimage_bump_tx, timeout_tx) = if claim_txn[1].input[0].previous_output == preimage_tx.input[0].previous_output {
1302 (&claim_txn[1], &claim_txn[2])
1304 (&claim_txn[2], &claim_txn[1])
1307 assert_eq!(preimage_tx.input.len(), 1);
1308 assert_eq!(preimage_bump_tx.input.len(), 1);
1310 assert_eq!(preimage_tx.input.len(), 1);
1311 assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1312 assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1314 assert_eq!(timeout_tx.input.len(), 1);
1315 assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1316 check_spends!(timeout_tx, remote_txn[0]);
1317 assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1319 let events = nodes[0].node.get_and_clear_pending_msg_events();
1320 assert_eq!(events.len(), 3);
1323 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1324 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1325 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1326 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1328 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, .. } } => {
1329 assert!(update_add_htlcs.is_empty());
1330 assert!(update_fail_htlcs.is_empty());
1331 assert_eq!(update_fulfill_htlcs.len(), 1);
1332 assert!(update_fail_malformed_htlcs.is_empty());
1333 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1335 _ => panic!("Unexpected event"),
1341 fn test_basic_channel_reserve() {
1342 let chanmon_cfgs = create_chanmon_cfgs(2);
1343 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1344 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1345 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1346 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1348 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1349 let channel_reserve = chan_stat.channel_reserve_msat;
1351 // The 2* and +1 are for the fee spike reserve.
1352 let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], nodes[1], chan.2), 1 + 1, &get_channel_type_features!(nodes[0], nodes[1], chan.2));
1353 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1354 let (mut route, our_payment_hash, _, our_payment_secret) =
1355 get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
1356 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1357 let err = nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1358 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1360 PaymentSendFailure::AllFailedResendSafe(ref fails) => {
1361 if let &APIError::ChannelUnavailable { .. } = &fails[0] {}
1362 else { panic!("Unexpected error variant"); }
1364 _ => panic!("Unexpected error variant"),
1366 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1368 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1372 fn test_fee_spike_violation_fails_htlc() {
1373 let chanmon_cfgs = create_chanmon_cfgs(2);
1374 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1375 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1376 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1377 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1379 let (mut route, payment_hash, _, payment_secret) =
1380 get_route_and_payment_hash!(nodes[0], nodes[1], 3460000);
1381 route.paths[0].hops[0].fee_msat += 1;
1382 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1383 let secp_ctx = Secp256k1::new();
1384 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1386 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1388 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1389 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1390 3460001, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1391 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1392 let msg = msgs::UpdateAddHTLC {
1395 amount_msat: htlc_msat,
1396 payment_hash: payment_hash,
1397 cltv_expiry: htlc_cltv,
1398 onion_routing_packet: onion_packet,
1399 skimmed_fee_msat: None,
1402 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1404 // Now manually create the commitment_signed message corresponding to the update_add
1405 // nodes[0] just sent. In the code for construction of this message, "local" refers
1406 // to the sender of the message, and "remote" refers to the receiver.
1408 let feerate_per_kw = get_feerate!(nodes[0], nodes[1], chan.2);
1410 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1412 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1413 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1414 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1415 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1416 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1417 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1418 let chan_signer = local_chan.get_signer();
1419 // Make the signer believe we validated another commitment, so we can release the secret
1420 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1422 let pubkeys = chan_signer.pubkeys();
1423 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1424 chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1425 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1426 chan_signer.pubkeys().funding_pubkey)
1428 let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1429 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
1430 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
1431 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1432 let chan_signer = remote_chan.get_signer();
1433 let pubkeys = chan_signer.pubkeys();
1434 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1435 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1436 chan_signer.pubkeys().funding_pubkey)
1439 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1440 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1441 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
1443 // Build the remote commitment transaction so we can sign it, and then later use the
1444 // signature for the commitment_signed message.
1445 let local_chan_balance = 1313;
1447 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1449 amount_msat: 3460001,
1450 cltv_expiry: htlc_cltv,
1452 transaction_output_index: Some(1),
1455 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1458 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1459 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1460 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
1461 let local_chan_signer = local_chan.get_signer();
1462 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1466 local_funding, remote_funding,
1467 commit_tx_keys.clone(),
1469 &mut vec![(accepted_htlc_info, ())],
1470 &local_chan.context.channel_transaction_parameters.as_counterparty_broadcastable()
1472 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1475 let commit_signed_msg = msgs::CommitmentSigned {
1478 htlc_signatures: res.1,
1480 partial_signature_with_nonce: None,
1483 // Send the commitment_signed message to the nodes[1].
1484 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1485 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1487 // Send the RAA to nodes[1].
1488 let raa_msg = msgs::RevokeAndACK {
1490 per_commitment_secret: local_secret,
1491 next_per_commitment_point: next_local_point,
1493 next_local_nonce: None,
1495 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1497 let events = nodes[1].node.get_and_clear_pending_msg_events();
1498 assert_eq!(events.len(), 1);
1499 // Make sure the HTLC failed in the way we expect.
1501 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1502 assert_eq!(update_fail_htlcs.len(), 1);
1503 update_fail_htlcs[0].clone()
1505 _ => panic!("Unexpected event"),
1507 nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1508 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1510 check_added_monitors!(nodes[1], 2);
1514 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1515 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1516 // Set the fee rate for the channel very high, to the point where the fundee
1517 // sending any above-dust amount would result in a channel reserve violation.
1518 // In this test we check that we would be prevented from sending an HTLC in
1520 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1521 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1522 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1523 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1524 let default_config = UserConfig::default();
1525 let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1527 let mut push_amt = 100_000_000;
1528 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1530 push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1532 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1534 // Fetch a route in advance as we will be unable to once we're unable to send.
1535 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1536 // Sending exactly enough to hit the reserve amount should be accepted
1537 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1538 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1541 // However one more HTLC should be significantly over the reserve amount and fail.
1542 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1543 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1544 ), true, APIError::ChannelUnavailable { .. }, {});
1545 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1549 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1550 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1551 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1552 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1553 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1554 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1555 let default_config = UserConfig::default();
1556 let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1558 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1559 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1560 // transaction fee with 0 HTLCs (183 sats)).
1561 let mut push_amt = 100_000_000;
1562 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1563 push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1564 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1566 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1567 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1568 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1571 let (mut route, payment_hash, _, payment_secret) =
1572 get_route_and_payment_hash!(nodes[1], nodes[0], 1000);
1573 route.paths[0].hops[0].fee_msat = 700_000;
1574 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1575 let secp_ctx = Secp256k1::new();
1576 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1577 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1578 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1579 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1580 700_000, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1581 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1582 let msg = msgs::UpdateAddHTLC {
1584 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1585 amount_msat: htlc_msat,
1586 payment_hash: payment_hash,
1587 cltv_expiry: htlc_cltv,
1588 onion_routing_packet: onion_packet,
1589 skimmed_fee_msat: None,
1592 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1593 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1594 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value".to_string(), 1);
1595 assert_eq!(nodes[0].node.list_channels().len(), 0);
1596 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1597 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1598 check_added_monitors!(nodes[0], 1);
1599 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value".to_string() },
1600 [nodes[1].node.get_our_node_id()], 100000);
1604 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1605 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1606 // calculating our commitment transaction fee (this was previously broken).
1607 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1608 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1610 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1611 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1612 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1613 let default_config = UserConfig::default();
1614 let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1616 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1617 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1618 // transaction fee with 0 HTLCs (183 sats)).
1619 let mut push_amt = 100_000_000;
1620 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1621 push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1622 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt);
1624 let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1625 + feerate_per_kw as u64 * htlc_success_tx_weight(&channel_type_features) / 1000 * 1000 - 1;
1626 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1627 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1628 // commitment transaction fee.
1629 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1631 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1632 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1633 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1636 // One more than the dust amt should fail, however.
1637 let (mut route, our_payment_hash, _, our_payment_secret) =
1638 get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt);
1639 route.paths[0].hops[0].fee_msat += 1;
1640 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1641 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1642 ), true, APIError::ChannelUnavailable { .. }, {});
1646 fn test_chan_init_feerate_unaffordability() {
1647 // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1648 // channel reserve and feerate requirements.
1649 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1650 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1651 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1652 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1653 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1654 let default_config = UserConfig::default();
1655 let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1657 // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1659 let mut push_amt = 100_000_000;
1660 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1661 assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1662 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1664 // During open, we don't have a "counterparty channel reserve" to check against, so that
1665 // requirement only comes into play on the open_channel handling side.
1666 push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1667 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1668 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1669 open_channel_msg.push_msat += 1;
1670 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
1672 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1673 assert_eq!(msg_events.len(), 1);
1674 match msg_events[0] {
1675 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1676 assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1678 _ => panic!("Unexpected event"),
1683 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1684 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1685 // calculating our counterparty's commitment transaction fee (this was previously broken).
1686 let chanmon_cfgs = create_chanmon_cfgs(2);
1687 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1688 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1689 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1690 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000);
1692 let payment_amt = 46000; // Dust amount
1693 // In the previous code, these first four payments would succeed.
1694 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1695 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1696 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1697 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1699 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1700 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1701 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1702 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1703 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1704 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1706 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1707 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1708 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1709 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1713 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1714 let chanmon_cfgs = create_chanmon_cfgs(3);
1715 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1716 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1717 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1718 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1719 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
1722 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1723 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1724 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
1725 let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
1727 // Add a 2* and +1 for the fee spike reserve.
1728 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features);
1729 let recv_value_1 = (chan_stat.value_to_self_msat - chan_stat.channel_reserve_msat - total_routing_fee_msat - commit_tx_fee_2_htlc)/2;
1730 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1732 // Add a pending HTLC.
1733 let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1734 let payment_event_1 = {
1735 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1736 RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1737 check_added_monitors!(nodes[0], 1);
1739 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1740 assert_eq!(events.len(), 1);
1741 SendEvent::from_event(events.remove(0))
1743 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1745 // Attempt to trigger a channel reserve violation --> payment failure.
1746 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, &channel_type_features);
1747 let recv_value_2 = chan_stat.value_to_self_msat - amt_msat_1 - chan_stat.channel_reserve_msat - total_routing_fee_msat - commit_tx_fee_2_htlcs + 1;
1748 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1749 let mut route_2 = route_1.clone();
1750 route_2.paths[0].hops.last_mut().unwrap().fee_msat = amt_msat_2;
1752 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1753 let secp_ctx = Secp256k1::new();
1754 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1755 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1756 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1757 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
1758 &route_2.paths[0], recv_value_2, RecipientOnionFields::spontaneous_empty(), cur_height, &None).unwrap();
1759 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1).unwrap();
1760 let msg = msgs::UpdateAddHTLC {
1763 amount_msat: htlc_msat + 1,
1764 payment_hash: our_payment_hash_1,
1765 cltv_expiry: htlc_cltv,
1766 onion_routing_packet: onion_packet,
1767 skimmed_fee_msat: None,
1770 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1771 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1772 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1773 assert_eq!(nodes[1].node.list_channels().len(), 1);
1774 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1775 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1776 check_added_monitors!(nodes[1], 1);
1777 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() },
1778 [nodes[0].node.get_our_node_id()], 100000);
1782 fn test_inbound_outbound_capacity_is_not_zero() {
1783 let chanmon_cfgs = create_chanmon_cfgs(2);
1784 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1785 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1786 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1787 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1788 let channels0 = node_chanmgrs[0].list_channels();
1789 let channels1 = node_chanmgrs[1].list_channels();
1790 let default_config = UserConfig::default();
1791 assert_eq!(channels0.len(), 1);
1792 assert_eq!(channels1.len(), 1);
1794 let reserve = get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1795 assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1796 assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1798 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1799 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1802 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, channel_type_features: &ChannelTypeFeatures) -> u64 {
1803 (commitment_tx_base_weight(channel_type_features) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1807 fn test_channel_reserve_holding_cell_htlcs() {
1808 let chanmon_cfgs = create_chanmon_cfgs(3);
1809 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1810 // When this test was written, the default base fee floated based on the HTLC count.
1811 // It is now fixed, so we simply set the fee to the expected value here.
1812 let mut config = test_default_channel_config();
1813 config.channel_config.forwarding_fee_base_msat = 239;
1814 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1815 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1816 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001);
1817 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001);
1819 let mut stat01 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1820 let mut stat11 = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
1822 let mut stat12 = get_channel_value_stat!(nodes[1], nodes[2], chan_2.2);
1823 let mut stat22 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
1825 macro_rules! expect_forward {
1827 let mut events = $node.node.get_and_clear_pending_msg_events();
1828 assert_eq!(events.len(), 1);
1829 check_added_monitors!($node, 1);
1830 let payment_event = SendEvent::from_event(events.remove(0));
1835 let feemsat = 239; // set above
1836 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1837 let feerate = get_feerate!(nodes[0], nodes[1], chan_1.2);
1838 let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_1.2);
1840 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1842 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1844 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1845 .with_bolt11_features(nodes[2].node.invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1846 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, recv_value_0);
1847 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1848 assert!(route.paths[0].hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1850 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1851 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1852 ), true, APIError::ChannelUnavailable { .. }, {});
1853 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1856 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1857 // nodes[0]'s wealth
1859 let amt_msat = recv_value_0 + total_fee_msat;
1860 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1861 // Also, ensure that each payment has enough to be over the dust limit to
1862 // ensure it'll be included in each commit tx fee calculation.
1863 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, &channel_type_features);
1864 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1865 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1869 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1870 .with_bolt11_features(nodes[2].node.invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1871 let route = get_route!(nodes[0], payment_params, recv_value_0).unwrap();
1872 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1873 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1875 let (stat01_, stat11_, stat12_, stat22_) = (
1876 get_channel_value_stat!(nodes[0], nodes[1], chan_1.2),
1877 get_channel_value_stat!(nodes[1], nodes[0], chan_1.2),
1878 get_channel_value_stat!(nodes[1], nodes[2], chan_2.2),
1879 get_channel_value_stat!(nodes[2], nodes[1], chan_2.2),
1882 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1883 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1884 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1885 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1886 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1889 // adding pending output.
1890 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1891 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1892 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1893 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1894 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1895 // cases where 1 msat over X amount will cause a payment failure, but anything less than
1896 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1897 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1898 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1900 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features);
1901 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1902 let amt_msat_1 = recv_value_1 + total_fee_msat;
1904 let (route_1, our_payment_hash_1, our_payment_preimage_1, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_1);
1905 let payment_event_1 = {
1906 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1907 RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1908 check_added_monitors!(nodes[0], 1);
1910 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1911 assert_eq!(events.len(), 1);
1912 SendEvent::from_event(events.remove(0))
1914 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1916 // channel reserve test with htlc pending output > 0
1917 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1919 let mut route = route_1.clone();
1920 route.paths[0].hops.last_mut().unwrap().fee_msat = recv_value_2 + 1;
1921 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
1922 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1923 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1924 ), true, APIError::ChannelUnavailable { .. }, {});
1925 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1928 // split the rest to test holding cell
1929 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, &channel_type_features);
1930 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1931 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1932 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1934 let stat = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1935 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 + commit_tx_fee_3_htlcs), stat.channel_reserve_msat);
1938 // now see if they go through on both sides
1939 let (route_21, our_payment_hash_21, our_payment_preimage_21, our_payment_secret_21) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_21);
1940 // but this will stuck in the holding cell
1941 nodes[0].node.send_payment_with_route(&route_21, our_payment_hash_21,
1942 RecipientOnionFields::secret_only(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
1943 check_added_monitors!(nodes[0], 0);
1944 let events = nodes[0].node.get_and_clear_pending_events();
1945 assert_eq!(events.len(), 0);
1947 // test with outbound holding cell amount > 0
1949 let (mut route, our_payment_hash, _, our_payment_secret) =
1950 get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22);
1951 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1952 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1953 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1954 ), true, APIError::ChannelUnavailable { .. }, {});
1955 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1958 let (route_22, our_payment_hash_22, our_payment_preimage_22, our_payment_secret_22) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22);
1959 // this will also stuck in the holding cell
1960 nodes[0].node.send_payment_with_route(&route_22, our_payment_hash_22,
1961 RecipientOnionFields::secret_only(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
1962 check_added_monitors!(nodes[0], 0);
1963 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1964 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1966 // flush the pending htlc
1967 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1968 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1969 check_added_monitors!(nodes[1], 1);
1971 // the pending htlc should be promoted to committed
1972 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1973 check_added_monitors!(nodes[0], 1);
1974 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1976 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1977 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1978 // No commitment_signed so get_event_msg's assert(len == 1) passes
1979 check_added_monitors!(nodes[0], 1);
1981 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1982 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1983 check_added_monitors!(nodes[1], 1);
1985 expect_pending_htlcs_forwardable!(nodes[1]);
1987 let ref payment_event_11 = expect_forward!(nodes[1]);
1988 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1989 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1991 expect_pending_htlcs_forwardable!(nodes[2]);
1992 expect_payment_claimable!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1994 // flush the htlcs in the holding cell
1995 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1996 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1997 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1998 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1999 expect_pending_htlcs_forwardable!(nodes[1]);
2001 let ref payment_event_3 = expect_forward!(nodes[1]);
2002 assert_eq!(payment_event_3.msgs.len(), 2);
2003 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
2004 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
2006 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2007 expect_pending_htlcs_forwardable!(nodes[2]);
2009 let events = nodes[2].node.get_and_clear_pending_events();
2010 assert_eq!(events.len(), 2);
2012 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2013 assert_eq!(our_payment_hash_21, *payment_hash);
2014 assert_eq!(recv_value_21, amount_msat);
2015 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2016 assert_eq!(via_channel_id, Some(chan_2.2));
2018 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2019 assert!(payment_preimage.is_none());
2020 assert_eq!(our_payment_secret_21, *payment_secret);
2022 _ => panic!("expected PaymentPurpose::InvoicePayment")
2025 _ => panic!("Unexpected event"),
2028 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2029 assert_eq!(our_payment_hash_22, *payment_hash);
2030 assert_eq!(recv_value_22, amount_msat);
2031 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2032 assert_eq!(via_channel_id, Some(chan_2.2));
2034 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2035 assert!(payment_preimage.is_none());
2036 assert_eq!(our_payment_secret_22, *payment_secret);
2038 _ => panic!("expected PaymentPurpose::InvoicePayment")
2041 _ => panic!("Unexpected event"),
2044 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2045 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2046 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2048 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, &channel_type_features);
2049 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2050 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2052 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
2053 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) - (recv_value_3 + total_fee_msat);
2054 let stat0 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
2055 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2056 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2058 let stat2 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
2059 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2063 fn channel_reserve_in_flight_removes() {
2064 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2065 // can send to its counterparty, but due to update ordering, the other side may not yet have
2066 // considered those HTLCs fully removed.
2067 // This tests that we don't count HTLCs which will not be included in the next remote
2068 // commitment transaction towards the reserve value (as it implies no commitment transaction
2069 // will be generated which violates the remote reserve value).
2070 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2072 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2073 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2074 // you only consider the value of the first HTLC, it may not),
2075 // * start routing a third HTLC from A to B,
2076 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2077 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2078 // * deliver the first fulfill from B
2079 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2081 // * deliver A's response CS and RAA.
2082 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2083 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
2084 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2085 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2086 let chanmon_cfgs = create_chanmon_cfgs(2);
2087 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2088 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2089 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2090 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2092 let b_chan_values = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
2093 // Route the first two HTLCs.
2094 let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2095 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2096 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2098 // Start routing the third HTLC (this is just used to get everyone in the right state).
2099 let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2101 nodes[0].node.send_payment_with_route(&route, payment_hash_3,
2102 RecipientOnionFields::secret_only(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2103 check_added_monitors!(nodes[0], 1);
2104 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2105 assert_eq!(events.len(), 1);
2106 SendEvent::from_event(events.remove(0))
2109 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2110 // initial fulfill/CS.
2111 nodes[1].node.claim_funds(payment_preimage_1);
2112 expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2113 check_added_monitors!(nodes[1], 1);
2114 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2116 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2117 // remove the second HTLC when we send the HTLC back from B to A.
2118 nodes[1].node.claim_funds(payment_preimage_2);
2119 expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2120 check_added_monitors!(nodes[1], 1);
2121 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2123 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2124 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2125 check_added_monitors!(nodes[0], 1);
2126 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2127 expect_payment_sent(&nodes[0], payment_preimage_1, None, false, false);
2129 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2130 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2131 check_added_monitors!(nodes[1], 1);
2132 // B is already AwaitingRAA, so cant generate a CS here
2133 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2135 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2136 check_added_monitors!(nodes[1], 1);
2137 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2139 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2140 check_added_monitors!(nodes[0], 1);
2141 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2143 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2144 check_added_monitors!(nodes[1], 1);
2145 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2147 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2148 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2149 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2150 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2151 // on-chain as necessary).
2152 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2153 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2154 check_added_monitors!(nodes[0], 1);
2155 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2156 expect_payment_sent(&nodes[0], payment_preimage_2, None, false, false);
2158 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2159 check_added_monitors!(nodes[1], 1);
2160 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2162 expect_pending_htlcs_forwardable!(nodes[1]);
2163 expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2165 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2166 // resolve the second HTLC from A's point of view.
2167 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2168 check_added_monitors!(nodes[0], 1);
2169 expect_payment_path_successful!(nodes[0]);
2170 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2172 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2173 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2174 let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2176 nodes[1].node.send_payment_with_route(&route, payment_hash_4,
2177 RecipientOnionFields::secret_only(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2178 check_added_monitors!(nodes[1], 1);
2179 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2180 assert_eq!(events.len(), 1);
2181 SendEvent::from_event(events.remove(0))
2184 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2185 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2186 check_added_monitors!(nodes[0], 1);
2187 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2189 // Now just resolve all the outstanding messages/HTLCs for completeness...
2191 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2192 check_added_monitors!(nodes[1], 1);
2193 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2195 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2196 check_added_monitors!(nodes[1], 1);
2198 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2199 check_added_monitors!(nodes[0], 1);
2200 expect_payment_path_successful!(nodes[0]);
2201 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2203 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2204 check_added_monitors!(nodes[1], 1);
2205 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2207 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2208 check_added_monitors!(nodes[0], 1);
2210 expect_pending_htlcs_forwardable!(nodes[0]);
2211 expect_payment_claimable!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2213 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2214 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2218 fn channel_monitor_network_test() {
2219 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2220 // tests that ChannelMonitor is able to recover from various states.
2221 let chanmon_cfgs = create_chanmon_cfgs(5);
2222 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2223 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2224 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2226 // Create some initial channels
2227 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2228 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2229 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2230 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
2232 // Make sure all nodes are at the same starting height
2233 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2234 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2235 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2236 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2237 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2239 // Rebalance the network a bit by relaying one payment through all the channels...
2240 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2241 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2242 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2243 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2245 // Simple case with no pending HTLCs:
2246 nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2247 check_added_monitors!(nodes[1], 1);
2248 check_closed_broadcast!(nodes[1], true);
2250 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2251 assert_eq!(node_txn.len(), 1);
2252 mine_transaction(&nodes[0], &node_txn[0]);
2253 check_added_monitors!(nodes[0], 1);
2254 test_txn_broadcast(&nodes[0], &chan_1, Some(node_txn[0].clone()), HTLCType::NONE);
2256 check_closed_broadcast!(nodes[0], true);
2257 assert_eq!(nodes[0].node.list_channels().len(), 0);
2258 assert_eq!(nodes[1].node.list_channels().len(), 1);
2259 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2260 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[0].node.get_our_node_id()], 100000);
2262 // One pending HTLC is discarded by the force-close:
2263 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2265 // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2266 // broadcasted until we reach the timelock time).
2267 nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2268 check_closed_broadcast!(nodes[1], true);
2269 check_added_monitors!(nodes[1], 1);
2271 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2272 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2273 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2274 mine_transaction(&nodes[2], &node_txn[0]);
2275 check_added_monitors!(nodes[2], 1);
2276 test_txn_broadcast(&nodes[2], &chan_2, Some(node_txn[0].clone()), HTLCType::NONE);
2278 check_closed_broadcast!(nodes[2], true);
2279 assert_eq!(nodes[1].node.list_channels().len(), 0);
2280 assert_eq!(nodes[2].node.list_channels().len(), 1);
2281 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[2].node.get_our_node_id()], 100000);
2282 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2284 macro_rules! claim_funds {
2285 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2287 $node.node.claim_funds($preimage);
2288 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2289 check_added_monitors!($node, 1);
2291 let events = $node.node.get_and_clear_pending_msg_events();
2292 assert_eq!(events.len(), 1);
2294 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2295 assert!(update_add_htlcs.is_empty());
2296 assert!(update_fail_htlcs.is_empty());
2297 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2299 _ => panic!("Unexpected event"),
2305 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2306 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2307 nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2308 check_added_monitors!(nodes[2], 1);
2309 check_closed_broadcast!(nodes[2], true);
2310 let node2_commitment_txid;
2312 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2313 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2314 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2315 node2_commitment_txid = node_txn[0].txid();
2317 // Claim the payment on nodes[3], giving it knowledge of the preimage
2318 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2319 mine_transaction(&nodes[3], &node_txn[0]);
2320 check_added_monitors!(nodes[3], 1);
2321 check_preimage_claim(&nodes[3], &node_txn);
2323 check_closed_broadcast!(nodes[3], true);
2324 assert_eq!(nodes[2].node.list_channels().len(), 0);
2325 assert_eq!(nodes[3].node.list_channels().len(), 1);
2326 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed, [nodes[3].node.get_our_node_id()], 100000);
2327 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
2329 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2330 // confusing us in the following tests.
2331 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2333 // One pending HTLC to time out:
2334 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2335 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2338 let (close_chan_update_1, close_chan_update_2) = {
2339 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2340 let events = nodes[3].node.get_and_clear_pending_msg_events();
2341 assert_eq!(events.len(), 2);
2342 let close_chan_update_1 = match events[0] {
2343 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2346 _ => panic!("Unexpected event"),
2349 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2350 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2352 _ => panic!("Unexpected event"),
2354 check_added_monitors!(nodes[3], 1);
2356 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2358 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2359 node_txn.retain(|tx| {
2360 if tx.input[0].previous_output.txid == node2_commitment_txid {
2366 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2368 // Claim the payment on nodes[4], giving it knowledge of the preimage
2369 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2371 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2372 let events = nodes[4].node.get_and_clear_pending_msg_events();
2373 assert_eq!(events.len(), 2);
2374 let close_chan_update_2 = match events[0] {
2375 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2378 _ => panic!("Unexpected event"),
2381 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2382 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2384 _ => panic!("Unexpected event"),
2386 check_added_monitors!(nodes[4], 1);
2387 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2389 mine_transaction(&nodes[4], &node_txn[0]);
2390 check_preimage_claim(&nodes[4], &node_txn);
2391 (close_chan_update_1, close_chan_update_2)
2393 nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2394 nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2395 assert_eq!(nodes[3].node.list_channels().len(), 0);
2396 assert_eq!(nodes[4].node.list_channels().len(), 0);
2398 assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2399 ChannelMonitorUpdateStatus::Completed);
2400 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed, [nodes[4].node.get_our_node_id()], 100000);
2401 check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed, [nodes[3].node.get_our_node_id()], 100000);
2405 fn test_justice_tx_htlc_timeout() {
2406 // Test justice txn built on revoked HTLC-Timeout tx, against both sides
2407 let mut alice_config = UserConfig::default();
2408 alice_config.channel_handshake_config.announced_channel = true;
2409 alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2410 alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2411 let mut bob_config = UserConfig::default();
2412 bob_config.channel_handshake_config.announced_channel = true;
2413 bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2414 bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2415 let user_cfgs = [Some(alice_config), Some(bob_config)];
2416 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2417 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2418 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2419 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2420 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2421 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2422 // Create some new channels:
2423 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
2425 // A pending HTLC which will be revoked:
2426 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2427 // Get the will-be-revoked local txn from nodes[0]
2428 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2429 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2430 assert_eq!(revoked_local_txn[0].input.len(), 1);
2431 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2432 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2433 assert_eq!(revoked_local_txn[1].input.len(), 1);
2434 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2435 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2436 // Revoke the old state
2437 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2440 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2442 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2443 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2444 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2445 check_spends!(node_txn[0], revoked_local_txn[0]);
2446 node_txn.swap_remove(0);
2448 check_added_monitors!(nodes[1], 1);
2449 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2450 test_txn_broadcast(&nodes[1], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2452 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2453 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2454 // Verify broadcast of revoked HTLC-timeout
2455 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2456 check_added_monitors!(nodes[0], 1);
2457 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2458 // Broadcast revoked HTLC-timeout on node 1
2459 mine_transaction(&nodes[1], &node_txn[1]);
2460 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2462 get_announce_close_broadcast_events(&nodes, 0, 1);
2463 assert_eq!(nodes[0].node.list_channels().len(), 0);
2464 assert_eq!(nodes[1].node.list_channels().len(), 0);
2468 fn test_justice_tx_htlc_success() {
2469 // Test justice txn built on revoked HTLC-Success tx, against both sides
2470 let mut alice_config = UserConfig::default();
2471 alice_config.channel_handshake_config.announced_channel = true;
2472 alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2473 alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2474 let mut bob_config = UserConfig::default();
2475 bob_config.channel_handshake_config.announced_channel = true;
2476 bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2477 bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2478 let user_cfgs = [Some(alice_config), Some(bob_config)];
2479 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2480 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2481 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2482 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2483 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2484 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2485 // Create some new channels:
2486 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
2488 // A pending HTLC which will be revoked:
2489 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2490 // Get the will-be-revoked local txn from B
2491 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2492 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2493 assert_eq!(revoked_local_txn[0].input.len(), 1);
2494 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2495 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2496 // Revoke the old state
2497 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2499 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2501 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2502 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2503 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2505 check_spends!(node_txn[0], revoked_local_txn[0]);
2506 node_txn.swap_remove(0);
2508 check_added_monitors!(nodes[0], 1);
2509 test_txn_broadcast(&nodes[0], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2511 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2512 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2513 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2514 check_added_monitors!(nodes[1], 1);
2515 mine_transaction(&nodes[0], &node_txn[1]);
2516 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2517 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2519 get_announce_close_broadcast_events(&nodes, 0, 1);
2520 assert_eq!(nodes[0].node.list_channels().len(), 0);
2521 assert_eq!(nodes[1].node.list_channels().len(), 0);
2525 fn revoked_output_claim() {
2526 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2527 // transaction is broadcast by its counterparty
2528 let chanmon_cfgs = create_chanmon_cfgs(2);
2529 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2530 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2531 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2532 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2533 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2534 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2535 assert_eq!(revoked_local_txn.len(), 1);
2536 // Only output is the full channel value back to nodes[0]:
2537 assert_eq!(revoked_local_txn[0].output.len(), 1);
2538 // Send a payment through, updating everyone's latest commitment txn
2539 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2541 // Inform nodes[1] that nodes[0] broadcast a stale tx
2542 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2543 check_added_monitors!(nodes[1], 1);
2544 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2545 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2546 assert_eq!(node_txn.len(), 1); // ChannelMonitor: justice tx against revoked to_local output
2548 check_spends!(node_txn[0], revoked_local_txn[0]);
2550 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2551 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2552 get_announce_close_broadcast_events(&nodes, 0, 1);
2553 check_added_monitors!(nodes[0], 1);
2554 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2558 fn claim_htlc_outputs_shared_tx() {
2559 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2560 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2561 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2562 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2563 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2564 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2566 // Create some new channel:
2567 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2569 // Rebalance the network to generate htlc in the two directions
2570 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2571 // 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
2572 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2573 let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2575 // Get the will-be-revoked local txn from node[0]
2576 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2577 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2578 assert_eq!(revoked_local_txn[0].input.len(), 1);
2579 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2580 assert_eq!(revoked_local_txn[1].input.len(), 1);
2581 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2582 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2583 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2585 //Revoke the old state
2586 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2589 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2590 check_added_monitors!(nodes[0], 1);
2591 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2592 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2593 check_added_monitors!(nodes[1], 1);
2594 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2595 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2596 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2598 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2599 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2601 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2602 check_spends!(node_txn[0], revoked_local_txn[0]);
2604 let mut witness_lens = BTreeSet::new();
2605 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2606 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2607 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2608 assert_eq!(witness_lens.len(), 3);
2609 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2610 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2611 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2613 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2614 // ANTI_REORG_DELAY confirmations.
2615 mine_transaction(&nodes[1], &node_txn[0]);
2616 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2617 expect_payment_failed!(nodes[1], payment_hash_2, false);
2619 get_announce_close_broadcast_events(&nodes, 0, 1);
2620 assert_eq!(nodes[0].node.list_channels().len(), 0);
2621 assert_eq!(nodes[1].node.list_channels().len(), 0);
2625 fn claim_htlc_outputs_single_tx() {
2626 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2627 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2628 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2629 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2630 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2631 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2633 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2635 // Rebalance the network to generate htlc in the two directions
2636 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2637 // 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
2638 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2639 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2640 let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2642 // Get the will-be-revoked local txn from node[0]
2643 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2645 //Revoke the old state
2646 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2649 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2650 check_added_monitors!(nodes[0], 1);
2651 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2652 check_added_monitors!(nodes[1], 1);
2653 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2654 let mut events = nodes[0].node.get_and_clear_pending_events();
2655 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2656 match events.last().unwrap() {
2657 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2658 _ => panic!("Unexpected event"),
2661 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2662 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2664 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcast();
2666 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2667 assert_eq!(node_txn[0].input.len(), 1);
2668 check_spends!(node_txn[0], chan_1.3);
2669 assert_eq!(node_txn[1].input.len(), 1);
2670 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2671 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2672 check_spends!(node_txn[1], node_txn[0]);
2674 // Filter out any non justice transactions.
2675 node_txn.retain(|tx| tx.input[0].previous_output.txid == revoked_local_txn[0].txid());
2676 assert!(node_txn.len() > 3);
2678 assert_eq!(node_txn[0].input.len(), 1);
2679 assert_eq!(node_txn[1].input.len(), 1);
2680 assert_eq!(node_txn[2].input.len(), 1);
2682 check_spends!(node_txn[0], revoked_local_txn[0]);
2683 check_spends!(node_txn[1], revoked_local_txn[0]);
2684 check_spends!(node_txn[2], revoked_local_txn[0]);
2686 let mut witness_lens = BTreeSet::new();
2687 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2688 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2689 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2690 assert_eq!(witness_lens.len(), 3);
2691 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2692 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2693 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2695 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2696 // ANTI_REORG_DELAY confirmations.
2697 mine_transaction(&nodes[1], &node_txn[0]);
2698 mine_transaction(&nodes[1], &node_txn[1]);
2699 mine_transaction(&nodes[1], &node_txn[2]);
2700 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2701 expect_payment_failed!(nodes[1], payment_hash_2, false);
2703 get_announce_close_broadcast_events(&nodes, 0, 1);
2704 assert_eq!(nodes[0].node.list_channels().len(), 0);
2705 assert_eq!(nodes[1].node.list_channels().len(), 0);
2709 fn test_htlc_on_chain_success() {
2710 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2711 // the preimage backward accordingly. So here we test that ChannelManager is
2712 // broadcasting the right event to other nodes in payment path.
2713 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2714 // A --------------------> B ----------------------> C (preimage)
2715 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2716 // commitment transaction was broadcast.
2717 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2719 // B should be able to claim via preimage if A then broadcasts its local tx.
2720 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2721 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2722 // PaymentSent event).
2724 let chanmon_cfgs = create_chanmon_cfgs(3);
2725 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2726 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2727 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2729 // Create some initial channels
2730 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2731 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2733 // Ensure all nodes are at the same height
2734 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2735 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2736 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2737 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2739 // Rebalance the network a bit by relaying one payment through all the channels...
2740 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2741 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2743 let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2744 let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2746 // Broadcast legit commitment tx from C on B's chain
2747 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2748 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2749 assert_eq!(commitment_tx.len(), 1);
2750 check_spends!(commitment_tx[0], chan_2.3);
2751 nodes[2].node.claim_funds(our_payment_preimage);
2752 expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2753 nodes[2].node.claim_funds(our_payment_preimage_2);
2754 expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2755 check_added_monitors!(nodes[2], 2);
2756 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2757 assert!(updates.update_add_htlcs.is_empty());
2758 assert!(updates.update_fail_htlcs.is_empty());
2759 assert!(updates.update_fail_malformed_htlcs.is_empty());
2760 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2762 mine_transaction(&nodes[2], &commitment_tx[0]);
2763 check_closed_broadcast!(nodes[2], true);
2764 check_added_monitors!(nodes[2], 1);
2765 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2766 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 2 (2 * HTLC-Success tx)
2767 assert_eq!(node_txn.len(), 2);
2768 check_spends!(node_txn[0], commitment_tx[0]);
2769 check_spends!(node_txn[1], commitment_tx[0]);
2770 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2771 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2772 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2773 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2774 assert_eq!(node_txn[0].lock_time.0, 0);
2775 assert_eq!(node_txn[1].lock_time.0, 0);
2777 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2778 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![commitment_tx[0].clone(), node_txn[0].clone(), node_txn[1].clone()]));
2779 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2781 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2782 assert_eq!(added_monitors.len(), 1);
2783 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2784 added_monitors.clear();
2786 let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2787 assert_eq!(forwarded_events.len(), 3);
2788 match forwarded_events[0] {
2789 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2790 _ => panic!("Unexpected event"),
2792 let chan_id = Some(chan_1.2);
2793 match forwarded_events[1] {
2794 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2795 assert_eq!(fee_earned_msat, Some(1000));
2796 assert_eq!(prev_channel_id, chan_id);
2797 assert_eq!(claim_from_onchain_tx, true);
2798 assert_eq!(next_channel_id, Some(chan_2.2));
2799 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2803 match forwarded_events[2] {
2804 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2805 assert_eq!(fee_earned_msat, Some(1000));
2806 assert_eq!(prev_channel_id, chan_id);
2807 assert_eq!(claim_from_onchain_tx, true);
2808 assert_eq!(next_channel_id, Some(chan_2.2));
2809 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2813 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2815 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2816 assert_eq!(added_monitors.len(), 2);
2817 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2818 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2819 added_monitors.clear();
2821 assert_eq!(events.len(), 3);
2823 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
2824 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
2826 match nodes_2_event {
2827 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2828 _ => panic!("Unexpected event"),
2831 match nodes_0_event {
2832 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, .. } } => {
2833 assert!(update_add_htlcs.is_empty());
2834 assert!(update_fail_htlcs.is_empty());
2835 assert_eq!(update_fulfill_htlcs.len(), 1);
2836 assert!(update_fail_malformed_htlcs.is_empty());
2837 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2839 _ => panic!("Unexpected event"),
2842 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
2844 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2845 _ => panic!("Unexpected event"),
2848 macro_rules! check_tx_local_broadcast {
2849 ($node: expr, $htlc_offered: expr, $commitment_tx: expr) => { {
2850 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2851 assert_eq!(node_txn.len(), 2);
2852 // Node[1]: 2 * HTLC-timeout tx
2853 // Node[0]: 2 * HTLC-timeout tx
2854 check_spends!(node_txn[0], $commitment_tx);
2855 check_spends!(node_txn[1], $commitment_tx);
2856 assert_ne!(node_txn[0].lock_time.0, 0);
2857 assert_ne!(node_txn[1].lock_time.0, 0);
2859 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2860 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2861 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2862 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2864 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2865 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2866 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2867 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2872 // nodes[1] now broadcasts its own timeout-claim of the output that nodes[2] just claimed via success.
2873 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0]);
2875 // Broadcast legit commitment tx from A on B's chain
2876 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2877 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2878 check_spends!(node_a_commitment_tx[0], chan_1.3);
2879 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2880 check_closed_broadcast!(nodes[1], true);
2881 check_added_monitors!(nodes[1], 1);
2882 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2883 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2884 assert!(node_txn.len() == 1 || node_txn.len() == 3); // HTLC-Success, 2* RBF bumps of above HTLC txn
2885 let commitment_spend =
2886 if node_txn.len() == 1 {
2889 // Certain `ConnectStyle`s will cause RBF bumps of the previous HTLC transaction to be broadcast.
2890 // FullBlockViaListen
2891 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2892 check_spends!(node_txn[1], commitment_tx[0]);
2893 check_spends!(node_txn[2], commitment_tx[0]);
2894 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2897 check_spends!(node_txn[0], commitment_tx[0]);
2898 check_spends!(node_txn[1], commitment_tx[0]);
2899 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2904 check_spends!(commitment_spend, node_a_commitment_tx[0]);
2905 assert_eq!(commitment_spend.input.len(), 2);
2906 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2907 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2908 assert_eq!(commitment_spend.lock_time.0, nodes[1].best_block_info().1);
2909 assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2910 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2911 // we already checked the same situation with A.
2913 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2914 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()]));
2915 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
2916 check_closed_broadcast!(nodes[0], true);
2917 check_added_monitors!(nodes[0], 1);
2918 let events = nodes[0].node.get_and_clear_pending_events();
2919 assert_eq!(events.len(), 5);
2920 let mut first_claimed = false;
2921 for event in events {
2923 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2924 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2925 assert!(!first_claimed);
2926 first_claimed = true;
2928 assert_eq!(payment_preimage, our_payment_preimage_2);
2929 assert_eq!(payment_hash, payment_hash_2);
2932 Event::PaymentPathSuccessful { .. } => {},
2933 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2934 _ => panic!("Unexpected event"),
2937 check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0]);
2940 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2941 // Test that in case of a unilateral close onchain, we detect the state of output and
2942 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2943 // broadcasting the right event to other nodes in payment path.
2944 // A ------------------> B ----------------------> C (timeout)
2945 // B's commitment tx C's commitment tx
2947 // B's HTLC timeout tx B's timeout tx
2949 let chanmon_cfgs = create_chanmon_cfgs(3);
2950 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2951 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2952 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2953 *nodes[0].connect_style.borrow_mut() = connect_style;
2954 *nodes[1].connect_style.borrow_mut() = connect_style;
2955 *nodes[2].connect_style.borrow_mut() = connect_style;
2957 // Create some intial channels
2958 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2959 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2961 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2962 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2963 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2965 let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2967 // Broadcast legit commitment tx from C on B's chain
2968 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2969 check_spends!(commitment_tx[0], chan_2.3);
2970 nodes[2].node.fail_htlc_backwards(&payment_hash);
2971 check_added_monitors!(nodes[2], 0);
2972 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
2973 check_added_monitors!(nodes[2], 1);
2975 let events = nodes[2].node.get_and_clear_pending_msg_events();
2976 assert_eq!(events.len(), 1);
2978 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, .. } } => {
2979 assert!(update_add_htlcs.is_empty());
2980 assert!(!update_fail_htlcs.is_empty());
2981 assert!(update_fulfill_htlcs.is_empty());
2982 assert!(update_fail_malformed_htlcs.is_empty());
2983 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2985 _ => panic!("Unexpected event"),
2987 mine_transaction(&nodes[2], &commitment_tx[0]);
2988 check_closed_broadcast!(nodes[2], true);
2989 check_added_monitors!(nodes[2], 1);
2990 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2991 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2992 assert_eq!(node_txn.len(), 0);
2994 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2995 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2996 mine_transaction(&nodes[1], &commitment_tx[0]);
2997 check_closed_event!(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false
2998 , [nodes[2].node.get_our_node_id()], 100000);
2999 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
3001 let mut txn = nodes[1].tx_broadcaster.txn_broadcast();
3002 if nodes[1].connect_style.borrow().skips_blocks() {
3003 assert_eq!(txn.len(), 1);
3005 assert_eq!(txn.len(), 3); // Two extra fee bumps for timeout transaction
3007 txn.iter().for_each(|tx| check_spends!(tx, commitment_tx[0]));
3008 assert_eq!(txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3012 mine_transaction(&nodes[1], &timeout_tx);
3013 check_added_monitors!(nodes[1], 1);
3014 check_closed_broadcast!(nodes[1], true);
3016 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3018 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
3019 check_added_monitors!(nodes[1], 1);
3020 let events = nodes[1].node.get_and_clear_pending_msg_events();
3021 assert_eq!(events.len(), 1);
3023 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, .. } } => {
3024 assert!(update_add_htlcs.is_empty());
3025 assert!(!update_fail_htlcs.is_empty());
3026 assert!(update_fulfill_htlcs.is_empty());
3027 assert!(update_fail_malformed_htlcs.is_empty());
3028 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3030 _ => panic!("Unexpected event"),
3033 // Broadcast legit commitment tx from B on A's chain
3034 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3035 check_spends!(commitment_tx[0], chan_1.3);
3037 mine_transaction(&nodes[0], &commitment_tx[0]);
3038 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
3040 check_closed_broadcast!(nodes[0], true);
3041 check_added_monitors!(nodes[0], 1);
3042 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
3043 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // 1 timeout tx
3044 assert_eq!(node_txn.len(), 1);
3045 check_spends!(node_txn[0], commitment_tx[0]);
3046 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3050 fn test_htlc_on_chain_timeout() {
3051 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3052 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3053 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3057 fn test_simple_commitment_revoked_fail_backward() {
3058 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3059 // and fail backward accordingly.
3061 let chanmon_cfgs = create_chanmon_cfgs(3);
3062 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3063 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3064 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3066 // Create some initial channels
3067 create_announced_chan_between_nodes(&nodes, 0, 1);
3068 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3070 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3071 // Get the will-be-revoked local txn from nodes[2]
3072 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3073 // Revoke the old state
3074 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3076 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3078 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3079 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
3080 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3081 check_added_monitors!(nodes[1], 1);
3082 check_closed_broadcast!(nodes[1], true);
3084 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
3085 check_added_monitors!(nodes[1], 1);
3086 let events = nodes[1].node.get_and_clear_pending_msg_events();
3087 assert_eq!(events.len(), 1);
3089 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, .. } } => {
3090 assert!(update_add_htlcs.is_empty());
3091 assert_eq!(update_fail_htlcs.len(), 1);
3092 assert!(update_fulfill_htlcs.is_empty());
3093 assert!(update_fail_malformed_htlcs.is_empty());
3094 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3096 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3097 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3098 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3100 _ => panic!("Unexpected event"),
3104 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3105 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3106 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3107 // commitment transaction anymore.
3108 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3109 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3110 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3111 // technically disallowed and we should probably handle it reasonably.
3112 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3113 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3115 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3116 // commitment_signed (implying it will be in the latest remote commitment transaction).
3117 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3118 // and once they revoke the previous commitment transaction (allowing us to send a new
3119 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3120 let chanmon_cfgs = create_chanmon_cfgs(3);
3121 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3122 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3123 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3125 // Create some initial channels
3126 create_announced_chan_between_nodes(&nodes, 0, 1);
3127 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3129 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3130 // Get the will-be-revoked local txn from nodes[2]
3131 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3132 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3133 // Revoke the old state
3134 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3136 let value = if use_dust {
3137 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3138 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3139 nodes[2].node.per_peer_state.read().unwrap().get(&nodes[1].node.get_our_node_id())
3140 .unwrap().lock().unwrap().channel_by_id.get(&chan_2.2).unwrap().context.holder_dust_limit_satoshis * 1000
3143 let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3144 let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3145 let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3147 nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3148 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3149 check_added_monitors!(nodes[2], 1);
3150 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3151 assert!(updates.update_add_htlcs.is_empty());
3152 assert!(updates.update_fulfill_htlcs.is_empty());
3153 assert!(updates.update_fail_malformed_htlcs.is_empty());
3154 assert_eq!(updates.update_fail_htlcs.len(), 1);
3155 assert!(updates.update_fee.is_none());
3156 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3157 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3158 // Drop the last RAA from 3 -> 2
3160 nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3161 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3162 check_added_monitors!(nodes[2], 1);
3163 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3164 assert!(updates.update_add_htlcs.is_empty());
3165 assert!(updates.update_fulfill_htlcs.is_empty());
3166 assert!(updates.update_fail_malformed_htlcs.is_empty());
3167 assert_eq!(updates.update_fail_htlcs.len(), 1);
3168 assert!(updates.update_fee.is_none());
3169 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3170 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3171 check_added_monitors!(nodes[1], 1);
3172 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3173 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3174 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3175 check_added_monitors!(nodes[2], 1);
3177 nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3178 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3179 check_added_monitors!(nodes[2], 1);
3180 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3181 assert!(updates.update_add_htlcs.is_empty());
3182 assert!(updates.update_fulfill_htlcs.is_empty());
3183 assert!(updates.update_fail_malformed_htlcs.is_empty());
3184 assert_eq!(updates.update_fail_htlcs.len(), 1);
3185 assert!(updates.update_fee.is_none());
3186 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3187 // At this point first_payment_hash has dropped out of the latest two commitment
3188 // transactions that nodes[1] is tracking...
3189 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3190 check_added_monitors!(nodes[1], 1);
3191 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3192 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3193 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3194 check_added_monitors!(nodes[2], 1);
3196 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3197 // on nodes[2]'s RAA.
3198 let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3199 nodes[1].node.send_payment_with_route(&route, fourth_payment_hash,
3200 RecipientOnionFields::secret_only(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3201 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3202 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3203 check_added_monitors!(nodes[1], 0);
3206 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3207 // One monitor for the new revocation preimage, no second on as we won't generate a new
3208 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3209 check_added_monitors!(nodes[1], 1);
3210 let events = nodes[1].node.get_and_clear_pending_events();
3211 assert_eq!(events.len(), 2);
3213 Event::PendingHTLCsForwardable { .. } => { },
3214 _ => panic!("Unexpected event"),
3217 Event::HTLCHandlingFailed { .. } => { },
3218 _ => panic!("Unexpected event"),
3220 // Deliberately don't process the pending fail-back so they all fail back at once after
3221 // block connection just like the !deliver_bs_raa case
3224 let mut failed_htlcs = HashSet::new();
3225 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3227 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3228 check_added_monitors!(nodes[1], 1);
3229 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3231 let events = nodes[1].node.get_and_clear_pending_events();
3232 assert_eq!(events.len(), if deliver_bs_raa { 3 + nodes.len() - 1 } else { 4 + nodes.len() });
3234 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3235 _ => panic!("Unexepected event"),
3238 Event::PaymentPathFailed { ref payment_hash, .. } => {
3239 assert_eq!(*payment_hash, fourth_payment_hash);
3241 _ => panic!("Unexpected event"),
3244 Event::PaymentFailed { ref payment_hash, .. } => {
3245 assert_eq!(*payment_hash, fourth_payment_hash);
3247 _ => panic!("Unexpected event"),
3250 nodes[1].node.process_pending_htlc_forwards();
3251 check_added_monitors!(nodes[1], 1);
3253 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
3254 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3257 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3258 match nodes_2_event {
3259 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, .. } } => {
3260 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3261 assert_eq!(update_add_htlcs.len(), 1);
3262 assert!(update_fulfill_htlcs.is_empty());
3263 assert!(update_fail_htlcs.is_empty());
3264 assert!(update_fail_malformed_htlcs.is_empty());
3266 _ => panic!("Unexpected event"),
3270 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3271 match nodes_2_event {
3272 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3273 assert_eq!(channel_id, chan_2.2);
3274 assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3276 _ => panic!("Unexpected event"),
3279 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
3280 match nodes_0_event {
3281 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, .. } } => {
3282 assert!(update_add_htlcs.is_empty());
3283 assert_eq!(update_fail_htlcs.len(), 3);
3284 assert!(update_fulfill_htlcs.is_empty());
3285 assert!(update_fail_malformed_htlcs.is_empty());
3286 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3288 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3289 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3290 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3292 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3294 let events = nodes[0].node.get_and_clear_pending_events();
3295 assert_eq!(events.len(), 6);
3297 Event::PaymentPathFailed { ref payment_hash, ref failure, .. } => {
3298 assert!(failed_htlcs.insert(payment_hash.0));
3299 // If we delivered B's RAA we got an unknown preimage error, not something
3300 // that we should update our routing table for.
3301 if !deliver_bs_raa {
3302 if let PathFailure::OnPath { network_update: Some(_) } = failure { } else { panic!("Unexpected path failure") }
3305 _ => panic!("Unexpected event"),
3308 Event::PaymentFailed { ref payment_hash, .. } => {
3309 assert_eq!(*payment_hash, first_payment_hash);
3311 _ => panic!("Unexpected event"),
3314 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3315 assert!(failed_htlcs.insert(payment_hash.0));
3317 _ => panic!("Unexpected event"),
3320 Event::PaymentFailed { ref payment_hash, .. } => {
3321 assert_eq!(*payment_hash, second_payment_hash);
3323 _ => panic!("Unexpected event"),
3326 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3327 assert!(failed_htlcs.insert(payment_hash.0));
3329 _ => panic!("Unexpected event"),
3332 Event::PaymentFailed { ref payment_hash, .. } => {
3333 assert_eq!(*payment_hash, third_payment_hash);
3335 _ => panic!("Unexpected event"),
3338 _ => panic!("Unexpected event"),
3341 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
3343 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3344 _ => panic!("Unexpected event"),
3347 assert!(failed_htlcs.contains(&first_payment_hash.0));
3348 assert!(failed_htlcs.contains(&second_payment_hash.0));
3349 assert!(failed_htlcs.contains(&third_payment_hash.0));
3353 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3354 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3355 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3356 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3357 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3361 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3362 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3363 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3364 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3365 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3369 fn fail_backward_pending_htlc_upon_channel_failure() {
3370 let chanmon_cfgs = create_chanmon_cfgs(2);
3371 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3372 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3373 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3374 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
3376 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3378 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3379 nodes[0].node.send_payment_with_route(&route, payment_hash, RecipientOnionFields::secret_only(payment_secret),
3380 PaymentId(payment_hash.0)).unwrap();
3381 check_added_monitors!(nodes[0], 1);
3383 let payment_event = {
3384 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3385 assert_eq!(events.len(), 1);
3386 SendEvent::from_event(events.remove(0))
3388 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3389 assert_eq!(payment_event.msgs.len(), 1);
3392 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3393 let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3395 nodes[0].node.send_payment_with_route(&route, failed_payment_hash,
3396 RecipientOnionFields::secret_only(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3397 check_added_monitors!(nodes[0], 0);
3399 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3402 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3404 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3406 let secp_ctx = Secp256k1::new();
3407 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3408 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3409 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(
3410 &route.paths[0], 50_000, RecipientOnionFields::secret_only(payment_secret), current_height, &None).unwrap();
3411 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3412 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
3414 // Send a 0-msat update_add_htlc to fail the channel.
3415 let update_add_htlc = msgs::UpdateAddHTLC {
3421 onion_routing_packet,
3422 skimmed_fee_msat: None,
3424 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3426 let events = nodes[0].node.get_and_clear_pending_events();
3427 assert_eq!(events.len(), 3);
3428 // Check that Alice fails backward the pending HTLC from the second payment.
3430 Event::PaymentPathFailed { payment_hash, .. } => {
3431 assert_eq!(payment_hash, failed_payment_hash);
3433 _ => panic!("Unexpected event"),
3436 Event::PaymentFailed { payment_hash, .. } => {
3437 assert_eq!(payment_hash, failed_payment_hash);
3439 _ => panic!("Unexpected event"),
3442 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3443 assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3445 _ => panic!("Unexpected event {:?}", events[1]),
3447 check_closed_broadcast!(nodes[0], true);
3448 check_added_monitors!(nodes[0], 1);
3452 fn test_htlc_ignore_latest_remote_commitment() {
3453 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3454 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3455 let chanmon_cfgs = create_chanmon_cfgs(2);
3456 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3457 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3458 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3459 if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3460 // We rely on the ability to connect a block redundantly, which isn't allowed via
3461 // `chain::Listen`, so we never run the test if we randomly get assigned that
3465 create_announced_chan_between_nodes(&nodes, 0, 1);
3467 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3468 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3469 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3470 check_closed_broadcast!(nodes[0], true);
3471 check_added_monitors!(nodes[0], 1);
3472 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
3474 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3475 assert_eq!(node_txn.len(), 3);
3476 assert_eq!(node_txn[0].txid(), node_txn[1].txid());
3478 let block = create_dummy_block(nodes[1].best_block_hash(), 42, vec![node_txn[0].clone(), node_txn[1].clone()]);
3479 connect_block(&nodes[1], &block);
3480 check_closed_broadcast!(nodes[1], true);
3481 check_added_monitors!(nodes[1], 1);
3482 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
3484 // Duplicate the connect_block call since this may happen due to other listeners
3485 // registering new transactions
3486 connect_block(&nodes[1], &block);
3490 fn test_force_close_fail_back() {
3491 // Check which HTLCs are failed-backwards on channel force-closure
3492 let chanmon_cfgs = create_chanmon_cfgs(3);
3493 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3494 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3495 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3496 create_announced_chan_between_nodes(&nodes, 0, 1);
3497 create_announced_chan_between_nodes(&nodes, 1, 2);
3499 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3501 let mut payment_event = {
3502 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
3503 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3504 check_added_monitors!(nodes[0], 1);
3506 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3507 assert_eq!(events.len(), 1);
3508 SendEvent::from_event(events.remove(0))
3511 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3512 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3514 expect_pending_htlcs_forwardable!(nodes[1]);
3516 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3517 assert_eq!(events_2.len(), 1);
3518 payment_event = SendEvent::from_event(events_2.remove(0));
3519 assert_eq!(payment_event.msgs.len(), 1);
3521 check_added_monitors!(nodes[1], 1);
3522 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3523 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3524 check_added_monitors!(nodes[2], 1);
3525 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3527 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3528 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3529 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3531 nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3532 check_closed_broadcast!(nodes[2], true);
3533 check_added_monitors!(nodes[2], 1);
3534 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
3536 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3537 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3538 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3539 // back to nodes[1] upon timeout otherwise.
3540 assert_eq!(node_txn.len(), 1);
3544 mine_transaction(&nodes[1], &tx);
3546 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3547 check_closed_broadcast!(nodes[1], true);
3548 check_added_monitors!(nodes[1], 1);
3549 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
3551 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3553 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3554 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &LowerBoundedFeeEstimator::new(node_cfgs[2].fee_estimator), &node_cfgs[2].logger);
3556 mine_transaction(&nodes[2], &tx);
3557 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3558 assert_eq!(node_txn.len(), 1);
3559 assert_eq!(node_txn[0].input.len(), 1);
3560 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3561 assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3562 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3564 check_spends!(node_txn[0], tx);
3568 fn test_dup_events_on_peer_disconnect() {
3569 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3570 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3571 // as we used to generate the event immediately upon receipt of the payment preimage in the
3572 // update_fulfill_htlc message.
3574 let chanmon_cfgs = create_chanmon_cfgs(2);
3575 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3576 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3577 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3578 create_announced_chan_between_nodes(&nodes, 0, 1);
3580 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3582 nodes[1].node.claim_funds(payment_preimage);
3583 expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3584 check_added_monitors!(nodes[1], 1);
3585 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3586 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3587 expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
3589 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3590 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3592 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3593 reconnect_args.pending_htlc_claims.0 = 1;
3594 reconnect_nodes(reconnect_args);
3595 expect_payment_path_successful!(nodes[0]);
3599 fn test_peer_disconnected_before_funding_broadcasted() {
3600 // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3601 // before the funding transaction has been broadcasted.
3602 let chanmon_cfgs = create_chanmon_cfgs(2);
3603 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3604 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3605 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3607 // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3608 // broadcasted, even though it's created by `nodes[0]`.
3609 let expected_temporary_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
3610 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3611 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
3612 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3613 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
3615 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3616 assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3618 assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3620 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3621 assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3623 // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3624 // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3627 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3630 // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3631 // disconnected before the funding transaction was broadcasted.
3632 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3633 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3635 check_closed_event!(&nodes[0], 1, ClosureReason::DisconnectedPeer, false
3636 , [nodes[1].node.get_our_node_id()], 1000000);
3637 check_closed_event!(&nodes[1], 1, ClosureReason::DisconnectedPeer, false
3638 , [nodes[0].node.get_our_node_id()], 1000000);
3642 fn test_simple_peer_disconnect() {
3643 // Test that we can reconnect when there are no lost messages
3644 let chanmon_cfgs = create_chanmon_cfgs(3);
3645 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3646 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3647 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3648 create_announced_chan_between_nodes(&nodes, 0, 1);
3649 create_announced_chan_between_nodes(&nodes, 1, 2);
3651 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3652 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3653 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3654 reconnect_args.send_channel_ready = (true, true);
3655 reconnect_nodes(reconnect_args);
3657 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3658 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3659 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3660 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3662 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3663 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3664 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3666 let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3667 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3668 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3669 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3671 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3672 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3674 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3675 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3677 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3678 reconnect_args.pending_cell_htlc_fails.0 = 1;
3679 reconnect_args.pending_cell_htlc_claims.0 = 1;
3680 reconnect_nodes(reconnect_args);
3682 let events = nodes[0].node.get_and_clear_pending_events();
3683 assert_eq!(events.len(), 4);
3685 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3686 assert_eq!(payment_preimage, payment_preimage_3);
3687 assert_eq!(payment_hash, payment_hash_3);
3689 _ => panic!("Unexpected event"),
3692 Event::PaymentPathSuccessful { .. } => {},
3693 _ => panic!("Unexpected event"),
3696 Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3697 assert_eq!(payment_hash, payment_hash_5);
3698 assert!(payment_failed_permanently);
3700 _ => panic!("Unexpected event"),
3703 Event::PaymentFailed { payment_hash, .. } => {
3704 assert_eq!(payment_hash, payment_hash_5);
3706 _ => panic!("Unexpected event"),
3709 check_added_monitors(&nodes[0], 1);
3711 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3712 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3715 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3716 // Test that we can reconnect when in-flight HTLC updates get dropped
3717 let chanmon_cfgs = create_chanmon_cfgs(2);
3718 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3719 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3720 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3722 let mut as_channel_ready = None;
3723 let channel_id = if messages_delivered == 0 {
3724 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3725 as_channel_ready = Some(channel_ready);
3726 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3727 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3728 // it before the channel_reestablish message.
3731 create_announced_chan_between_nodes(&nodes, 0, 1).2
3734 let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3736 let payment_event = {
3737 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
3738 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3739 check_added_monitors!(nodes[0], 1);
3741 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3742 assert_eq!(events.len(), 1);
3743 SendEvent::from_event(events.remove(0))
3745 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3747 if messages_delivered < 2 {
3748 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3750 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3751 if messages_delivered >= 3 {
3752 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3753 check_added_monitors!(nodes[1], 1);
3754 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3756 if messages_delivered >= 4 {
3757 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3758 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3759 check_added_monitors!(nodes[0], 1);
3761 if messages_delivered >= 5 {
3762 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3763 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3764 // No commitment_signed so get_event_msg's assert(len == 1) passes
3765 check_added_monitors!(nodes[0], 1);
3767 if messages_delivered >= 6 {
3768 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3769 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3770 check_added_monitors!(nodes[1], 1);
3777 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3778 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3779 if messages_delivered < 3 {
3780 if simulate_broken_lnd {
3781 // lnd has a long-standing bug where they send a channel_ready prior to a
3782 // channel_reestablish if you reconnect prior to channel_ready time.
3784 // Here we simulate that behavior, delivering a channel_ready immediately on
3785 // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3786 // in `reconnect_nodes` but we currently don't fail based on that.
3788 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3789 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3791 // Even if the channel_ready messages get exchanged, as long as nothing further was
3792 // received on either side, both sides will need to resend them.
3793 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3794 reconnect_args.send_channel_ready = (true, true);
3795 reconnect_args.pending_htlc_adds.1 = 1;
3796 reconnect_nodes(reconnect_args);
3797 } else if messages_delivered == 3 {
3798 // nodes[0] still wants its RAA + commitment_signed
3799 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3800 reconnect_args.pending_htlc_adds.0 = -1;
3801 reconnect_args.pending_raa.0 = true;
3802 reconnect_nodes(reconnect_args);
3803 } else if messages_delivered == 4 {
3804 // nodes[0] still wants its commitment_signed
3805 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3806 reconnect_args.pending_htlc_adds.0 = -1;
3807 reconnect_nodes(reconnect_args);
3808 } else if messages_delivered == 5 {
3809 // nodes[1] still wants its final RAA
3810 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3811 reconnect_args.pending_raa.1 = true;
3812 reconnect_nodes(reconnect_args);
3813 } else if messages_delivered == 6 {
3814 // Everything was delivered...
3815 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3818 let events_1 = nodes[1].node.get_and_clear_pending_events();
3819 if messages_delivered == 0 {
3820 assert_eq!(events_1.len(), 2);
3822 Event::ChannelReady { .. } => { },
3823 _ => panic!("Unexpected event"),
3826 Event::PendingHTLCsForwardable { .. } => { },
3827 _ => panic!("Unexpected event"),
3830 assert_eq!(events_1.len(), 1);
3832 Event::PendingHTLCsForwardable { .. } => { },
3833 _ => panic!("Unexpected event"),
3837 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3838 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3839 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3841 nodes[1].node.process_pending_htlc_forwards();
3843 let events_2 = nodes[1].node.get_and_clear_pending_events();
3844 assert_eq!(events_2.len(), 1);
3846 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
3847 assert_eq!(payment_hash_1, *payment_hash);
3848 assert_eq!(amount_msat, 1_000_000);
3849 assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3850 assert_eq!(via_channel_id, Some(channel_id));
3852 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3853 assert!(payment_preimage.is_none());
3854 assert_eq!(payment_secret_1, *payment_secret);
3856 _ => panic!("expected PaymentPurpose::InvoicePayment")
3859 _ => panic!("Unexpected event"),
3862 nodes[1].node.claim_funds(payment_preimage_1);
3863 check_added_monitors!(nodes[1], 1);
3864 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3866 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3867 assert_eq!(events_3.len(), 1);
3868 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3869 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3870 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3871 assert!(updates.update_add_htlcs.is_empty());
3872 assert!(updates.update_fail_htlcs.is_empty());
3873 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3874 assert!(updates.update_fail_malformed_htlcs.is_empty());
3875 assert!(updates.update_fee.is_none());
3876 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3878 _ => panic!("Unexpected event"),
3881 if messages_delivered >= 1 {
3882 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3884 let events_4 = nodes[0].node.get_and_clear_pending_events();
3885 assert_eq!(events_4.len(), 1);
3887 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3888 assert_eq!(payment_preimage_1, *payment_preimage);
3889 assert_eq!(payment_hash_1, *payment_hash);
3891 _ => panic!("Unexpected event"),
3894 if messages_delivered >= 2 {
3895 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3896 check_added_monitors!(nodes[0], 1);
3897 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3899 if messages_delivered >= 3 {
3900 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3901 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3902 check_added_monitors!(nodes[1], 1);
3904 if messages_delivered >= 4 {
3905 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3906 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3907 // No commitment_signed so get_event_msg's assert(len == 1) passes
3908 check_added_monitors!(nodes[1], 1);
3910 if messages_delivered >= 5 {
3911 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3912 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3913 check_added_monitors!(nodes[0], 1);
3920 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3921 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3922 if messages_delivered < 2 {
3923 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3924 reconnect_args.pending_htlc_claims.0 = 1;
3925 reconnect_nodes(reconnect_args);
3926 if messages_delivered < 1 {
3927 expect_payment_sent!(nodes[0], payment_preimage_1);
3929 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3931 } else if messages_delivered == 2 {
3932 // nodes[0] still wants its RAA + commitment_signed
3933 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3934 reconnect_args.pending_htlc_adds.1 = -1;
3935 reconnect_args.pending_raa.1 = true;
3936 reconnect_nodes(reconnect_args);
3937 } else if messages_delivered == 3 {
3938 // nodes[0] still wants its commitment_signed
3939 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3940 reconnect_args.pending_htlc_adds.1 = -1;
3941 reconnect_nodes(reconnect_args);
3942 } else if messages_delivered == 4 {
3943 // nodes[1] still wants its final RAA
3944 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3945 reconnect_args.pending_raa.0 = true;
3946 reconnect_nodes(reconnect_args);
3947 } else if messages_delivered == 5 {
3948 // Everything was delivered...
3949 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3952 if messages_delivered == 1 || messages_delivered == 2 {
3953 expect_payment_path_successful!(nodes[0]);
3955 if messages_delivered <= 5 {
3956 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3957 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3959 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3961 if messages_delivered > 2 {
3962 expect_payment_path_successful!(nodes[0]);
3965 // Channel should still work fine...
3966 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3967 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3968 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3972 fn test_drop_messages_peer_disconnect_a() {
3973 do_test_drop_messages_peer_disconnect(0, true);
3974 do_test_drop_messages_peer_disconnect(0, false);
3975 do_test_drop_messages_peer_disconnect(1, false);
3976 do_test_drop_messages_peer_disconnect(2, false);
3980 fn test_drop_messages_peer_disconnect_b() {
3981 do_test_drop_messages_peer_disconnect(3, false);
3982 do_test_drop_messages_peer_disconnect(4, false);
3983 do_test_drop_messages_peer_disconnect(5, false);
3984 do_test_drop_messages_peer_disconnect(6, false);
3988 fn test_channel_ready_without_best_block_updated() {
3989 // Previously, if we were offline when a funding transaction was locked in, and then we came
3990 // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
3991 // generate a channel_ready until a later best_block_updated. This tests that we generate the
3992 // channel_ready immediately instead.
3993 let chanmon_cfgs = create_chanmon_cfgs(2);
3994 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3995 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3996 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3997 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
3999 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
4001 let conf_height = nodes[0].best_block_info().1 + 1;
4002 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4003 let block_txn = [funding_tx];
4004 let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
4005 let conf_block_header = nodes[0].get_block_header(conf_height);
4006 nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
4008 // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4009 let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4010 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4014 fn test_drop_messages_peer_disconnect_dual_htlc() {
4015 // Test that we can handle reconnecting when both sides of a channel have pending
4016 // commitment_updates when we disconnect.
4017 let chanmon_cfgs = create_chanmon_cfgs(2);
4018 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4019 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4020 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4021 create_announced_chan_between_nodes(&nodes, 0, 1);
4023 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
4025 // Now try to send a second payment which will fail to send
4026 let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4027 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
4028 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
4029 check_added_monitors!(nodes[0], 1);
4031 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4032 assert_eq!(events_1.len(), 1);
4034 MessageSendEvent::UpdateHTLCs { .. } => {},
4035 _ => panic!("Unexpected event"),
4038 nodes[1].node.claim_funds(payment_preimage_1);
4039 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4040 check_added_monitors!(nodes[1], 1);
4042 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4043 assert_eq!(events_2.len(), 1);
4045 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 } } => {
4046 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4047 assert!(update_add_htlcs.is_empty());
4048 assert_eq!(update_fulfill_htlcs.len(), 1);
4049 assert!(update_fail_htlcs.is_empty());
4050 assert!(update_fail_malformed_htlcs.is_empty());
4051 assert!(update_fee.is_none());
4053 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4054 let events_3 = nodes[0].node.get_and_clear_pending_events();
4055 assert_eq!(events_3.len(), 1);
4057 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4058 assert_eq!(*payment_preimage, payment_preimage_1);
4059 assert_eq!(*payment_hash, payment_hash_1);
4061 _ => panic!("Unexpected event"),
4064 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4065 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4066 // No commitment_signed so get_event_msg's assert(len == 1) passes
4067 check_added_monitors!(nodes[0], 1);
4069 _ => panic!("Unexpected event"),
4072 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4073 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4075 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
4076 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
4078 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4079 assert_eq!(reestablish_1.len(), 1);
4080 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
4081 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
4083 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4084 assert_eq!(reestablish_2.len(), 1);
4086 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4087 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4088 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4089 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4091 assert!(as_resp.0.is_none());
4092 assert!(bs_resp.0.is_none());
4094 assert!(bs_resp.1.is_none());
4095 assert!(bs_resp.2.is_none());
4097 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4099 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4100 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4101 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4102 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4103 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4104 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4105 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4106 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4107 // No commitment_signed so get_event_msg's assert(len == 1) passes
4108 check_added_monitors!(nodes[1], 1);
4110 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4111 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4112 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4113 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4114 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4115 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4116 assert!(bs_second_commitment_signed.update_fee.is_none());
4117 check_added_monitors!(nodes[1], 1);
4119 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4120 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4121 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4122 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4123 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4124 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4125 assert!(as_commitment_signed.update_fee.is_none());
4126 check_added_monitors!(nodes[0], 1);
4128 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4129 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4130 // No commitment_signed so get_event_msg's assert(len == 1) passes
4131 check_added_monitors!(nodes[0], 1);
4133 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4134 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4135 // No commitment_signed so get_event_msg's assert(len == 1) passes
4136 check_added_monitors!(nodes[1], 1);
4138 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4139 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4140 check_added_monitors!(nodes[1], 1);
4142 expect_pending_htlcs_forwardable!(nodes[1]);
4144 let events_5 = nodes[1].node.get_and_clear_pending_events();
4145 assert_eq!(events_5.len(), 1);
4147 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4148 assert_eq!(payment_hash_2, *payment_hash);
4150 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4151 assert!(payment_preimage.is_none());
4152 assert_eq!(payment_secret_2, *payment_secret);
4154 _ => panic!("expected PaymentPurpose::InvoicePayment")
4157 _ => panic!("Unexpected event"),
4160 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4161 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4162 check_added_monitors!(nodes[0], 1);
4164 expect_payment_path_successful!(nodes[0]);
4165 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4168 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4169 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4170 // to avoid our counterparty failing the channel.
4171 let chanmon_cfgs = create_chanmon_cfgs(2);
4172 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4173 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4174 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4176 create_announced_chan_between_nodes(&nodes, 0, 1);
4178 let our_payment_hash = if send_partial_mpp {
4179 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4180 // Use the utility function send_payment_along_path to send the payment with MPP data which
4181 // indicates there are more HTLCs coming.
4182 let cur_height = CHAN_CONFIRM_DEPTH + 1; // route_payment calls send_payment, which adds 1 to the current height. So we do the same here to match.
4183 let payment_id = PaymentId([42; 32]);
4184 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
4185 RecipientOnionFields::secret_only(payment_secret), payment_id, &route).unwrap();
4186 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
4187 RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id,
4188 &None, session_privs[0]).unwrap();
4189 check_added_monitors!(nodes[0], 1);
4190 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4191 assert_eq!(events.len(), 1);
4192 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4193 // hop should *not* yet generate any PaymentClaimable event(s).
4194 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4197 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4200 let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
4201 connect_block(&nodes[0], &block);
4202 connect_block(&nodes[1], &block);
4203 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4204 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4205 block.header.prev_blockhash = block.block_hash();
4206 connect_block(&nodes[0], &block);
4207 connect_block(&nodes[1], &block);
4210 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4212 check_added_monitors!(nodes[1], 1);
4213 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4214 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4215 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4216 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4217 assert!(htlc_timeout_updates.update_fee.is_none());
4219 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4220 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4221 // 100_000 msat as u64, followed by the height at which we failed back above
4222 let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4223 expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4224 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4228 fn test_htlc_timeout() {
4229 do_test_htlc_timeout(true);
4230 do_test_htlc_timeout(false);
4233 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4234 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4235 let chanmon_cfgs = create_chanmon_cfgs(3);
4236 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4237 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4238 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4239 create_announced_chan_between_nodes(&nodes, 0, 1);
4240 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4242 // Make sure all nodes are at the same starting height
4243 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4244 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4245 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4247 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4248 let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4249 nodes[1].node.send_payment_with_route(&route, first_payment_hash,
4250 RecipientOnionFields::secret_only(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4251 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4252 check_added_monitors!(nodes[1], 1);
4254 // Now attempt to route a second payment, which should be placed in the holding cell
4255 let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4256 let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4257 sending_node.node.send_payment_with_route(&route, second_payment_hash,
4258 RecipientOnionFields::secret_only(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4260 check_added_monitors!(nodes[0], 1);
4261 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4262 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4263 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4264 expect_pending_htlcs_forwardable!(nodes[1]);
4266 check_added_monitors!(nodes[1], 0);
4268 connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4269 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4270 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4271 connect_blocks(&nodes[1], 1);
4274 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
4275 check_added_monitors!(nodes[1], 1);
4276 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4277 assert_eq!(fail_commit.len(), 1);
4278 match fail_commit[0] {
4279 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4280 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4281 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4283 _ => unreachable!(),
4285 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4287 expect_payment_failed!(nodes[1], second_payment_hash, false);
4292 fn test_holding_cell_htlc_add_timeouts() {
4293 do_test_holding_cell_htlc_add_timeouts(false);
4294 do_test_holding_cell_htlc_add_timeouts(true);
4297 macro_rules! check_spendable_outputs {
4298 ($node: expr, $keysinterface: expr) => {
4300 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4301 let mut txn = Vec::new();
4302 let mut all_outputs = Vec::new();
4303 let secp_ctx = Secp256k1::new();
4304 for event in events.drain(..) {
4306 Event::SpendableOutputs { mut outputs } => {
4307 for outp in outputs.drain(..) {
4308 txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, None, &secp_ctx).unwrap());
4309 all_outputs.push(outp);
4312 _ => panic!("Unexpected event"),
4315 if all_outputs.len() > 1 {
4316 if let Ok(tx) = $keysinterface.backing.spend_spendable_outputs(&all_outputs.iter().map(|a| a).collect::<Vec<_>>(), Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, None, &secp_ctx) {
4326 fn test_claim_sizeable_push_msat() {
4327 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4328 let chanmon_cfgs = create_chanmon_cfgs(2);
4329 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4330 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4331 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4333 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4334 nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4335 check_closed_broadcast!(nodes[1], true);
4336 check_added_monitors!(nodes[1], 1);
4337 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[0].node.get_our_node_id()], 100000);
4338 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4339 assert_eq!(node_txn.len(), 1);
4340 check_spends!(node_txn[0], chan.3);
4341 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
4343 mine_transaction(&nodes[1], &node_txn[0]);
4344 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4346 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4347 assert_eq!(spend_txn.len(), 1);
4348 assert_eq!(spend_txn[0].input.len(), 1);
4349 check_spends!(spend_txn[0], node_txn[0]);
4350 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4354 fn test_claim_on_remote_sizeable_push_msat() {
4355 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4356 // to_remote output is encumbered by a P2WPKH
4357 let chanmon_cfgs = create_chanmon_cfgs(2);
4358 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4359 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4360 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4362 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4363 nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4364 check_closed_broadcast!(nodes[0], true);
4365 check_added_monitors!(nodes[0], 1);
4366 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
4368 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4369 assert_eq!(node_txn.len(), 1);
4370 check_spends!(node_txn[0], chan.3);
4371 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
4373 mine_transaction(&nodes[1], &node_txn[0]);
4374 check_closed_broadcast!(nodes[1], true);
4375 check_added_monitors!(nodes[1], 1);
4376 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4377 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4379 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4380 assert_eq!(spend_txn.len(), 1);
4381 check_spends!(spend_txn[0], node_txn[0]);
4385 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4386 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4387 // to_remote output is encumbered by a P2WPKH
4389 let chanmon_cfgs = create_chanmon_cfgs(2);
4390 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4391 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4392 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4394 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4395 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4396 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4397 assert_eq!(revoked_local_txn[0].input.len(), 1);
4398 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4400 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4401 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4402 check_closed_broadcast!(nodes[1], true);
4403 check_added_monitors!(nodes[1], 1);
4404 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4406 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4407 mine_transaction(&nodes[1], &node_txn[0]);
4408 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4410 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4411 assert_eq!(spend_txn.len(), 3);
4412 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4413 check_spends!(spend_txn[1], node_txn[0]);
4414 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4418 fn test_static_spendable_outputs_preimage_tx() {
4419 let chanmon_cfgs = create_chanmon_cfgs(2);
4420 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4421 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4422 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4424 // Create some initial channels
4425 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4427 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4429 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4430 assert_eq!(commitment_tx[0].input.len(), 1);
4431 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4433 // Settle A's commitment tx on B's chain
4434 nodes[1].node.claim_funds(payment_preimage);
4435 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4436 check_added_monitors!(nodes[1], 1);
4437 mine_transaction(&nodes[1], &commitment_tx[0]);
4438 check_added_monitors!(nodes[1], 1);
4439 let events = nodes[1].node.get_and_clear_pending_msg_events();
4441 MessageSendEvent::UpdateHTLCs { .. } => {},
4442 _ => panic!("Unexpected event"),
4445 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4446 _ => panic!("Unexepected event"),
4449 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4450 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4451 assert_eq!(node_txn.len(), 1);
4452 check_spends!(node_txn[0], commitment_tx[0]);
4453 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4455 mine_transaction(&nodes[1], &node_txn[0]);
4456 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4457 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4459 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4460 assert_eq!(spend_txn.len(), 1);
4461 check_spends!(spend_txn[0], node_txn[0]);
4465 fn test_static_spendable_outputs_timeout_tx() {
4466 let chanmon_cfgs = create_chanmon_cfgs(2);
4467 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4468 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4469 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4471 // Create some initial channels
4472 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4474 // Rebalance the network a bit by relaying one payment through all the channels ...
4475 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4477 let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4479 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4480 assert_eq!(commitment_tx[0].input.len(), 1);
4481 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4483 // Settle A's commitment tx on B' chain
4484 mine_transaction(&nodes[1], &commitment_tx[0]);
4485 check_added_monitors!(nodes[1], 1);
4486 let events = nodes[1].node.get_and_clear_pending_msg_events();
4488 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4489 _ => panic!("Unexpected event"),
4491 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4493 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4494 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4495 assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4496 check_spends!(node_txn[0], commitment_tx[0].clone());
4497 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4499 mine_transaction(&nodes[1], &node_txn[0]);
4500 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4501 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4502 expect_payment_failed!(nodes[1], our_payment_hash, false);
4504 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4505 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4506 check_spends!(spend_txn[0], commitment_tx[0]);
4507 check_spends!(spend_txn[1], node_txn[0]);
4508 check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4512 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4513 let chanmon_cfgs = create_chanmon_cfgs(2);
4514 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4515 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4516 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4518 // Create some initial channels
4519 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4521 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4522 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4523 assert_eq!(revoked_local_txn[0].input.len(), 1);
4524 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4526 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4528 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4529 check_closed_broadcast!(nodes[1], true);
4530 check_added_monitors!(nodes[1], 1);
4531 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4533 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4534 assert_eq!(node_txn.len(), 1);
4535 assert_eq!(node_txn[0].input.len(), 2);
4536 check_spends!(node_txn[0], revoked_local_txn[0]);
4538 mine_transaction(&nodes[1], &node_txn[0]);
4539 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4541 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4542 assert_eq!(spend_txn.len(), 1);
4543 check_spends!(spend_txn[0], node_txn[0]);
4547 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4548 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4549 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4550 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4551 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4552 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4554 // Create some initial channels
4555 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4557 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4558 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4559 assert_eq!(revoked_local_txn[0].input.len(), 1);
4560 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4562 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4564 // A will generate HTLC-Timeout from revoked commitment tx
4565 mine_transaction(&nodes[0], &revoked_local_txn[0]);
4566 check_closed_broadcast!(nodes[0], true);
4567 check_added_monitors!(nodes[0], 1);
4568 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4569 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4571 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4572 assert_eq!(revoked_htlc_txn.len(), 1);
4573 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4574 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4575 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4576 assert_ne!(revoked_htlc_txn[0].lock_time.0, 0); // HTLC-Timeout
4578 // B will generate justice tx from A's revoked commitment/HTLC tx
4579 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4580 check_closed_broadcast!(nodes[1], true);
4581 check_added_monitors!(nodes[1], 1);
4582 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4584 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4585 assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4586 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4587 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4588 // transactions next...
4589 assert_eq!(node_txn[0].input.len(), 3);
4590 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4592 assert_eq!(node_txn[1].input.len(), 2);
4593 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4594 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4595 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4597 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4598 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4601 mine_transaction(&nodes[1], &node_txn[1]);
4602 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4604 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4605 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4606 assert_eq!(spend_txn.len(), 1);
4607 assert_eq!(spend_txn[0].input.len(), 1);
4608 check_spends!(spend_txn[0], node_txn[1]);
4612 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4613 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4614 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4615 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4616 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4617 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4619 // Create some initial channels
4620 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4622 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4623 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4624 assert_eq!(revoked_local_txn[0].input.len(), 1);
4625 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4627 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4628 assert_eq!(revoked_local_txn[0].output.len(), 2);
4630 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4632 // B will generate HTLC-Success from revoked commitment tx
4633 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4634 check_closed_broadcast!(nodes[1], true);
4635 check_added_monitors!(nodes[1], 1);
4636 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4637 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4639 assert_eq!(revoked_htlc_txn.len(), 1);
4640 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4641 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4642 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4644 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4645 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4646 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4648 // A will generate justice tx from B's revoked commitment/HTLC tx
4649 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4650 check_closed_broadcast!(nodes[0], true);
4651 check_added_monitors!(nodes[0], 1);
4652 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4654 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4655 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4657 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4658 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4659 // transactions next...
4660 assert_eq!(node_txn[0].input.len(), 2);
4661 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4662 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4663 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4665 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4666 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4669 assert_eq!(node_txn[1].input.len(), 1);
4670 check_spends!(node_txn[1], revoked_htlc_txn[0]);
4672 mine_transaction(&nodes[0], &node_txn[1]);
4673 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4675 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4676 // didn't try to generate any new transactions.
4678 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4679 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4680 assert_eq!(spend_txn.len(), 3);
4681 assert_eq!(spend_txn[0].input.len(), 1);
4682 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4683 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4684 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4685 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4689 fn test_onchain_to_onchain_claim() {
4690 // Test that in case of channel closure, we detect the state of output and claim HTLC
4691 // on downstream peer's remote commitment tx.
4692 // First, have C claim an HTLC against its own latest commitment transaction.
4693 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4695 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4698 let chanmon_cfgs = create_chanmon_cfgs(3);
4699 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4700 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4701 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4703 // Create some initial channels
4704 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4705 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4707 // Ensure all nodes are at the same height
4708 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4709 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4710 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4711 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4713 // Rebalance the network a bit by relaying one payment through all the channels ...
4714 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4715 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4717 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4718 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4719 check_spends!(commitment_tx[0], chan_2.3);
4720 nodes[2].node.claim_funds(payment_preimage);
4721 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4722 check_added_monitors!(nodes[2], 1);
4723 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4724 assert!(updates.update_add_htlcs.is_empty());
4725 assert!(updates.update_fail_htlcs.is_empty());
4726 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4727 assert!(updates.update_fail_malformed_htlcs.is_empty());
4729 mine_transaction(&nodes[2], &commitment_tx[0]);
4730 check_closed_broadcast!(nodes[2], true);
4731 check_added_monitors!(nodes[2], 1);
4732 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4734 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4735 assert_eq!(c_txn.len(), 1);
4736 check_spends!(c_txn[0], commitment_tx[0]);
4737 assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4738 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4739 assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
4741 // 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
4742 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![commitment_tx[0].clone(), c_txn[0].clone()]));
4743 check_added_monitors!(nodes[1], 1);
4744 let events = nodes[1].node.get_and_clear_pending_events();
4745 assert_eq!(events.len(), 2);
4747 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4748 _ => panic!("Unexpected event"),
4751 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
4752 assert_eq!(fee_earned_msat, Some(1000));
4753 assert_eq!(prev_channel_id, Some(chan_1.2));
4754 assert_eq!(claim_from_onchain_tx, true);
4755 assert_eq!(next_channel_id, Some(chan_2.2));
4756 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
4758 _ => panic!("Unexpected event"),
4760 check_added_monitors!(nodes[1], 1);
4761 let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4762 assert_eq!(msg_events.len(), 3);
4763 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut msg_events);
4764 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut msg_events);
4766 match nodes_2_event {
4767 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
4768 _ => panic!("Unexpected event"),
4771 match nodes_0_event {
4772 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, .. } } => {
4773 assert!(update_add_htlcs.is_empty());
4774 assert!(update_fail_htlcs.is_empty());
4775 assert_eq!(update_fulfill_htlcs.len(), 1);
4776 assert!(update_fail_malformed_htlcs.is_empty());
4777 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4779 _ => panic!("Unexpected event"),
4782 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
4783 match msg_events[0] {
4784 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4785 _ => panic!("Unexpected event"),
4788 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4789 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4790 mine_transaction(&nodes[1], &commitment_tx[0]);
4791 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4792 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4793 // ChannelMonitor: HTLC-Success tx
4794 assert_eq!(b_txn.len(), 1);
4795 check_spends!(b_txn[0], commitment_tx[0]);
4796 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4797 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4798 assert_eq!(b_txn[0].lock_time.0, nodes[1].best_block_info().1); // Success tx
4800 check_closed_broadcast!(nodes[1], true);
4801 check_added_monitors!(nodes[1], 1);
4805 fn test_duplicate_payment_hash_one_failure_one_success() {
4806 // Topology : A --> B --> C --> D
4807 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4808 // Note that because C will refuse to generate two payment secrets for the same payment hash,
4809 // we forward one of the payments onwards to D.
4810 let chanmon_cfgs = create_chanmon_cfgs(4);
4811 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4812 // When this test was written, the default base fee floated based on the HTLC count.
4813 // It is now fixed, so we simply set the fee to the expected value here.
4814 let mut config = test_default_channel_config();
4815 config.channel_config.forwarding_fee_base_msat = 196;
4816 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4817 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4818 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4820 create_announced_chan_between_nodes(&nodes, 0, 1);
4821 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4822 create_announced_chan_between_nodes(&nodes, 2, 3);
4824 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4825 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4826 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4827 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4828 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4830 let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
4832 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
4833 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4834 // script push size limit so that the below script length checks match
4835 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
4836 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV - 40)
4837 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
4838 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000);
4839 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
4841 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4842 assert_eq!(commitment_txn[0].input.len(), 1);
4843 check_spends!(commitment_txn[0], chan_2.3);
4845 mine_transaction(&nodes[1], &commitment_txn[0]);
4846 check_closed_broadcast!(nodes[1], true);
4847 check_added_monitors!(nodes[1], 1);
4848 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
4849 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
4851 let htlc_timeout_tx;
4852 { // Extract one of the two HTLC-Timeout transaction
4853 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4854 // ChannelMonitor: timeout tx * 2-or-3
4855 assert!(node_txn.len() == 2 || node_txn.len() == 3);
4857 check_spends!(node_txn[0], commitment_txn[0]);
4858 assert_eq!(node_txn[0].input.len(), 1);
4859 assert_eq!(node_txn[0].output.len(), 1);
4861 if node_txn.len() > 2 {
4862 check_spends!(node_txn[1], commitment_txn[0]);
4863 assert_eq!(node_txn[1].input.len(), 1);
4864 assert_eq!(node_txn[1].output.len(), 1);
4865 assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4867 check_spends!(node_txn[2], commitment_txn[0]);
4868 assert_eq!(node_txn[2].input.len(), 1);
4869 assert_eq!(node_txn[2].output.len(), 1);
4870 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
4872 check_spends!(node_txn[1], commitment_txn[0]);
4873 assert_eq!(node_txn[1].input.len(), 1);
4874 assert_eq!(node_txn[1].output.len(), 1);
4875 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4878 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4879 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4880 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
4881 // (with value 900 sats) will be claimed in the below `claim_funds` call.
4882 if node_txn.len() > 2 {
4883 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4884 htlc_timeout_tx = if node_txn[2].output[0].value < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
4886 htlc_timeout_tx = if node_txn[0].output[0].value < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
4890 nodes[2].node.claim_funds(our_payment_preimage);
4891 expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
4893 mine_transaction(&nodes[2], &commitment_txn[0]);
4894 check_added_monitors!(nodes[2], 2);
4895 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4896 let events = nodes[2].node.get_and_clear_pending_msg_events();
4898 MessageSendEvent::UpdateHTLCs { .. } => {},
4899 _ => panic!("Unexpected event"),
4902 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4903 _ => panic!("Unexepected event"),
4905 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4906 assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
4907 check_spends!(htlc_success_txn[0], commitment_txn[0]);
4908 check_spends!(htlc_success_txn[1], commitment_txn[0]);
4909 assert_eq!(htlc_success_txn[0].input.len(), 1);
4910 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4911 assert_eq!(htlc_success_txn[1].input.len(), 1);
4912 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4913 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
4914 assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
4916 mine_transaction(&nodes[1], &htlc_timeout_tx);
4917 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4918 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
4919 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4920 assert!(htlc_updates.update_add_htlcs.is_empty());
4921 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4922 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
4923 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4924 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4925 check_added_monitors!(nodes[1], 1);
4927 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4928 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4930 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4932 expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
4934 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4935 mine_transaction(&nodes[1], &htlc_success_txn[1]);
4936 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
4937 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4938 assert!(updates.update_add_htlcs.is_empty());
4939 assert!(updates.update_fail_htlcs.is_empty());
4940 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4941 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
4942 assert!(updates.update_fail_malformed_htlcs.is_empty());
4943 check_added_monitors!(nodes[1], 1);
4945 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4946 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4947 expect_payment_sent(&nodes[0], our_payment_preimage, None, true, true);
4951 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4952 let chanmon_cfgs = create_chanmon_cfgs(2);
4953 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4954 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4955 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4957 // Create some initial channels
4958 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4960 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
4961 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4962 assert_eq!(local_txn.len(), 1);
4963 assert_eq!(local_txn[0].input.len(), 1);
4964 check_spends!(local_txn[0], chan_1.3);
4966 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4967 nodes[1].node.claim_funds(payment_preimage);
4968 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
4969 check_added_monitors!(nodes[1], 1);
4971 mine_transaction(&nodes[1], &local_txn[0]);
4972 check_added_monitors!(nodes[1], 1);
4973 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4974 let events = nodes[1].node.get_and_clear_pending_msg_events();
4976 MessageSendEvent::UpdateHTLCs { .. } => {},
4977 _ => panic!("Unexpected event"),
4980 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4981 _ => panic!("Unexepected event"),
4984 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4985 assert_eq!(node_txn.len(), 1);
4986 assert_eq!(node_txn[0].input.len(), 1);
4987 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4988 check_spends!(node_txn[0], local_txn[0]);
4992 mine_transaction(&nodes[1], &node_tx);
4993 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4995 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4996 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4997 assert_eq!(spend_txn.len(), 1);
4998 assert_eq!(spend_txn[0].input.len(), 1);
4999 check_spends!(spend_txn[0], node_tx);
5000 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5003 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5004 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5005 // unrevoked commitment transaction.
5006 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5007 // a remote RAA before they could be failed backwards (and combinations thereof).
5008 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5009 // use the same payment hashes.
5010 // Thus, we use a six-node network:
5015 // And test where C fails back to A/B when D announces its latest commitment transaction
5016 let chanmon_cfgs = create_chanmon_cfgs(6);
5017 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5018 // When this test was written, the default base fee floated based on the HTLC count.
5019 // It is now fixed, so we simply set the fee to the expected value here.
5020 let mut config = test_default_channel_config();
5021 config.channel_config.forwarding_fee_base_msat = 196;
5022 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5023 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5024 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5026 let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2);
5027 let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5028 let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5029 let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
5030 let chan_3_5 = create_announced_chan_between_nodes(&nodes, 3, 5);
5032 // Rebalance and check output sanity...
5033 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5034 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5035 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
5037 let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
5038 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().context.holder_dust_limit_satoshis;
5040 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
5042 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
5043 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5045 send_along_route_with_secret(&nodes[1], route.clone(), &[&[&nodes[2], &nodes[3], &nodes[5]]], ds_dust_limit*1000, payment_hash_1, nodes[5].node.create_inbound_payment_for_hash(payment_hash_1, None, 7200, None).unwrap()); // not added < dust limit + HTLC tx fee
5047 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], ds_dust_limit*1000, payment_hash_2, nodes[5].node.create_inbound_payment_for_hash(payment_hash_2, None, 7200, None).unwrap()); // not added < dust limit + HTLC tx fee
5049 let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5051 let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5052 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5054 send_along_route_with_secret(&nodes[1], route.clone(), &[&[&nodes[2], &nodes[3], &nodes[5]]], 1000000, payment_hash_3, nodes[5].node.create_inbound_payment_for_hash(payment_hash_3, None, 7200, None).unwrap());
5056 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], 1000000, payment_hash_4, nodes[5].node.create_inbound_payment_for_hash(payment_hash_4, None, 7200, None).unwrap());
5059 let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5061 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5062 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], ds_dust_limit*1000, payment_hash_5, nodes[5].node.create_inbound_payment_for_hash(payment_hash_5, None, 7200, None).unwrap()); // not added < dust limit + HTLC tx fee
5065 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
5067 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5068 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], 1000000, payment_hash_6, nodes[5].node.create_inbound_payment_for_hash(payment_hash_6, None, 7200, None).unwrap());
5070 // Double-check that six of the new HTLC were added
5071 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5072 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5073 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5074 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5076 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5077 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5078 nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5079 nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5080 nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5081 nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5082 check_added_monitors!(nodes[4], 0);
5084 let failed_destinations = vec![
5085 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5086 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5087 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5088 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5090 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5091 check_added_monitors!(nodes[4], 1);
5093 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5094 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5095 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5096 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5097 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5098 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5100 // Fail 3rd below-dust and 7th above-dust HTLCs
5101 nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5102 nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5103 check_added_monitors!(nodes[5], 0);
5105 let failed_destinations_2 = vec![
5106 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5107 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5109 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5110 check_added_monitors!(nodes[5], 1);
5112 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5113 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5114 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5115 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5117 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5119 // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5120 let failed_destinations_3 = vec![
5121 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5122 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5123 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5124 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5125 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5126 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5128 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5129 check_added_monitors!(nodes[3], 1);
5130 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5131 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5132 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5133 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5134 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5135 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5136 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5137 if deliver_last_raa {
5138 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5140 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5143 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5144 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5145 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5146 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5148 // We now broadcast the latest commitment transaction, which *should* result in failures for
5149 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5150 // the non-broadcast above-dust HTLCs.
5152 // Alternatively, we may broadcast the previous commitment transaction, which should only
5153 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5154 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5156 if announce_latest {
5157 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5159 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5161 let events = nodes[2].node.get_and_clear_pending_events();
5162 let close_event = if deliver_last_raa {
5163 assert_eq!(events.len(), 2 + 6);
5164 events.last().clone().unwrap()
5166 assert_eq!(events.len(), 1);
5167 events.last().clone().unwrap()
5170 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5171 _ => panic!("Unexpected event"),
5174 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5175 check_closed_broadcast!(nodes[2], true);
5176 if deliver_last_raa {
5177 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5179 let expected_destinations: Vec<HTLCDestination> = repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(3).collect();
5180 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5182 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5183 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5185 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5188 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5190 check_added_monitors!(nodes[2], 3);
5192 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5193 assert_eq!(cs_msgs.len(), 2);
5194 let mut a_done = false;
5195 for msg in cs_msgs {
5197 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5198 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5199 // should be failed-backwards here.
5200 let target = if *node_id == nodes[0].node.get_our_node_id() {
5201 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5202 for htlc in &updates.update_fail_htlcs {
5203 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 });
5205 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5210 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5211 for htlc in &updates.update_fail_htlcs {
5212 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5214 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5215 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5218 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5219 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5220 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5221 if announce_latest {
5222 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5223 if *node_id == nodes[0].node.get_our_node_id() {
5224 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5227 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5229 _ => panic!("Unexpected event"),
5233 let as_events = nodes[0].node.get_and_clear_pending_events();
5234 assert_eq!(as_events.len(), if announce_latest { 10 } else { 6 });
5235 let mut as_failds = HashSet::new();
5236 let mut as_updates = 0;
5237 for event in as_events.iter() {
5238 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5239 assert!(as_failds.insert(*payment_hash));
5240 if *payment_hash != payment_hash_2 {
5241 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5243 assert!(!payment_failed_permanently);
5245 if let PathFailure::OnPath { network_update: Some(_) } = failure {
5248 } else if let &Event::PaymentFailed { .. } = event {
5249 } else { panic!("Unexpected event"); }
5251 assert!(as_failds.contains(&payment_hash_1));
5252 assert!(as_failds.contains(&payment_hash_2));
5253 if announce_latest {
5254 assert!(as_failds.contains(&payment_hash_3));
5255 assert!(as_failds.contains(&payment_hash_5));
5257 assert!(as_failds.contains(&payment_hash_6));
5259 let bs_events = nodes[1].node.get_and_clear_pending_events();
5260 assert_eq!(bs_events.len(), if announce_latest { 8 } else { 6 });
5261 let mut bs_failds = HashSet::new();
5262 let mut bs_updates = 0;
5263 for event in bs_events.iter() {
5264 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5265 assert!(bs_failds.insert(*payment_hash));
5266 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5267 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5269 assert!(!payment_failed_permanently);
5271 if let PathFailure::OnPath { network_update: Some(_) } = failure {
5274 } else if let &Event::PaymentFailed { .. } = event {
5275 } else { panic!("Unexpected event"); }
5277 assert!(bs_failds.contains(&payment_hash_1));
5278 assert!(bs_failds.contains(&payment_hash_2));
5279 if announce_latest {
5280 assert!(bs_failds.contains(&payment_hash_4));
5282 assert!(bs_failds.contains(&payment_hash_5));
5284 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5285 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5286 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5287 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5288 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5289 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5293 fn test_fail_backwards_latest_remote_announce_a() {
5294 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5298 fn test_fail_backwards_latest_remote_announce_b() {
5299 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5303 fn test_fail_backwards_previous_remote_announce() {
5304 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5305 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5306 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5310 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5311 let chanmon_cfgs = create_chanmon_cfgs(2);
5312 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5313 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5314 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5316 // Create some initial channels
5317 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5319 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5320 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5321 assert_eq!(local_txn[0].input.len(), 1);
5322 check_spends!(local_txn[0], chan_1.3);
5324 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5325 mine_transaction(&nodes[0], &local_txn[0]);
5326 check_closed_broadcast!(nodes[0], true);
5327 check_added_monitors!(nodes[0], 1);
5328 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5329 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5331 let htlc_timeout = {
5332 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5333 assert_eq!(node_txn.len(), 1);
5334 assert_eq!(node_txn[0].input.len(), 1);
5335 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5336 check_spends!(node_txn[0], local_txn[0]);
5340 mine_transaction(&nodes[0], &htlc_timeout);
5341 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5342 expect_payment_failed!(nodes[0], our_payment_hash, false);
5344 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5345 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5346 assert_eq!(spend_txn.len(), 3);
5347 check_spends!(spend_txn[0], local_txn[0]);
5348 assert_eq!(spend_txn[1].input.len(), 1);
5349 check_spends!(spend_txn[1], htlc_timeout);
5350 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5351 assert_eq!(spend_txn[2].input.len(), 2);
5352 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5353 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5354 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5358 fn test_key_derivation_params() {
5359 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5360 // manager rotation to test that `channel_keys_id` returned in
5361 // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5362 // then derive a `delayed_payment_key`.
5364 let chanmon_cfgs = create_chanmon_cfgs(3);
5366 // We manually create the node configuration to backup the seed.
5367 let seed = [42; 32];
5368 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5369 let chain_monitor = test_utils::TestChainMonitor::new(Some(&chanmon_cfgs[0].chain_source), &chanmon_cfgs[0].tx_broadcaster, &chanmon_cfgs[0].logger, &chanmon_cfgs[0].fee_estimator, &chanmon_cfgs[0].persister, &keys_manager);
5370 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[0].logger));
5371 let scorer = Mutex::new(test_utils::TestScorer::new());
5372 let router = test_utils::TestRouter::new(network_graph.clone(), &scorer);
5373 let node = NodeCfg { chain_source: &chanmon_cfgs[0].chain_source, logger: &chanmon_cfgs[0].logger, tx_broadcaster: &chanmon_cfgs[0].tx_broadcaster, fee_estimator: &chanmon_cfgs[0].fee_estimator, router, chain_monitor, keys_manager: &keys_manager, network_graph, node_seed: seed, override_init_features: alloc::rc::Rc::new(core::cell::RefCell::new(None)) };
5374 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5375 node_cfgs.remove(0);
5376 node_cfgs.insert(0, node);
5378 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5379 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5381 // Create some initial channels
5382 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5384 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2);
5385 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5386 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5388 // Ensure all nodes are at the same height
5389 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5390 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5391 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5392 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5394 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5395 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5396 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5397 assert_eq!(local_txn_1[0].input.len(), 1);
5398 check_spends!(local_txn_1[0], chan_1.3);
5400 // We check funding pubkey are unique
5401 let (from_0_funding_key_0, from_0_funding_key_1) = (PublicKey::from_slice(&local_txn_0[0].input[0].witness.to_vec()[3][2..35]), PublicKey::from_slice(&local_txn_0[0].input[0].witness.to_vec()[3][36..69]));
5402 let (from_1_funding_key_0, from_1_funding_key_1) = (PublicKey::from_slice(&local_txn_1[0].input[0].witness.to_vec()[3][2..35]), PublicKey::from_slice(&local_txn_1[0].input[0].witness.to_vec()[3][36..69]));
5403 if from_0_funding_key_0 == from_1_funding_key_0
5404 || from_0_funding_key_0 == from_1_funding_key_1
5405 || from_0_funding_key_1 == from_1_funding_key_0
5406 || from_0_funding_key_1 == from_1_funding_key_1 {
5407 panic!("Funding pubkeys aren't unique");
5410 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5411 mine_transaction(&nodes[0], &local_txn_1[0]);
5412 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5413 check_closed_broadcast!(nodes[0], true);
5414 check_added_monitors!(nodes[0], 1);
5415 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5417 let htlc_timeout = {
5418 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5419 assert_eq!(node_txn.len(), 1);
5420 assert_eq!(node_txn[0].input.len(), 1);
5421 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5422 check_spends!(node_txn[0], local_txn_1[0]);
5426 mine_transaction(&nodes[0], &htlc_timeout);
5427 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5428 expect_payment_failed!(nodes[0], our_payment_hash, false);
5430 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5431 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5432 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5433 assert_eq!(spend_txn.len(), 3);
5434 check_spends!(spend_txn[0], local_txn_1[0]);
5435 assert_eq!(spend_txn[1].input.len(), 1);
5436 check_spends!(spend_txn[1], htlc_timeout);
5437 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5438 assert_eq!(spend_txn[2].input.len(), 2);
5439 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5440 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5441 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5445 fn test_static_output_closing_tx() {
5446 let chanmon_cfgs = create_chanmon_cfgs(2);
5447 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5448 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5449 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5451 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5453 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5454 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5456 mine_transaction(&nodes[0], &closing_tx);
5457 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
5458 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5460 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5461 assert_eq!(spend_txn.len(), 1);
5462 check_spends!(spend_txn[0], closing_tx);
5464 mine_transaction(&nodes[1], &closing_tx);
5465 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
5466 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5468 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5469 assert_eq!(spend_txn.len(), 1);
5470 check_spends!(spend_txn[0], closing_tx);
5473 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5474 let chanmon_cfgs = create_chanmon_cfgs(2);
5475 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5476 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5477 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5478 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5480 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5482 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5483 // present in B's local commitment transaction, but none of A's commitment transactions.
5484 nodes[1].node.claim_funds(payment_preimage);
5485 check_added_monitors!(nodes[1], 1);
5486 expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5488 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5489 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5490 expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
5492 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5493 check_added_monitors!(nodes[0], 1);
5494 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5495 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5496 check_added_monitors!(nodes[1], 1);
5498 let starting_block = nodes[1].best_block_info();
5499 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5500 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5501 connect_block(&nodes[1], &block);
5502 block.header.prev_blockhash = block.block_hash();
5504 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5505 check_closed_broadcast!(nodes[1], true);
5506 check_added_monitors!(nodes[1], 1);
5507 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
5510 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5511 let chanmon_cfgs = create_chanmon_cfgs(2);
5512 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5513 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5514 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5515 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5517 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5518 nodes[0].node.send_payment_with_route(&route, payment_hash,
5519 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
5520 check_added_monitors!(nodes[0], 1);
5522 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5524 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5525 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5526 // to "time out" the HTLC.
5528 let starting_block = nodes[1].best_block_info();
5529 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5531 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5532 connect_block(&nodes[0], &block);
5533 block.header.prev_blockhash = block.block_hash();
5535 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5536 check_closed_broadcast!(nodes[0], true);
5537 check_added_monitors!(nodes[0], 1);
5538 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5541 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5542 let chanmon_cfgs = create_chanmon_cfgs(3);
5543 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5544 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5545 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5546 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5548 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5549 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5550 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5551 // actually revoked.
5552 let htlc_value = if use_dust { 50000 } else { 3000000 };
5553 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5554 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5555 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5556 check_added_monitors!(nodes[1], 1);
5558 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5559 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5560 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5561 check_added_monitors!(nodes[0], 1);
5562 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5563 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5564 check_added_monitors!(nodes[1], 1);
5565 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5566 check_added_monitors!(nodes[1], 1);
5567 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5569 if check_revoke_no_close {
5570 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5571 check_added_monitors!(nodes[0], 1);
5574 let starting_block = nodes[1].best_block_info();
5575 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5576 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5577 connect_block(&nodes[0], &block);
5578 block.header.prev_blockhash = block.block_hash();
5580 if !check_revoke_no_close {
5581 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5582 check_closed_broadcast!(nodes[0], true);
5583 check_added_monitors!(nodes[0], 1);
5584 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5586 expect_payment_failed!(nodes[0], our_payment_hash, true);
5590 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5591 // There are only a few cases to test here:
5592 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5593 // broadcastable commitment transactions result in channel closure,
5594 // * its included in an unrevoked-but-previous remote commitment transaction,
5595 // * its included in the latest remote or local commitment transactions.
5596 // We test each of the three possible commitment transactions individually and use both dust and
5598 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5599 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5600 // tested for at least one of the cases in other tests.
5602 fn htlc_claim_single_commitment_only_a() {
5603 do_htlc_claim_local_commitment_only(true);
5604 do_htlc_claim_local_commitment_only(false);
5606 do_htlc_claim_current_remote_commitment_only(true);
5607 do_htlc_claim_current_remote_commitment_only(false);
5611 fn htlc_claim_single_commitment_only_b() {
5612 do_htlc_claim_previous_remote_commitment_only(true, false);
5613 do_htlc_claim_previous_remote_commitment_only(false, false);
5614 do_htlc_claim_previous_remote_commitment_only(true, true);
5615 do_htlc_claim_previous_remote_commitment_only(false, true);
5620 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5621 let chanmon_cfgs = create_chanmon_cfgs(2);
5622 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5623 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5624 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5625 // Force duplicate randomness for every get-random call
5626 for node in nodes.iter() {
5627 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5630 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5631 let channel_value_satoshis=10000;
5632 let push_msat=10001;
5633 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5634 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5635 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5636 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5638 // Create a second channel with the same random values. This used to panic due to a colliding
5639 // channel_id, but now panics due to a colliding outbound SCID alias.
5640 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5644 fn bolt2_open_channel_sending_node_checks_part2() {
5645 let chanmon_cfgs = create_chanmon_cfgs(2);
5646 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5647 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5648 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5650 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5651 let channel_value_satoshis=2^24;
5652 let push_msat=10001;
5653 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5655 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5656 let channel_value_satoshis=10000;
5657 // Test when push_msat is equal to 1000 * funding_satoshis.
5658 let push_msat=1000*channel_value_satoshis+1;
5659 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5661 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5662 let channel_value_satoshis=10000;
5663 let push_msat=10001;
5664 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_ok()); //Create a valid channel
5665 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5666 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5668 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5669 // Only the least-significant bit of channel_flags is currently defined resulting in channel_flags only having one of two possible states 0 or 1
5670 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5672 // BOLT #2 spec: Sending node should set to_self_delay sufficient to ensure the sender can irreversibly spend a commitment transaction output, in case of misbehaviour by the receiver.
5673 assert!(BREAKDOWN_TIMEOUT>0);
5674 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5676 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5677 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5678 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5680 // BOLT #2 spec: Sending node must set funding_pubkey, revocation_basepoint, htlc_basepoint, payment_basepoint, and delayed_payment_basepoint to valid DER-encoded, compressed, secp256k1 pubkeys.
5681 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5682 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5683 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5684 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5685 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5689 fn bolt2_open_channel_sane_dust_limit() {
5690 let chanmon_cfgs = create_chanmon_cfgs(2);
5691 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5692 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5693 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5695 let channel_value_satoshis=1000000;
5696 let push_msat=10001;
5697 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5698 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5699 node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5700 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5702 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5703 let events = nodes[1].node.get_and_clear_pending_msg_events();
5704 let err_msg = match events[0] {
5705 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5708 _ => panic!("Unexpected event"),
5710 assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5713 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5714 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5715 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5716 // is no longer affordable once it's freed.
5718 fn test_fail_holding_cell_htlc_upon_free() {
5719 let chanmon_cfgs = create_chanmon_cfgs(2);
5720 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5721 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5722 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5723 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5725 // First nodes[0] generates an update_fee, setting the channel's
5726 // pending_update_fee.
5728 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5729 *feerate_lock += 20;
5731 nodes[0].node.timer_tick_occurred();
5732 check_added_monitors!(nodes[0], 1);
5734 let events = nodes[0].node.get_and_clear_pending_msg_events();
5735 assert_eq!(events.len(), 1);
5736 let (update_msg, commitment_signed) = match events[0] {
5737 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5738 (update_fee.as_ref(), commitment_signed)
5740 _ => panic!("Unexpected event"),
5743 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5745 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5746 let channel_reserve = chan_stat.channel_reserve_msat;
5747 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5748 let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
5750 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5751 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
5752 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5754 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5755 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5756 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5757 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5758 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5760 // Flush the pending fee update.
5761 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5762 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5763 check_added_monitors!(nodes[1], 1);
5764 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5765 check_added_monitors!(nodes[0], 1);
5767 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5768 // HTLC, but now that the fee has been raised the payment will now fail, causing
5769 // us to surface its failure to the user.
5770 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5771 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5772 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Freeing holding cell with 1 HTLC updates in channel {}", hex::encode(chan.2)), 1);
5774 // Check that the payment failed to be sent out.
5775 let events = nodes[0].node.get_and_clear_pending_events();
5776 assert_eq!(events.len(), 2);
5778 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5779 assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5780 assert_eq!(our_payment_hash.clone(), *payment_hash);
5781 assert_eq!(*payment_failed_permanently, false);
5782 assert_eq!(*short_channel_id, Some(route.paths[0].hops[0].short_channel_id));
5784 _ => panic!("Unexpected event"),
5787 &Event::PaymentFailed { ref payment_hash, .. } => {
5788 assert_eq!(our_payment_hash.clone(), *payment_hash);
5790 _ => panic!("Unexpected event"),
5794 // Test that if multiple HTLCs are released from the holding cell and one is
5795 // valid but the other is no longer valid upon release, the valid HTLC can be
5796 // successfully completed while the other one fails as expected.
5798 fn test_free_and_fail_holding_cell_htlcs() {
5799 let chanmon_cfgs = create_chanmon_cfgs(2);
5800 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5801 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5802 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5803 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5805 // First nodes[0] generates an update_fee, setting the channel's
5806 // pending_update_fee.
5808 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5809 *feerate_lock += 200;
5811 nodes[0].node.timer_tick_occurred();
5812 check_added_monitors!(nodes[0], 1);
5814 let events = nodes[0].node.get_and_clear_pending_msg_events();
5815 assert_eq!(events.len(), 1);
5816 let (update_msg, commitment_signed) = match events[0] {
5817 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5818 (update_fee.as_ref(), commitment_signed)
5820 _ => panic!("Unexpected event"),
5823 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5825 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5826 let channel_reserve = chan_stat.channel_reserve_msat;
5827 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5828 let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
5830 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5832 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features) - amt_1;
5833 let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5834 let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5836 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5837 nodes[0].node.send_payment_with_route(&route_1, payment_hash_1,
5838 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
5839 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5840 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
5841 let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
5842 nodes[0].node.send_payment_with_route(&route_2, payment_hash_2,
5843 RecipientOnionFields::secret_only(payment_secret_2), payment_id_2).unwrap();
5844 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5845 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
5847 // Flush the pending fee update.
5848 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5849 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5850 check_added_monitors!(nodes[1], 1);
5851 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
5852 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5853 check_added_monitors!(nodes[0], 2);
5855 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
5856 // but now that the fee has been raised the second payment will now fail, causing us
5857 // to surface its failure to the user. The first payment should succeed.
5858 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5859 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5860 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Freeing holding cell with 2 HTLC updates in channel {}", hex::encode(chan.2)), 1);
5862 // Check that the second payment failed to be sent out.
5863 let events = nodes[0].node.get_and_clear_pending_events();
5864 assert_eq!(events.len(), 2);
5866 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5867 assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
5868 assert_eq!(payment_hash_2.clone(), *payment_hash);
5869 assert_eq!(*payment_failed_permanently, false);
5870 assert_eq!(*short_channel_id, Some(route_2.paths[0].hops[0].short_channel_id));
5872 _ => panic!("Unexpected event"),
5875 &Event::PaymentFailed { ref payment_hash, .. } => {
5876 assert_eq!(payment_hash_2.clone(), *payment_hash);
5878 _ => panic!("Unexpected event"),
5881 // Complete the first payment and the RAA from the fee update.
5882 let (payment_event, send_raa_event) = {
5883 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
5884 assert_eq!(msgs.len(), 2);
5885 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
5887 let raa = match send_raa_event {
5888 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
5889 _ => panic!("Unexpected event"),
5891 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5892 check_added_monitors!(nodes[1], 1);
5893 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5894 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5895 let events = nodes[1].node.get_and_clear_pending_events();
5896 assert_eq!(events.len(), 1);
5898 Event::PendingHTLCsForwardable { .. } => {},
5899 _ => panic!("Unexpected event"),
5901 nodes[1].node.process_pending_htlc_forwards();
5902 let events = nodes[1].node.get_and_clear_pending_events();
5903 assert_eq!(events.len(), 1);
5905 Event::PaymentClaimable { .. } => {},
5906 _ => panic!("Unexpected event"),
5908 nodes[1].node.claim_funds(payment_preimage_1);
5909 check_added_monitors!(nodes[1], 1);
5910 expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
5912 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5913 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
5914 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
5915 expect_payment_sent!(nodes[0], payment_preimage_1);
5918 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
5919 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
5920 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
5923 fn test_fail_holding_cell_htlc_upon_free_multihop() {
5924 let chanmon_cfgs = create_chanmon_cfgs(3);
5925 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5926 // Avoid having to include routing fees in calculations
5927 let mut config = test_default_channel_config();
5928 config.channel_config.forwarding_fee_base_msat = 0;
5929 config.channel_config.forwarding_fee_proportional_millionths = 0;
5930 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5931 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5932 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5933 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
5935 // First nodes[1] generates an update_fee, setting the channel's
5936 // pending_update_fee.
5938 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
5939 *feerate_lock += 20;
5941 nodes[1].node.timer_tick_occurred();
5942 check_added_monitors!(nodes[1], 1);
5944 let events = nodes[1].node.get_and_clear_pending_msg_events();
5945 assert_eq!(events.len(), 1);
5946 let (update_msg, commitment_signed) = match events[0] {
5947 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5948 (update_fee.as_ref(), commitment_signed)
5950 _ => panic!("Unexpected event"),
5953 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
5955 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan_0_1.2);
5956 let channel_reserve = chan_stat.channel_reserve_msat;
5957 let feerate = get_feerate!(nodes[0], nodes[1], chan_0_1.2);
5958 let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_0_1.2);
5960 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5961 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
5962 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
5963 let payment_event = {
5964 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5965 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5966 check_added_monitors!(nodes[0], 1);
5968 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5969 assert_eq!(events.len(), 1);
5971 SendEvent::from_event(events.remove(0))
5973 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5974 check_added_monitors!(nodes[1], 0);
5975 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5976 expect_pending_htlcs_forwardable!(nodes[1]);
5978 chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
5979 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5981 // Flush the pending fee update.
5982 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
5983 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5984 check_added_monitors!(nodes[2], 1);
5985 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
5986 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
5987 check_added_monitors!(nodes[1], 2);
5989 // A final RAA message is generated to finalize the fee update.
5990 let events = nodes[1].node.get_and_clear_pending_msg_events();
5991 assert_eq!(events.len(), 1);
5993 let raa_msg = match &events[0] {
5994 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
5997 _ => panic!("Unexpected event"),
6000 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6001 check_added_monitors!(nodes[2], 1);
6002 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6004 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6005 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6006 assert_eq!(process_htlc_forwards_event.len(), 2);
6007 match &process_htlc_forwards_event[0] {
6008 &Event::PendingHTLCsForwardable { .. } => {},
6009 _ => panic!("Unexpected event"),
6012 // In response, we call ChannelManager's process_pending_htlc_forwards
6013 nodes[1].node.process_pending_htlc_forwards();
6014 check_added_monitors!(nodes[1], 1);
6016 // This causes the HTLC to be failed backwards.
6017 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6018 assert_eq!(fail_event.len(), 1);
6019 let (fail_msg, commitment_signed) = match &fail_event[0] {
6020 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6021 assert_eq!(updates.update_add_htlcs.len(), 0);
6022 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6023 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6024 assert_eq!(updates.update_fail_htlcs.len(), 1);
6025 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6027 _ => panic!("Unexpected event"),
6030 // Pass the failure messages back to nodes[0].
6031 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6032 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6034 // Complete the HTLC failure+removal process.
6035 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6036 check_added_monitors!(nodes[0], 1);
6037 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6038 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6039 check_added_monitors!(nodes[1], 2);
6040 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6041 assert_eq!(final_raa_event.len(), 1);
6042 let raa = match &final_raa_event[0] {
6043 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6044 _ => panic!("Unexpected event"),
6046 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6047 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6048 check_added_monitors!(nodes[0], 1);
6051 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6052 // 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.
6053 //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.
6056 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6057 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6058 let chanmon_cfgs = create_chanmon_cfgs(2);
6059 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6060 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6061 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6062 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6064 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6065 route.paths[0].hops[0].fee_msat = 100;
6067 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6068 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6069 ), true, APIError::ChannelUnavailable { .. }, {});
6070 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6074 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6075 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6076 let chanmon_cfgs = create_chanmon_cfgs(2);
6077 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6078 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6079 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6080 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6082 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6083 route.paths[0].hops[0].fee_msat = 0;
6084 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6085 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)),
6086 true, APIError::ChannelUnavailable { ref err },
6087 assert_eq!(err, "Cannot send 0-msat HTLC"));
6089 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6090 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send 0-msat HTLC", 1);
6094 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6095 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6096 let chanmon_cfgs = create_chanmon_cfgs(2);
6097 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6098 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6099 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6100 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6102 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6103 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6104 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6105 check_added_monitors!(nodes[0], 1);
6106 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6107 updates.update_add_htlcs[0].amount_msat = 0;
6109 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6110 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6111 check_closed_broadcast!(nodes[1], true).unwrap();
6112 check_added_monitors!(nodes[1], 1);
6113 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() },
6114 [nodes[0].node.get_our_node_id()], 100000);
6118 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6119 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6120 //It is enforced when constructing a route.
6121 let chanmon_cfgs = create_chanmon_cfgs(2);
6122 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6123 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6124 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6125 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6127 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6128 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
6129 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);
6130 route.paths[0].hops.last_mut().unwrap().cltv_expiry_delta = 500000001;
6131 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6132 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6133 ), true, APIError::InvalidRoute { ref err },
6134 assert_eq!(err, &"Channel CLTV overflowed?"));
6138 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6139 //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.
6140 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6141 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6142 let chanmon_cfgs = create_chanmon_cfgs(2);
6143 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6144 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6145 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6146 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6147 let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6148 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context.counterparty_max_accepted_htlcs as u64;
6150 // Fetch a route in advance as we will be unable to once we're unable to send.
6151 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6152 for i in 0..max_accepted_htlcs {
6153 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6154 let payment_event = {
6155 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6156 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6157 check_added_monitors!(nodes[0], 1);
6159 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6160 assert_eq!(events.len(), 1);
6161 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6162 assert_eq!(htlcs[0].htlc_id, i);
6166 SendEvent::from_event(events.remove(0))
6168 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6169 check_added_monitors!(nodes[1], 0);
6170 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6172 expect_pending_htlcs_forwardable!(nodes[1]);
6173 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6175 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6176 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6177 ), true, APIError::ChannelUnavailable { .. }, {});
6179 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6183 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6184 //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.
6185 let chanmon_cfgs = create_chanmon_cfgs(2);
6186 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6187 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6188 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6189 let channel_value = 100000;
6190 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6191 let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6193 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6195 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6196 // Manually create a route over our max in flight (which our router normally automatically
6198 route.paths[0].hops[0].fee_msat = max_in_flight + 1;
6199 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6200 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6201 ), true, APIError::ChannelUnavailable { .. }, {});
6202 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6204 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6207 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6209 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6210 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6211 let chanmon_cfgs = create_chanmon_cfgs(2);
6212 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6213 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6214 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6215 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6216 let htlc_minimum_msat: u64;
6218 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6219 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6220 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6221 htlc_minimum_msat = channel.context.get_holder_htlc_minimum_msat();
6224 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6225 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6226 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6227 check_added_monitors!(nodes[0], 1);
6228 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6229 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6230 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6231 assert!(nodes[1].node.list_channels().is_empty());
6232 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6233 assert!(regex::Regex::new(r"Remote side tried to send less than our minimum HTLC value\. Lower limit: \(\d+\)\. Actual: \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6234 check_added_monitors!(nodes[1], 1);
6235 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6239 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6240 //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
6241 let chanmon_cfgs = create_chanmon_cfgs(2);
6242 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6243 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6244 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6245 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6247 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6248 let channel_reserve = chan_stat.channel_reserve_msat;
6249 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6250 let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
6251 // The 2* and +1 are for the fee spike reserve.
6252 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
6254 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6255 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6256 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6257 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6258 check_added_monitors!(nodes[0], 1);
6259 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6261 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6262 // at this time channel-initiatee receivers are not required to enforce that senders
6263 // respect the fee_spike_reserve.
6264 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6265 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6267 assert!(nodes[1].node.list_channels().is_empty());
6268 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6269 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6270 check_added_monitors!(nodes[1], 1);
6271 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6275 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6276 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6277 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6278 let chanmon_cfgs = create_chanmon_cfgs(2);
6279 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6280 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6281 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6282 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6284 let send_amt = 3999999;
6285 let (mut route, our_payment_hash, _, our_payment_secret) =
6286 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
6287 route.paths[0].hops[0].fee_msat = send_amt;
6288 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6289 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6290 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6291 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
6292 &route.paths[0], send_amt, RecipientOnionFields::secret_only(our_payment_secret), cur_height, &None).unwrap();
6293 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
6295 let mut msg = msgs::UpdateAddHTLC {
6299 payment_hash: our_payment_hash,
6300 cltv_expiry: htlc_cltv,
6301 onion_routing_packet: onion_packet.clone(),
6302 skimmed_fee_msat: None,
6306 msg.htlc_id = i as u64;
6307 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6309 msg.htlc_id = (50) as u64;
6310 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6312 assert!(nodes[1].node.list_channels().is_empty());
6313 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6314 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6315 check_added_monitors!(nodes[1], 1);
6316 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6320 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6321 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6322 let chanmon_cfgs = create_chanmon_cfgs(2);
6323 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6324 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6325 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6326 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6328 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6329 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6330 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6331 check_added_monitors!(nodes[0], 1);
6332 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6333 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6334 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6336 assert!(nodes[1].node.list_channels().is_empty());
6337 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6338 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6339 check_added_monitors!(nodes[1], 1);
6340 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 1000000);
6344 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6345 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6346 let chanmon_cfgs = create_chanmon_cfgs(2);
6347 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6348 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6349 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6351 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6352 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6353 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6354 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6355 check_added_monitors!(nodes[0], 1);
6356 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6357 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6358 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6360 assert!(nodes[1].node.list_channels().is_empty());
6361 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6362 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6363 check_added_monitors!(nodes[1], 1);
6364 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6368 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6369 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6370 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6371 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6372 let chanmon_cfgs = create_chanmon_cfgs(2);
6373 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6374 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6375 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6377 create_announced_chan_between_nodes(&nodes, 0, 1);
6378 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6379 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6380 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6381 check_added_monitors!(nodes[0], 1);
6382 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6383 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6385 //Disconnect and Reconnect
6386 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
6387 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
6388 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
6389 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
6391 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6392 assert_eq!(reestablish_1.len(), 1);
6393 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
6394 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
6396 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6397 assert_eq!(reestablish_2.len(), 1);
6398 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6399 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6400 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6401 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6404 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6405 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6406 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6407 check_added_monitors!(nodes[1], 1);
6408 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6410 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6412 assert!(nodes[1].node.list_channels().is_empty());
6413 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6414 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6415 check_added_monitors!(nodes[1], 1);
6416 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6420 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6421 //BOLT 2 Requirement: until the corresponding HTLC is irrevocably committed in both sides' commitment transactions: MUST NOT send an update_fulfill_htlc, update_fail_htlc, or update_fail_malformed_htlc.
6423 let chanmon_cfgs = create_chanmon_cfgs(2);
6424 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6425 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6426 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6427 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6428 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6429 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6430 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6432 check_added_monitors!(nodes[0], 1);
6433 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6434 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6436 let update_msg = msgs::UpdateFulfillHTLC{
6439 payment_preimage: our_payment_preimage,
6442 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6444 assert!(nodes[0].node.list_channels().is_empty());
6445 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6446 assert!(regex::Regex::new(r"Remote tried to fulfill/fail HTLC \(\d+\) before it had been committed").unwrap().is_match(err_msg.data.as_str()));
6447 check_added_monitors!(nodes[0], 1);
6448 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6452 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6453 //BOLT 2 Requirement: until the corresponding HTLC is irrevocably committed in both sides' commitment transactions: MUST NOT send an update_fulfill_htlc, update_fail_htlc, or update_fail_malformed_htlc.
6455 let chanmon_cfgs = create_chanmon_cfgs(2);
6456 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6457 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6458 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6459 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6461 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6462 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6463 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6464 check_added_monitors!(nodes[0], 1);
6465 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6466 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6468 let update_msg = msgs::UpdateFailHTLC{
6471 reason: msgs::OnionErrorPacket { data: Vec::new()},
6474 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6476 assert!(nodes[0].node.list_channels().is_empty());
6477 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6478 assert!(regex::Regex::new(r"Remote tried to fulfill/fail HTLC \(\d+\) before it had been committed").unwrap().is_match(err_msg.data.as_str()));
6479 check_added_monitors!(nodes[0], 1);
6480 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6484 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6485 //BOLT 2 Requirement: until the corresponding HTLC is irrevocably committed in both sides' commitment transactions: MUST NOT send an update_fulfill_htlc, update_fail_htlc, or update_fail_malformed_htlc.
6487 let chanmon_cfgs = create_chanmon_cfgs(2);
6488 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6489 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6490 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6491 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6493 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6494 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6495 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6496 check_added_monitors!(nodes[0], 1);
6497 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6498 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6499 let update_msg = msgs::UpdateFailMalformedHTLC{
6502 sha256_of_onion: [1; 32],
6503 failure_code: 0x8000,
6506 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6508 assert!(nodes[0].node.list_channels().is_empty());
6509 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6510 assert!(regex::Regex::new(r"Remote tried to fulfill/fail HTLC \(\d+\) before it had been committed").unwrap().is_match(err_msg.data.as_str()));
6511 check_added_monitors!(nodes[0], 1);
6512 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6516 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6517 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6519 let chanmon_cfgs = create_chanmon_cfgs(2);
6520 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6521 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6522 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6523 create_announced_chan_between_nodes(&nodes, 0, 1);
6525 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6527 nodes[1].node.claim_funds(our_payment_preimage);
6528 check_added_monitors!(nodes[1], 1);
6529 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6531 let events = nodes[1].node.get_and_clear_pending_msg_events();
6532 assert_eq!(events.len(), 1);
6533 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6535 MessageSendEvent::UpdateHTLCs { 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, .. } } => {
6536 assert!(update_add_htlcs.is_empty());
6537 assert_eq!(update_fulfill_htlcs.len(), 1);
6538 assert!(update_fail_htlcs.is_empty());
6539 assert!(update_fail_malformed_htlcs.is_empty());
6540 assert!(update_fee.is_none());
6541 update_fulfill_htlcs[0].clone()
6543 _ => panic!("Unexpected event"),
6547 update_fulfill_msg.htlc_id = 1;
6549 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6551 assert!(nodes[0].node.list_channels().is_empty());
6552 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6553 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6554 check_added_monitors!(nodes[0], 1);
6555 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6559 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6560 //BOLT 2 Requirement: A receiving node: if the payment_preimage value in update_fulfill_htlc doesn't SHA256 hash to the corresponding HTLC payment_hash MUST fail the channel.
6562 let chanmon_cfgs = create_chanmon_cfgs(2);
6563 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6564 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6565 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6566 create_announced_chan_between_nodes(&nodes, 0, 1);
6568 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6570 nodes[1].node.claim_funds(our_payment_preimage);
6571 check_added_monitors!(nodes[1], 1);
6572 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6574 let events = nodes[1].node.get_and_clear_pending_msg_events();
6575 assert_eq!(events.len(), 1);
6576 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6578 MessageSendEvent::UpdateHTLCs { 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, .. } } => {
6579 assert!(update_add_htlcs.is_empty());
6580 assert_eq!(update_fulfill_htlcs.len(), 1);
6581 assert!(update_fail_htlcs.is_empty());
6582 assert!(update_fail_malformed_htlcs.is_empty());
6583 assert!(update_fee.is_none());
6584 update_fulfill_htlcs[0].clone()
6586 _ => panic!("Unexpected event"),
6590 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6592 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6594 assert!(nodes[0].node.list_channels().is_empty());
6595 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6596 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6597 check_added_monitors!(nodes[0], 1);
6598 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6602 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6603 //BOLT 2 Requirement: A receiving node: if the BADONION bit in failure_code is not set for update_fail_malformed_htlc MUST fail the channel.
6605 let chanmon_cfgs = create_chanmon_cfgs(2);
6606 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6607 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6608 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6609 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6611 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6612 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6613 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6614 check_added_monitors!(nodes[0], 1);
6616 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6617 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6619 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6620 check_added_monitors!(nodes[1], 0);
6621 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6623 let events = nodes[1].node.get_and_clear_pending_msg_events();
6625 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6627 MessageSendEvent::UpdateHTLCs { 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, .. } } => {
6628 assert!(update_add_htlcs.is_empty());
6629 assert!(update_fulfill_htlcs.is_empty());
6630 assert!(update_fail_htlcs.is_empty());
6631 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6632 assert!(update_fee.is_none());
6633 update_fail_malformed_htlcs[0].clone()
6635 _ => panic!("Unexpected event"),
6638 update_msg.failure_code &= !0x8000;
6639 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6641 assert!(nodes[0].node.list_channels().is_empty());
6642 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6643 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6644 check_added_monitors!(nodes[0], 1);
6645 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 1000000);
6649 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6650 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6651 // * MUST return an error in the update_fail_htlc sent to the link which originally sent the HTLC, using the failure_code given and setting the data to sha256_of_onion.
6653 let chanmon_cfgs = create_chanmon_cfgs(3);
6654 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6655 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6656 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6657 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6658 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000);
6660 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6663 let mut payment_event = {
6664 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6665 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6666 check_added_monitors!(nodes[0], 1);
6667 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6668 assert_eq!(events.len(), 1);
6669 SendEvent::from_event(events.remove(0))
6671 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6672 check_added_monitors!(nodes[1], 0);
6673 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6674 expect_pending_htlcs_forwardable!(nodes[1]);
6675 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6676 assert_eq!(events_2.len(), 1);
6677 check_added_monitors!(nodes[1], 1);
6678 payment_event = SendEvent::from_event(events_2.remove(0));
6679 assert_eq!(payment_event.msgs.len(), 1);
6682 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6683 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6684 check_added_monitors!(nodes[2], 0);
6685 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6687 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6688 assert_eq!(events_3.len(), 1);
6689 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6691 MessageSendEvent::UpdateHTLCs { 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 } } => {
6692 assert!(update_add_htlcs.is_empty());
6693 assert!(update_fulfill_htlcs.is_empty());
6694 assert!(update_fail_htlcs.is_empty());
6695 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6696 assert!(update_fee.is_none());
6697 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6699 _ => panic!("Unexpected event"),
6703 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6705 check_added_monitors!(nodes[1], 0);
6706 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6707 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6708 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6709 assert_eq!(events_4.len(), 1);
6711 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6713 MessageSendEvent::UpdateHTLCs { 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, .. } } => {
6714 assert!(update_add_htlcs.is_empty());
6715 assert!(update_fulfill_htlcs.is_empty());
6716 assert_eq!(update_fail_htlcs.len(), 1);
6717 assert!(update_fail_malformed_htlcs.is_empty());
6718 assert!(update_fee.is_none());
6720 _ => panic!("Unexpected event"),
6723 check_added_monitors!(nodes[1], 1);
6727 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6728 let chanmon_cfgs = create_chanmon_cfgs(3);
6729 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6730 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6731 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6732 create_announced_chan_between_nodes(&nodes, 0, 1);
6733 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6735 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6738 let mut payment_event = {
6739 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6740 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6741 check_added_monitors!(nodes[0], 1);
6742 SendEvent::from_node(&nodes[0])
6745 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6746 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6747 expect_pending_htlcs_forwardable!(nodes[1]);
6748 check_added_monitors!(nodes[1], 1);
6749 payment_event = SendEvent::from_node(&nodes[1]);
6750 assert_eq!(payment_event.msgs.len(), 1);
6753 payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6754 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6755 check_added_monitors!(nodes[2], 0);
6756 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6758 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6759 assert_eq!(events_3.len(), 1);
6761 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6762 let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6763 // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6764 update_msg.failure_code |= 0x2000;
6766 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6767 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6769 _ => panic!("Unexpected event"),
6772 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6773 vec![HTLCDestination::NextHopChannel {
6774 node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6775 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6776 assert_eq!(events_4.len(), 1);
6777 check_added_monitors!(nodes[1], 1);
6780 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6781 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6782 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6784 _ => panic!("Unexpected event"),
6787 let events_5 = nodes[0].node.get_and_clear_pending_events();
6788 assert_eq!(events_5.len(), 2);
6790 // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6791 // the node originating the error to its next hop.
6793 Event::PaymentPathFailed { error_code, failure: PathFailure::OnPath { network_update: Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }) }, ..
6795 assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6796 assert!(is_permanent);
6797 assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
6799 _ => panic!("Unexpected event"),
6802 Event::PaymentFailed { payment_hash, .. } => {
6803 assert_eq!(payment_hash, our_payment_hash);
6805 _ => panic!("Unexpected event"),
6808 // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
6811 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6812 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6813 // We can have at most two valid local commitment tx, so both cases must be covered, and both txs must be checked to get them all as
6814 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6816 let mut chanmon_cfgs = create_chanmon_cfgs(2);
6817 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6818 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6819 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6820 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6821 let chan =create_announced_chan_between_nodes(&nodes, 0, 1);
6823 let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6824 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context.holder_dust_limit_satoshis;
6826 // We route 2 dust-HTLCs between A and B
6827 let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6828 let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6829 route_payment(&nodes[0], &[&nodes[1]], 1000000);
6831 // Cache one local commitment tx as previous
6832 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6834 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6835 nodes[1].node.fail_htlc_backwards(&payment_hash_2);
6836 check_added_monitors!(nodes[1], 0);
6837 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
6838 check_added_monitors!(nodes[1], 1);
6840 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6841 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6842 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6843 check_added_monitors!(nodes[0], 1);
6845 // Cache one local commitment tx as lastest
6846 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6848 let events = nodes[0].node.get_and_clear_pending_msg_events();
6850 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6851 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6853 _ => panic!("Unexpected event"),
6856 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6857 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6859 _ => panic!("Unexpected event"),
6862 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6863 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6864 if announce_latest {
6865 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6867 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6870 check_closed_broadcast!(nodes[0], true);
6871 check_added_monitors!(nodes[0], 1);
6872 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
6874 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6875 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6876 let events = nodes[0].node.get_and_clear_pending_events();
6877 // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
6878 assert_eq!(events.len(), 4);
6879 let mut first_failed = false;
6880 for event in events {
6882 Event::PaymentPathFailed { payment_hash, .. } => {
6883 if payment_hash == payment_hash_1 {
6884 assert!(!first_failed);
6885 first_failed = true;
6887 assert_eq!(payment_hash, payment_hash_2);
6890 Event::PaymentFailed { .. } => {}
6891 _ => panic!("Unexpected event"),
6897 fn test_failure_delay_dust_htlc_local_commitment() {
6898 do_test_failure_delay_dust_htlc_local_commitment(true);
6899 do_test_failure_delay_dust_htlc_local_commitment(false);
6902 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6903 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6904 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6905 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6906 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6907 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6908 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6910 let chanmon_cfgs = create_chanmon_cfgs(3);
6911 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6912 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6913 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6914 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6916 let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6917 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context.holder_dust_limit_satoshis;
6919 let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6920 let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6922 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6923 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6925 // We revoked bs_commitment_tx
6927 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6928 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
6931 let mut timeout_tx = Vec::new();
6933 // We fail dust-HTLC 1 by broadcast of local commitment tx
6934 mine_transaction(&nodes[0], &as_commitment_tx[0]);
6935 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
6936 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6937 expect_payment_failed!(nodes[0], dust_hash, false);
6939 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
6940 check_closed_broadcast!(nodes[0], true);
6941 check_added_monitors!(nodes[0], 1);
6942 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6943 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6944 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6945 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
6946 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6947 mine_transaction(&nodes[0], &timeout_tx[0]);
6948 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6949 expect_payment_failed!(nodes[0], non_dust_hash, false);
6951 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
6952 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
6953 check_closed_broadcast!(nodes[0], true);
6954 check_added_monitors!(nodes[0], 1);
6955 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
6956 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6958 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
6959 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
6960 .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
6961 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
6962 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
6963 // dust HTLC should have been failed.
6964 expect_payment_failed!(nodes[0], dust_hash, false);
6967 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6969 assert_eq!(timeout_tx[0].lock_time.0, 11);
6971 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
6972 mine_transaction(&nodes[0], &timeout_tx[0]);
6973 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6974 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6975 expect_payment_failed!(nodes[0], non_dust_hash, false);
6980 fn test_sweep_outbound_htlc_failure_update() {
6981 do_test_sweep_outbound_htlc_failure_update(false, true);
6982 do_test_sweep_outbound_htlc_failure_update(false, false);
6983 do_test_sweep_outbound_htlc_failure_update(true, false);
6987 fn test_user_configurable_csv_delay() {
6988 // We test our channel constructors yield errors when we pass them absurd csv delay
6990 let mut low_our_to_self_config = UserConfig::default();
6991 low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
6992 let mut high_their_to_self_config = UserConfig::default();
6993 high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
6994 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
6995 let chanmon_cfgs = create_chanmon_cfgs(2);
6996 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6997 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
6998 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7000 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in OutboundV1Channel::new()
7001 if let Err(error) = OutboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7002 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[1].node.init_features(), 1000000, 1000000, 0,
7003 &low_our_to_self_config, 0, 42)
7006 APIError::APIMisuseError { err } => { assert!(regex::Regex::new(r"Configured with an unreasonable our_to_self_delay \(\d+\) putting user funds at risks").unwrap().is_match(err.as_str())); },
7007 _ => panic!("Unexpected event"),
7009 } else { assert!(false) }
7011 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in InboundV1Channel::new()
7012 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7013 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7014 open_channel.to_self_delay = 200;
7015 if let Err(error) = InboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7016 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[0].node.channel_type_features(), &nodes[1].node.init_features(), &open_channel, 0,
7017 &low_our_to_self_config, 0, &nodes[0].logger, /*is_0conf=*/false)
7020 ChannelError::Close(err) => { assert!(regex::Regex::new(r"Configured with an unreasonable our_to_self_delay \(\d+\) putting user funds at risks").unwrap().is_match(err.as_str())); },
7021 _ => panic!("Unexpected event"),
7023 } else { assert!(false); }
7025 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7026 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7027 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id()));
7028 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7029 accept_channel.to_self_delay = 200;
7030 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
7032 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7034 &ErrorAction::SendErrorMessage { ref msg } => {
7035 assert!(regex::Regex::new(r"They wanted our payments to be delayed by a needlessly long period\. Upper limit: \d+\. Actual: \d+").unwrap().is_match(msg.data.as_str()));
7036 reason_msg = msg.data.clone();
7040 } else { panic!(); }
7041 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg }, [nodes[1].node.get_our_node_id()], 1000000);
7043 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in InboundV1Channel::new()
7044 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7045 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7046 open_channel.to_self_delay = 200;
7047 if let Err(error) = InboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7048 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[0].node.channel_type_features(), &nodes[1].node.init_features(), &open_channel, 0,
7049 &high_their_to_self_config, 0, &nodes[0].logger, /*is_0conf=*/false)
7052 ChannelError::Close(err) => { assert!(regex::Regex::new(r"They wanted our payments to be delayed by a needlessly long period\. Upper limit: \d+\. Actual: \d+").unwrap().is_match(err.as_str())); },
7053 _ => panic!("Unexpected event"),
7055 } else { assert!(false); }
7059 fn test_check_htlc_underpaying() {
7060 // Send payment through A -> B but A is maliciously
7061 // sending a probe payment (i.e less than expected value0
7062 // to B, B should refuse payment.
7064 let chanmon_cfgs = create_chanmon_cfgs(2);
7065 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7066 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7067 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7069 // Create some initial channels
7070 create_announced_chan_between_nodes(&nodes, 0, 1);
7072 let scorer = test_utils::TestScorer::new();
7073 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7074 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV).with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
7075 let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None, 10_000, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7076 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7077 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, None).unwrap();
7078 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
7079 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
7080 check_added_monitors!(nodes[0], 1);
7082 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7083 assert_eq!(events.len(), 1);
7084 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7085 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7086 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7088 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7089 // and then will wait a second random delay before failing the HTLC back:
7090 expect_pending_htlcs_forwardable!(nodes[1]);
7091 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7093 // Node 3 is expecting payment of 100_000 but received 10_000,
7094 // it should fail htlc like we didn't know the preimage.
7095 nodes[1].node.process_pending_htlc_forwards();
7097 let events = nodes[1].node.get_and_clear_pending_msg_events();
7098 assert_eq!(events.len(), 1);
7099 let (update_fail_htlc, commitment_signed) = match events[0] {
7100 MessageSendEvent::UpdateHTLCs { 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 } } => {
7101 assert!(update_add_htlcs.is_empty());
7102 assert!(update_fulfill_htlcs.is_empty());
7103 assert_eq!(update_fail_htlcs.len(), 1);
7104 assert!(update_fail_malformed_htlcs.is_empty());
7105 assert!(update_fee.is_none());
7106 (update_fail_htlcs[0].clone(), commitment_signed)
7108 _ => panic!("Unexpected event"),
7110 check_added_monitors!(nodes[1], 1);
7112 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7113 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7115 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7116 let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
7117 expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
7118 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7122 fn test_announce_disable_channels() {
7123 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7124 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7126 let chanmon_cfgs = create_chanmon_cfgs(2);
7127 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7128 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7129 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7131 create_announced_chan_between_nodes(&nodes, 0, 1);
7132 create_announced_chan_between_nodes(&nodes, 1, 0);
7133 create_announced_chan_between_nodes(&nodes, 0, 1);
7136 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
7137 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
7139 for _ in 0..DISABLE_GOSSIP_TICKS + 1 {
7140 nodes[0].node.timer_tick_occurred();
7142 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7143 assert_eq!(msg_events.len(), 3);
7144 let mut chans_disabled = HashMap::new();
7145 for e in msg_events {
7147 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7148 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7149 // Check that each channel gets updated exactly once
7150 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7151 panic!("Generated ChannelUpdate for wrong chan!");
7154 _ => panic!("Unexpected event"),
7158 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
7159 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
7161 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7162 assert_eq!(reestablish_1.len(), 3);
7163 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
7164 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
7166 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7167 assert_eq!(reestablish_2.len(), 3);
7169 // Reestablish chan_1
7170 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7171 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7172 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7173 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7174 // Reestablish chan_2
7175 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7176 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7177 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7178 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7179 // Reestablish chan_3
7180 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7181 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7182 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7183 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7185 for _ in 0..ENABLE_GOSSIP_TICKS {
7186 nodes[0].node.timer_tick_occurred();
7188 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7189 nodes[0].node.timer_tick_occurred();
7190 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7191 assert_eq!(msg_events.len(), 3);
7192 for e in msg_events {
7194 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7195 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7196 match chans_disabled.remove(&msg.contents.short_channel_id) {
7197 // Each update should have a higher timestamp than the previous one, replacing
7199 Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7200 None => panic!("Generated ChannelUpdate for wrong chan!"),
7203 _ => panic!("Unexpected event"),
7206 // Check that each channel gets updated exactly once
7207 assert!(chans_disabled.is_empty());
7211 fn test_bump_penalty_txn_on_revoked_commitment() {
7212 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7213 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7215 let chanmon_cfgs = create_chanmon_cfgs(2);
7216 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7217 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7218 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7220 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7222 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7223 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7224 .with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7225 let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000);
7226 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7228 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7229 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7230 assert_eq!(revoked_txn[0].output.len(), 4);
7231 assert_eq!(revoked_txn[0].input.len(), 1);
7232 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7233 let revoked_txid = revoked_txn[0].txid();
7235 let mut penalty_sum = 0;
7236 for outp in revoked_txn[0].output.iter() {
7237 if outp.script_pubkey.is_v0_p2wsh() {
7238 penalty_sum += outp.value;
7242 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7243 let header_114 = connect_blocks(&nodes[1], 14);
7245 // Actually revoke tx by claiming a HTLC
7246 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7247 connect_block(&nodes[1], &create_dummy_block(header_114, 42, vec![revoked_txn[0].clone()]));
7248 check_added_monitors!(nodes[1], 1);
7250 // One or more justice tx should have been broadcast, check it
7254 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7255 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7256 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7257 assert_eq!(node_txn[0].output.len(), 1);
7258 check_spends!(node_txn[0], revoked_txn[0]);
7259 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7260 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7261 penalty_1 = node_txn[0].txid();
7265 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7266 connect_blocks(&nodes[1], 15);
7267 let mut penalty_2 = penalty_1;
7268 let mut feerate_2 = 0;
7270 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7271 assert_eq!(node_txn.len(), 1);
7272 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7273 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7274 assert_eq!(node_txn[0].output.len(), 1);
7275 check_spends!(node_txn[0], revoked_txn[0]);
7276 penalty_2 = node_txn[0].txid();
7277 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7278 assert_ne!(penalty_2, penalty_1);
7279 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7280 feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7281 // Verify 25% bump heuristic
7282 assert!(feerate_2 * 100 >= feerate_1 * 125);
7286 assert_ne!(feerate_2, 0);
7288 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7289 connect_blocks(&nodes[1], 1);
7291 let mut feerate_3 = 0;
7293 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7294 assert_eq!(node_txn.len(), 1);
7295 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7296 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7297 assert_eq!(node_txn[0].output.len(), 1);
7298 check_spends!(node_txn[0], revoked_txn[0]);
7299 penalty_3 = node_txn[0].txid();
7300 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7301 assert_ne!(penalty_3, penalty_2);
7302 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7303 feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7304 // Verify 25% bump heuristic
7305 assert!(feerate_3 * 100 >= feerate_2 * 125);
7309 assert_ne!(feerate_3, 0);
7311 nodes[1].node.get_and_clear_pending_events();
7312 nodes[1].node.get_and_clear_pending_msg_events();
7316 fn test_bump_penalty_txn_on_revoked_htlcs() {
7317 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7318 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7320 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7321 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7322 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7323 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7324 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7326 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7327 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7328 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 50).with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
7329 let scorer = test_utils::TestScorer::new();
7330 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7331 let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7332 3_000_000, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7333 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7334 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50).with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7335 let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7336 3_000_000, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7337 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7339 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7340 assert_eq!(revoked_local_txn[0].input.len(), 1);
7341 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7343 // Revoke local commitment tx
7344 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7346 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7347 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone()]));
7348 check_closed_broadcast!(nodes[1], true);
7349 check_added_monitors!(nodes[1], 1);
7350 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 1000000);
7351 connect_blocks(&nodes[1], 50); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7353 let revoked_htlc_txn = {
7354 let txn = nodes[1].tx_broadcaster.unique_txn_broadcast();
7355 assert_eq!(txn.len(), 2);
7357 assert_eq!(txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7358 assert_eq!(txn[0].input.len(), 1);
7359 check_spends!(txn[0], revoked_local_txn[0]);
7361 assert_eq!(txn[1].input.len(), 1);
7362 assert_eq!(txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7363 assert_eq!(txn[1].output.len(), 1);
7364 check_spends!(txn[1], revoked_local_txn[0]);
7369 // Broadcast set of revoked txn on A
7370 let hash_128 = connect_blocks(&nodes[0], 40);
7371 let block_11 = create_dummy_block(hash_128, 42, vec![revoked_local_txn[0].clone()]);
7372 connect_block(&nodes[0], &block_11);
7373 let block_129 = create_dummy_block(block_11.block_hash(), 42, vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()]);
7374 connect_block(&nodes[0], &block_129);
7375 let events = nodes[0].node.get_and_clear_pending_events();
7376 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7377 match events.last().unwrap() {
7378 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7379 _ => panic!("Unexpected event"),
7385 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7386 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7387 // Verify claim tx are spending revoked HTLC txn
7389 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7390 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7391 // which are included in the same block (they are broadcasted because we scan the
7392 // transactions linearly and generate claims as we go, they likely should be removed in the
7394 assert_eq!(node_txn[0].input.len(), 1);
7395 check_spends!(node_txn[0], revoked_local_txn[0]);
7396 assert_eq!(node_txn[1].input.len(), 1);
7397 check_spends!(node_txn[1], revoked_local_txn[0]);
7398 assert_eq!(node_txn[2].input.len(), 1);
7399 check_spends!(node_txn[2], revoked_local_txn[0]);
7401 // Each of the three justice transactions claim a separate (single) output of the three
7402 // available, which we check here:
7403 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7404 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7405 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7407 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7408 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7410 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7411 // output, checked above).
7412 assert_eq!(node_txn[3].input.len(), 2);
7413 assert_eq!(node_txn[3].output.len(), 1);
7414 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7416 first = node_txn[3].txid();
7417 // Store both feerates for later comparison
7418 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7419 feerate_1 = fee_1 * 1000 / node_txn[3].weight() as u64;
7420 penalty_txn = vec![node_txn[2].clone()];
7424 // Connect one more block to see if bumped penalty are issued for HTLC txn
7425 let block_130 = create_dummy_block(block_129.block_hash(), 42, penalty_txn);
7426 connect_block(&nodes[0], &block_130);
7427 let block_131 = create_dummy_block(block_130.block_hash(), 42, Vec::new());
7428 connect_block(&nodes[0], &block_131);
7430 // Few more blocks to confirm penalty txn
7431 connect_blocks(&nodes[0], 4);
7432 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7433 let header_144 = connect_blocks(&nodes[0], 9);
7435 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7436 assert_eq!(node_txn.len(), 1);
7438 assert_eq!(node_txn[0].input.len(), 2);
7439 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7440 // Verify bumped tx is different and 25% bump heuristic
7441 assert_ne!(first, node_txn[0].txid());
7442 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7443 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7444 assert!(feerate_2 * 100 > feerate_1 * 125);
7445 let txn = vec![node_txn[0].clone()];
7449 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7450 connect_block(&nodes[0], &create_dummy_block(header_144, 42, node_txn));
7451 connect_blocks(&nodes[0], 20);
7453 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7454 // We verify than no new transaction has been broadcast because previously
7455 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7456 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7457 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7458 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7459 // up bumped justice generation.
7460 assert_eq!(node_txn.len(), 0);
7463 check_closed_broadcast!(nodes[0], true);
7464 check_added_monitors!(nodes[0], 1);
7468 fn test_bump_penalty_txn_on_remote_commitment() {
7469 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7470 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7473 // Provide preimage for one
7474 // Check aggregation
7476 let chanmon_cfgs = create_chanmon_cfgs(2);
7477 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7478 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7479 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7481 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7482 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7483 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7485 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7486 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7487 assert_eq!(remote_txn[0].output.len(), 4);
7488 assert_eq!(remote_txn[0].input.len(), 1);
7489 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7491 // Claim a HTLC without revocation (provide B monitor with preimage)
7492 nodes[1].node.claim_funds(payment_preimage);
7493 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7494 mine_transaction(&nodes[1], &remote_txn[0]);
7495 check_added_monitors!(nodes[1], 2);
7496 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7498 // One or more claim tx should have been broadcast, check it
7502 let feerate_timeout;
7503 let feerate_preimage;
7505 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7506 // 3 transactions including:
7507 // preimage and timeout sweeps from remote commitment + preimage sweep bump
7508 assert_eq!(node_txn.len(), 3);
7509 assert_eq!(node_txn[0].input.len(), 1);
7510 assert_eq!(node_txn[1].input.len(), 1);
7511 assert_eq!(node_txn[2].input.len(), 1);
7512 check_spends!(node_txn[0], remote_txn[0]);
7513 check_spends!(node_txn[1], remote_txn[0]);
7514 check_spends!(node_txn[2], remote_txn[0]);
7516 preimage = node_txn[0].txid();
7517 let index = node_txn[0].input[0].previous_output.vout;
7518 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7519 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
7521 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7522 (node_txn[2].clone(), node_txn[1].clone())
7524 (node_txn[1].clone(), node_txn[2].clone())
7527 preimage_bump = preimage_bump_tx;
7528 check_spends!(preimage_bump, remote_txn[0]);
7529 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7531 timeout = timeout_tx.txid();
7532 let index = timeout_tx.input[0].previous_output.vout;
7533 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7534 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
7538 assert_ne!(feerate_timeout, 0);
7539 assert_ne!(feerate_preimage, 0);
7541 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7542 connect_blocks(&nodes[1], 1);
7544 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7545 assert_eq!(node_txn.len(), 1);
7546 assert_eq!(node_txn[0].input.len(), 1);
7547 assert_eq!(preimage_bump.input.len(), 1);
7548 check_spends!(node_txn[0], remote_txn[0]);
7549 check_spends!(preimage_bump, remote_txn[0]);
7551 let index = preimage_bump.input[0].previous_output.vout;
7552 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7553 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
7554 assert!(new_feerate * 100 > feerate_timeout * 125);
7555 assert_ne!(timeout, preimage_bump.txid());
7557 let index = node_txn[0].input[0].previous_output.vout;
7558 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7559 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
7560 assert!(new_feerate * 100 > feerate_preimage * 125);
7561 assert_ne!(preimage, node_txn[0].txid());
7566 nodes[1].node.get_and_clear_pending_events();
7567 nodes[1].node.get_and_clear_pending_msg_events();
7571 fn test_counterparty_raa_skip_no_crash() {
7572 // Previously, if our counterparty sent two RAAs in a row without us having provided a
7573 // commitment transaction, we would have happily carried on and provided them the next
7574 // commitment transaction based on one RAA forward. This would probably eventually have led to
7575 // channel closure, but it would not have resulted in funds loss. Still, our
7576 // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7577 // check simply that the channel is closed in response to such an RAA, but don't check whether
7578 // we decide to punish our counterparty for revoking their funds (as we don't currently
7580 let chanmon_cfgs = create_chanmon_cfgs(2);
7581 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7582 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7583 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7584 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7586 let per_commitment_secret;
7587 let next_per_commitment_point;
7589 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7590 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7591 let keys = guard.channel_by_id.get_mut(&channel_id).unwrap().get_signer();
7593 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7595 // Make signer believe we got a counterparty signature, so that it allows the revocation
7596 keys.get_enforcement_state().last_holder_commitment -= 1;
7597 per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7599 // Must revoke without gaps
7600 keys.get_enforcement_state().last_holder_commitment -= 1;
7601 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7603 keys.get_enforcement_state().last_holder_commitment -= 1;
7604 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7605 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7608 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7609 &msgs::RevokeAndACK {
7611 per_commitment_secret,
7612 next_per_commitment_point,
7614 next_local_nonce: None,
7616 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7617 check_added_monitors!(nodes[1], 1);
7618 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() }
7619 , [nodes[0].node.get_our_node_id()], 100000);
7623 fn test_bump_txn_sanitize_tracking_maps() {
7624 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7625 // verify we clean then right after expiration of ANTI_REORG_DELAY.
7627 let chanmon_cfgs = create_chanmon_cfgs(2);
7628 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7629 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7630 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7632 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7633 // Lock HTLC in both directions
7634 let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7635 let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7637 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7638 assert_eq!(revoked_local_txn[0].input.len(), 1);
7639 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7641 // Revoke local commitment tx
7642 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7644 // Broadcast set of revoked txn on A
7645 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7646 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7647 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7649 mine_transaction(&nodes[0], &revoked_local_txn[0]);
7650 check_closed_broadcast!(nodes[0], true);
7651 check_added_monitors!(nodes[0], 1);
7652 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 1000000);
7654 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7655 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7656 check_spends!(node_txn[0], revoked_local_txn[0]);
7657 check_spends!(node_txn[1], revoked_local_txn[0]);
7658 check_spends!(node_txn[2], revoked_local_txn[0]);
7659 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7663 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, penalty_txn));
7664 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7666 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7667 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7668 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7673 fn test_channel_conf_timeout() {
7674 // Tests that, for inbound channels, we give up on them if the funding transaction does not
7675 // confirm within 2016 blocks, as recommended by BOLT 2.
7676 let chanmon_cfgs = create_chanmon_cfgs(2);
7677 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7678 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7679 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7681 let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7683 // The outbound node should wait forever for confirmation:
7684 // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7685 // copied here instead of directly referencing the constant.
7686 connect_blocks(&nodes[0], 2016);
7687 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7689 // The inbound node should fail the channel after exactly 2016 blocks
7690 connect_blocks(&nodes[1], 2015);
7691 check_added_monitors!(nodes[1], 0);
7692 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7694 connect_blocks(&nodes[1], 1);
7695 check_added_monitors!(nodes[1], 1);
7696 check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut, [nodes[0].node.get_our_node_id()], 1000000);
7697 let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7698 assert_eq!(close_ev.len(), 1);
7700 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
7701 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7702 assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7704 _ => panic!("Unexpected event"),
7709 fn test_override_channel_config() {
7710 let chanmon_cfgs = create_chanmon_cfgs(2);
7711 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7712 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7713 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7715 // Node0 initiates a channel to node1 using the override config.
7716 let mut override_config = UserConfig::default();
7717 override_config.channel_handshake_config.our_to_self_delay = 200;
7719 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7721 // Assert the channel created by node0 is using the override config.
7722 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7723 assert_eq!(res.channel_flags, 0);
7724 assert_eq!(res.to_self_delay, 200);
7728 fn test_override_0msat_htlc_minimum() {
7729 let mut zero_config = UserConfig::default();
7730 zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7731 let chanmon_cfgs = create_chanmon_cfgs(2);
7732 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7733 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7734 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7736 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7737 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7738 assert_eq!(res.htlc_minimum_msat, 1);
7740 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7741 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7742 assert_eq!(res.htlc_minimum_msat, 1);
7746 fn test_channel_update_has_correct_htlc_maximum_msat() {
7747 // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7748 // Bolt 7 specifies that if present `htlc_maximum_msat`:
7749 // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7750 // 90% of the `channel_value`.
7751 // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7753 let mut config_30_percent = UserConfig::default();
7754 config_30_percent.channel_handshake_config.announced_channel = true;
7755 config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7756 let mut config_50_percent = UserConfig::default();
7757 config_50_percent.channel_handshake_config.announced_channel = true;
7758 config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7759 let mut config_95_percent = UserConfig::default();
7760 config_95_percent.channel_handshake_config.announced_channel = true;
7761 config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7762 let mut config_100_percent = UserConfig::default();
7763 config_100_percent.channel_handshake_config.announced_channel = true;
7764 config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7766 let chanmon_cfgs = create_chanmon_cfgs(4);
7767 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7768 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[Some(config_30_percent), Some(config_50_percent), Some(config_95_percent), Some(config_100_percent)]);
7769 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7771 let channel_value_satoshis = 100000;
7772 let channel_value_msat = channel_value_satoshis * 1000;
7773 let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7774 let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7775 let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7777 let (node_0_chan_update, node_1_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
7778 let (node_2_chan_update, node_3_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
7780 // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7781 // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7782 assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7783 // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7784 // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7785 assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7787 // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7788 // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7790 assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7791 // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7792 // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7794 assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7798 fn test_manually_accept_inbound_channel_request() {
7799 let mut manually_accept_conf = UserConfig::default();
7800 manually_accept_conf.manually_accept_inbound_channels = true;
7801 let chanmon_cfgs = create_chanmon_cfgs(2);
7802 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7803 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7804 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7806 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7807 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7809 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7811 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7812 // accepting the inbound channel request.
7813 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7815 let events = nodes[1].node.get_and_clear_pending_events();
7817 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7818 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
7820 _ => panic!("Unexpected event"),
7823 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7824 assert_eq!(accept_msg_ev.len(), 1);
7826 match accept_msg_ev[0] {
7827 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7828 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7830 _ => panic!("Unexpected event"),
7833 nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7835 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7836 assert_eq!(close_msg_ev.len(), 1);
7838 let events = nodes[1].node.get_and_clear_pending_events();
7840 Event::ChannelClosed { user_channel_id, .. } => {
7841 assert_eq!(user_channel_id, 23);
7843 _ => panic!("Unexpected event"),
7848 fn test_manually_reject_inbound_channel_request() {
7849 let mut manually_accept_conf = UserConfig::default();
7850 manually_accept_conf.manually_accept_inbound_channels = true;
7851 let chanmon_cfgs = create_chanmon_cfgs(2);
7852 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7853 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7854 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7856 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7857 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7859 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7861 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7862 // rejecting the inbound channel request.
7863 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7865 let events = nodes[1].node.get_and_clear_pending_events();
7867 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7868 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7870 _ => panic!("Unexpected event"),
7873 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7874 assert_eq!(close_msg_ev.len(), 1);
7876 match close_msg_ev[0] {
7877 MessageSendEvent::HandleError { ref node_id, .. } => {
7878 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7880 _ => panic!("Unexpected event"),
7883 // There should be no more events to process, as the channel was never opened.
7884 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
7888 fn test_can_not_accept_inbound_channel_twice() {
7889 let mut manually_accept_conf = UserConfig::default();
7890 manually_accept_conf.manually_accept_inbound_channels = true;
7891 let chanmon_cfgs = create_chanmon_cfgs(2);
7892 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7893 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7894 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7896 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7897 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7899 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7901 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7902 // accepting the inbound channel request.
7903 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7905 let events = nodes[1].node.get_and_clear_pending_events();
7907 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7908 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
7909 let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
7911 Err(APIError::APIMisuseError { err }) => {
7912 assert_eq!(err, "No such channel awaiting to be accepted.");
7914 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
7915 Err(e) => panic!("Unexpected Error {:?}", e),
7918 _ => panic!("Unexpected event"),
7921 // Ensure that the channel wasn't closed after attempting to accept it twice.
7922 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7923 assert_eq!(accept_msg_ev.len(), 1);
7925 match accept_msg_ev[0] {
7926 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7927 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7929 _ => panic!("Unexpected event"),
7934 fn test_can_not_accept_unknown_inbound_channel() {
7935 let chanmon_cfg = create_chanmon_cfgs(2);
7936 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
7937 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
7938 let nodes = create_network(2, &node_cfg, &node_chanmgr);
7940 let unknown_channel_id = [0; 32];
7941 let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
7943 Err(APIError::APIMisuseError { err }) => {
7944 assert_eq!(err, "No such channel awaiting to be accepted.");
7946 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
7947 Err(e) => panic!("Unexpected Error: {:?}", e),
7952 fn test_onion_value_mpp_set_calculation() {
7953 // Test that we use the onion value `amt_to_forward` when
7954 // calculating whether we've reached the `total_msat` of an MPP
7955 // by having a routing node forward more than `amt_to_forward`
7956 // and checking that the receiving node doesn't generate
7957 // a PaymentClaimable event too early
7959 let chanmon_cfgs = create_chanmon_cfgs(node_count);
7960 let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
7961 let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
7962 let mut nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
7964 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
7965 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
7966 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
7967 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
7969 let total_msat = 100_000;
7970 let expected_paths: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
7971 let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], total_msat);
7972 let sample_path = route.paths.pop().unwrap();
7974 let mut path_1 = sample_path.clone();
7975 path_1.hops[0].pubkey = nodes[1].node.get_our_node_id();
7976 path_1.hops[0].short_channel_id = chan_1_id;
7977 path_1.hops[1].pubkey = nodes[3].node.get_our_node_id();
7978 path_1.hops[1].short_channel_id = chan_3_id;
7979 path_1.hops[1].fee_msat = 100_000;
7980 route.paths.push(path_1);
7982 let mut path_2 = sample_path.clone();
7983 path_2.hops[0].pubkey = nodes[2].node.get_our_node_id();
7984 path_2.hops[0].short_channel_id = chan_2_id;
7985 path_2.hops[1].pubkey = nodes[3].node.get_our_node_id();
7986 path_2.hops[1].short_channel_id = chan_4_id;
7987 path_2.hops[1].fee_msat = 1_000;
7988 route.paths.push(path_2);
7991 let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
7992 let onion_session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
7993 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
7994 nodes[0].node.test_send_payment_internal(&route, our_payment_hash,
7995 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
7996 check_added_monitors!(nodes[0], expected_paths.len());
7998 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7999 assert_eq!(events.len(), expected_paths.len());
8002 let ev = remove_first_msg_event_to_node(&expected_paths[0][0].node.get_our_node_id(), &mut events);
8003 let mut payment_event = SendEvent::from_event(ev);
8004 let mut prev_node = &nodes[0];
8006 for (idx, &node) in expected_paths[0].iter().enumerate() {
8007 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
8009 if idx == 0 { // routing node
8010 let session_priv = [3; 32];
8011 let height = nodes[0].best_block_info().1;
8012 let session_priv = SecretKey::from_slice(&session_priv).unwrap();
8013 let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
8014 let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], 100_000,
8015 RecipientOnionFields::secret_only(our_payment_secret), height + 1, &None).unwrap();
8016 // Edit amt_to_forward to simulate the sender having set
8017 // the final amount and the routing node taking less fee
8018 if let msgs::OutboundOnionPayload::Receive { ref mut amt_msat, .. } = onion_payloads[1] {
8021 let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
8022 payment_event.msgs[0].onion_routing_packet = new_onion_packet;
8025 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
8026 check_added_monitors!(node, 0);
8027 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
8028 expect_pending_htlcs_forwardable!(node);
8031 let mut events_2 = node.node.get_and_clear_pending_msg_events();
8032 assert_eq!(events_2.len(), 1);
8033 check_added_monitors!(node, 1);
8034 payment_event = SendEvent::from_event(events_2.remove(0));
8035 assert_eq!(payment_event.msgs.len(), 1);
8037 let events_2 = node.node.get_and_clear_pending_events();
8038 assert!(events_2.is_empty());
8045 let ev = remove_first_msg_event_to_node(&expected_paths[1][0].node.get_our_node_id(), &mut events);
8046 pass_along_path(&nodes[0], expected_paths[1], 101_000, our_payment_hash.clone(), Some(our_payment_secret), ev, true, None);
8048 claim_payment_along_route(&nodes[0], expected_paths, false, our_payment_preimage);
8051 fn do_test_overshoot_mpp(msat_amounts: &[u64], total_msat: u64) {
8053 let routing_node_count = msat_amounts.len();
8054 let node_count = routing_node_count + 2;
8056 let chanmon_cfgs = create_chanmon_cfgs(node_count);
8057 let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8058 let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8059 let nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8064 // Create channels for each amount
8065 let mut expected_paths = Vec::with_capacity(routing_node_count);
8066 let mut src_chan_ids = Vec::with_capacity(routing_node_count);
8067 let mut dst_chan_ids = Vec::with_capacity(routing_node_count);
8068 for i in 0..routing_node_count {
8069 let routing_node = 2 + i;
8070 let src_chan_id = create_announced_chan_between_nodes(&nodes, src_idx, routing_node).0.contents.short_channel_id;
8071 src_chan_ids.push(src_chan_id);
8072 let dst_chan_id = create_announced_chan_between_nodes(&nodes, routing_node, dst_idx).0.contents.short_channel_id;
8073 dst_chan_ids.push(dst_chan_id);
8074 let path = vec![&nodes[routing_node], &nodes[dst_idx]];
8075 expected_paths.push(path);
8077 let expected_paths: Vec<&[&Node]> = expected_paths.iter().map(|route| route.as_slice()).collect();
8079 // Create a route for each amount
8080 let example_amount = 100000;
8081 let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[src_idx], nodes[dst_idx], example_amount);
8082 let sample_path = route.paths.pop().unwrap();
8083 for i in 0..routing_node_count {
8084 let routing_node = 2 + i;
8085 let mut path = sample_path.clone();
8086 path.hops[0].pubkey = nodes[routing_node].node.get_our_node_id();
8087 path.hops[0].short_channel_id = src_chan_ids[i];
8088 path.hops[1].pubkey = nodes[dst_idx].node.get_our_node_id();
8089 path.hops[1].short_channel_id = dst_chan_ids[i];
8090 path.hops[1].fee_msat = msat_amounts[i];
8091 route.paths.push(path);
8094 // Send payment with manually set total_msat
8095 let payment_id = PaymentId(nodes[src_idx].keys_manager.backing.get_secure_random_bytes());
8096 let onion_session_privs = nodes[src_idx].node.test_add_new_pending_payment(our_payment_hash,
8097 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8098 nodes[src_idx].node.test_send_payment_internal(&route, our_payment_hash,
8099 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8100 check_added_monitors!(nodes[src_idx], expected_paths.len());
8102 let mut events = nodes[src_idx].node.get_and_clear_pending_msg_events();
8103 assert_eq!(events.len(), expected_paths.len());
8104 let mut amount_received = 0;
8105 for (path_idx, expected_path) in expected_paths.iter().enumerate() {
8106 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
8108 let current_path_amount = msat_amounts[path_idx];
8109 amount_received += current_path_amount;
8110 let became_claimable_now = amount_received >= total_msat && amount_received - current_path_amount < total_msat;
8111 pass_along_path(&nodes[src_idx], expected_path, amount_received, our_payment_hash.clone(), Some(our_payment_secret), ev, became_claimable_now, None);
8114 claim_payment_along_route(&nodes[src_idx], &expected_paths, false, our_payment_preimage);
8118 fn test_overshoot_mpp() {
8119 do_test_overshoot_mpp(&[100_000, 101_000], 200_000);
8120 do_test_overshoot_mpp(&[100_000, 10_000, 100_000], 200_000);
8124 fn test_simple_mpp() {
8125 // Simple test of sending a multi-path payment.
8126 let chanmon_cfgs = create_chanmon_cfgs(4);
8127 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8128 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8129 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8131 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8132 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8133 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8134 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8136 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8137 let path = route.paths[0].clone();
8138 route.paths.push(path);
8139 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
8140 route.paths[0].hops[0].short_channel_id = chan_1_id;
8141 route.paths[0].hops[1].short_channel_id = chan_3_id;
8142 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
8143 route.paths[1].hops[0].short_channel_id = chan_2_id;
8144 route.paths[1].hops[1].short_channel_id = chan_4_id;
8145 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8146 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8150 fn test_preimage_storage() {
8151 // Simple test of payment preimage storage allowing no client-side storage to claim payments
8152 let chanmon_cfgs = create_chanmon_cfgs(2);
8153 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8154 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8155 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8157 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8160 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
8161 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8162 nodes[0].node.send_payment_with_route(&route, payment_hash,
8163 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8164 check_added_monitors!(nodes[0], 1);
8165 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8166 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8167 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8168 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8170 // Note that after leaving the above scope we have no knowledge of any arguments or return
8171 // values from previous calls.
8172 expect_pending_htlcs_forwardable!(nodes[1]);
8173 let events = nodes[1].node.get_and_clear_pending_events();
8174 assert_eq!(events.len(), 1);
8176 Event::PaymentClaimable { ref purpose, .. } => {
8178 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8179 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8181 _ => panic!("expected PaymentPurpose::InvoicePayment")
8184 _ => panic!("Unexpected event"),
8189 fn test_bad_secret_hash() {
8190 // Simple test of unregistered payment hash/invalid payment secret handling
8191 let chanmon_cfgs = create_chanmon_cfgs(2);
8192 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8193 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8194 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8196 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8198 let random_payment_hash = PaymentHash([42; 32]);
8199 let random_payment_secret = PaymentSecret([43; 32]);
8200 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8201 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8203 // All the below cases should end up being handled exactly identically, so we macro the
8204 // resulting events.
8205 macro_rules! handle_unknown_invalid_payment_data {
8206 ($payment_hash: expr) => {
8207 check_added_monitors!(nodes[0], 1);
8208 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8209 let payment_event = SendEvent::from_event(events.pop().unwrap());
8210 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8211 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8213 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8214 // again to process the pending backwards-failure of the HTLC
8215 expect_pending_htlcs_forwardable!(nodes[1]);
8216 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8217 check_added_monitors!(nodes[1], 1);
8219 // We should fail the payment back
8220 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8221 match events.pop().unwrap() {
8222 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8223 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8224 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8226 _ => panic!("Unexpected event"),
8231 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8232 // Error data is the HTLC value (100,000) and current block height
8233 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8235 // Send a payment with the right payment hash but the wrong payment secret
8236 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
8237 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8238 handle_unknown_invalid_payment_data!(our_payment_hash);
8239 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8241 // Send a payment with a random payment hash, but the right payment secret
8242 nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8243 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8244 handle_unknown_invalid_payment_data!(random_payment_hash);
8245 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8247 // Send a payment with a random payment hash and random payment secret
8248 nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8249 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8250 handle_unknown_invalid_payment_data!(random_payment_hash);
8251 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8255 fn test_update_err_monitor_lockdown() {
8256 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8257 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8258 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8261 // This scenario may happen in a watchtower setup, where watchtower process a block height
8262 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8263 // commitment at same time.
8265 let chanmon_cfgs = create_chanmon_cfgs(2);
8266 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8267 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8268 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8270 // Create some initial channel
8271 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8272 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8274 // Rebalance the network to generate htlc in the two directions
8275 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8277 // Route a HTLC from node 0 to node 1 (but don't settle)
8278 let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8280 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8281 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8282 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8283 let persister = test_utils::TestPersister::new();
8286 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8287 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8288 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8289 assert!(new_monitor == *monitor);
8292 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8293 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8296 let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8297 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8298 // transaction lock time requirements here.
8299 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 200));
8300 watchtower.chain_monitor.block_connected(&block, 200);
8302 // Try to update ChannelMonitor
8303 nodes[1].node.claim_funds(preimage);
8304 check_added_monitors!(nodes[1], 1);
8305 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8307 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8308 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8309 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8311 let mut node_0_per_peer_lock;
8312 let mut node_0_peer_state_lock;
8313 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8314 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8315 assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8316 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8317 } else { assert!(false); }
8319 // Our local monitor is in-sync and hasn't processed yet timeout
8320 check_added_monitors!(nodes[0], 1);
8321 let events = nodes[0].node.get_and_clear_pending_events();
8322 assert_eq!(events.len(), 1);
8326 fn test_concurrent_monitor_claim() {
8327 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8328 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8329 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8330 // state N+1 confirms. Alice claims output from state N+1.
8332 let chanmon_cfgs = create_chanmon_cfgs(2);
8333 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8334 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8335 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8337 // Create some initial channel
8338 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8339 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8341 // Rebalance the network to generate htlc in the two directions
8342 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8344 // Route a HTLC from node 0 to node 1 (but don't settle)
8345 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8347 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8348 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8349 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8350 let persister = test_utils::TestPersister::new();
8351 let alice_broadcaster = test_utils::TestBroadcaster::with_blocks(
8352 Arc::new(Mutex::new(nodes[0].blocks.lock().unwrap().clone())),
8354 let watchtower_alice = {
8356 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8357 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8358 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8359 assert!(new_monitor == *monitor);
8362 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &alice_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8363 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8366 let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8367 // Make Alice aware of enough blocks that it doesn't think we're violating transaction lock time
8368 // requirements here.
8369 const HTLC_TIMEOUT_BROADCAST: u32 = CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS;
8370 alice_broadcaster.blocks.lock().unwrap().resize((HTLC_TIMEOUT_BROADCAST) as usize, (block.clone(), HTLC_TIMEOUT_BROADCAST));
8371 watchtower_alice.chain_monitor.block_connected(&block, HTLC_TIMEOUT_BROADCAST);
8373 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8375 let mut txn = alice_broadcaster.txn_broadcast();
8376 assert_eq!(txn.len(), 2);
8380 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8381 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8382 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8383 let persister = test_utils::TestPersister::new();
8384 let bob_broadcaster = test_utils::TestBroadcaster::with_blocks(Arc::clone(&alice_broadcaster.blocks));
8385 let watchtower_bob = {
8387 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8388 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8389 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8390 assert!(new_monitor == *monitor);
8393 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &bob_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8394 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8397 watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST - 1);
8399 // Route another payment to generate another update with still previous HTLC pending
8400 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8401 nodes[1].node.send_payment_with_route(&route, payment_hash,
8402 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8403 check_added_monitors!(nodes[1], 1);
8405 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8406 assert_eq!(updates.update_add_htlcs.len(), 1);
8407 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8409 let mut node_0_per_peer_lock;
8410 let mut node_0_peer_state_lock;
8411 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8412 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8413 // Watchtower Alice should already have seen the block and reject the update
8414 assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8415 assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8416 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8417 } else { assert!(false); }
8419 // Our local monitor is in-sync and hasn't processed yet timeout
8420 check_added_monitors!(nodes[0], 1);
8422 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8423 watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST);
8425 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8428 let mut txn = bob_broadcaster.txn_broadcast();
8429 assert_eq!(txn.len(), 2);
8430 bob_state_y = txn.remove(0);
8433 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8434 let height = HTLC_TIMEOUT_BROADCAST + 1;
8435 connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
8436 check_closed_broadcast(&nodes[0], 1, true);
8437 check_closed_event!(&nodes[0], 1, ClosureReason::CommitmentTxConfirmed, false,
8438 [nodes[1].node.get_our_node_id()], 100000);
8439 watchtower_alice.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, vec![bob_state_y.clone()]), height);
8440 check_added_monitors(&nodes[0], 1);
8442 let htlc_txn = alice_broadcaster.txn_broadcast();
8443 assert_eq!(htlc_txn.len(), 2);
8444 check_spends!(htlc_txn[0], bob_state_y);
8445 // Alice doesn't clean up the old HTLC claim since it hasn't seen a conflicting spend for
8446 // it. However, she should, because it now has an invalid parent.
8447 check_spends!(htlc_txn[1], alice_state);
8452 fn test_pre_lockin_no_chan_closed_update() {
8453 // Test that if a peer closes a channel in response to a funding_created message we don't
8454 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8457 // Doing so would imply a channel monitor update before the initial channel monitor
8458 // registration, violating our API guarantees.
8460 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8461 // then opening a second channel with the same funding output as the first (which is not
8462 // rejected because the first channel does not exist in the ChannelManager) and closing it
8463 // before receiving funding_signed.
8464 let chanmon_cfgs = create_chanmon_cfgs(2);
8465 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8466 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8467 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8469 // Create an initial channel
8470 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8471 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8472 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8473 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8474 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8476 // Move the first channel through the funding flow...
8477 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8479 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8480 check_added_monitors!(nodes[0], 0);
8482 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8483 let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8484 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8485 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8486 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("Hi".to_string()) }, true,
8487 [nodes[1].node.get_our_node_id(); 2], 100000);
8491 fn test_htlc_no_detection() {
8492 // This test is a mutation to underscore the detection logic bug we had
8493 // before #653. HTLC value routed is above the remaining balance, thus
8494 // inverting HTLC and `to_remote` output. HTLC will come second and
8495 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8496 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8497 // outputs order detection for correct spending children filtring.
8499 let chanmon_cfgs = create_chanmon_cfgs(2);
8500 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8501 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8502 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8504 // Create some initial channels
8505 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8507 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8508 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8509 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8510 assert_eq!(local_txn[0].input.len(), 1);
8511 assert_eq!(local_txn[0].output.len(), 3);
8512 check_spends!(local_txn[0], chan_1.3);
8514 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8515 let block = create_dummy_block(nodes[0].best_block_hash(), 42, vec![local_txn[0].clone()]);
8516 connect_block(&nodes[0], &block);
8517 // We deliberately connect the local tx twice as this should provoke a failure calling
8518 // this test before #653 fix.
8519 chain::Listen::block_connected(&nodes[0].chain_monitor.chain_monitor, &block, nodes[0].best_block_info().1 + 1);
8520 check_closed_broadcast!(nodes[0], true);
8521 check_added_monitors!(nodes[0], 1);
8522 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
8523 connect_blocks(&nodes[0], TEST_FINAL_CLTV);
8525 let htlc_timeout = {
8526 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8527 assert_eq!(node_txn.len(), 1);
8528 assert_eq!(node_txn[0].input.len(), 1);
8529 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8530 check_spends!(node_txn[0], local_txn[0]);
8534 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![htlc_timeout.clone()]));
8535 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8536 expect_payment_failed!(nodes[0], our_payment_hash, false);
8539 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8540 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8541 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8542 // Carol, Alice would be the upstream node, and Carol the downstream.)
8544 // Steps of the test:
8545 // 1) Alice sends a HTLC to Carol through Bob.
8546 // 2) Carol doesn't settle the HTLC.
8547 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8548 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8549 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8550 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8551 // 5) Carol release the preimage to Bob off-chain.
8552 // 6) Bob claims the offered output on the broadcasted commitment.
8553 let chanmon_cfgs = create_chanmon_cfgs(3);
8554 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8555 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8556 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8558 // Create some initial channels
8559 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8560 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8562 // Steps (1) and (2):
8563 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8564 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8566 // Check that Alice's commitment transaction now contains an output for this HTLC.
8567 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8568 check_spends!(alice_txn[0], chan_ab.3);
8569 assert_eq!(alice_txn[0].output.len(), 2);
8570 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8571 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8572 assert_eq!(alice_txn.len(), 2);
8574 // Steps (3) and (4):
8575 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8576 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8577 let mut force_closing_node = 0; // Alice force-closes
8578 let mut counterparty_node = 1; // Bob if Alice force-closes
8581 if !broadcast_alice {
8582 force_closing_node = 1;
8583 counterparty_node = 0;
8585 nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8586 check_closed_broadcast!(nodes[force_closing_node], true);
8587 check_added_monitors!(nodes[force_closing_node], 1);
8588 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed, [nodes[counterparty_node].node.get_our_node_id()], 100000);
8589 if go_onchain_before_fulfill {
8590 let txn_to_broadcast = match broadcast_alice {
8591 true => alice_txn.clone(),
8592 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8594 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8595 if broadcast_alice {
8596 check_closed_broadcast!(nodes[1], true);
8597 check_added_monitors!(nodes[1], 1);
8598 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
8603 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8604 // process of removing the HTLC from their commitment transactions.
8605 nodes[2].node.claim_funds(payment_preimage);
8606 check_added_monitors!(nodes[2], 1);
8607 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8609 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8610 assert!(carol_updates.update_add_htlcs.is_empty());
8611 assert!(carol_updates.update_fail_htlcs.is_empty());
8612 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8613 assert!(carol_updates.update_fee.is_none());
8614 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8616 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8617 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
8618 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8619 if !go_onchain_before_fulfill && broadcast_alice {
8620 let events = nodes[1].node.get_and_clear_pending_msg_events();
8621 assert_eq!(events.len(), 1);
8623 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8624 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8626 _ => panic!("Unexpected event"),
8629 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8630 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8631 // Carol<->Bob's updated commitment transaction info.
8632 check_added_monitors!(nodes[1], 2);
8634 let events = nodes[1].node.get_and_clear_pending_msg_events();
8635 assert_eq!(events.len(), 2);
8636 let bob_revocation = match events[0] {
8637 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8638 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8641 _ => panic!("Unexpected event"),
8643 let bob_updates = match events[1] {
8644 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8645 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8648 _ => panic!("Unexpected event"),
8651 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8652 check_added_monitors!(nodes[2], 1);
8653 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8654 check_added_monitors!(nodes[2], 1);
8656 let events = nodes[2].node.get_and_clear_pending_msg_events();
8657 assert_eq!(events.len(), 1);
8658 let carol_revocation = match events[0] {
8659 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8660 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8663 _ => panic!("Unexpected event"),
8665 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8666 check_added_monitors!(nodes[1], 1);
8668 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8669 // here's where we put said channel's commitment tx on-chain.
8670 let mut txn_to_broadcast = alice_txn.clone();
8671 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8672 if !go_onchain_before_fulfill {
8673 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8674 // If Bob was the one to force-close, he will have already passed these checks earlier.
8675 if broadcast_alice {
8676 check_closed_broadcast!(nodes[1], true);
8677 check_added_monitors!(nodes[1], 1);
8678 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
8680 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8681 if broadcast_alice {
8682 assert_eq!(bob_txn.len(), 1);
8683 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8685 assert_eq!(bob_txn.len(), 2);
8686 check_spends!(bob_txn[0], chan_ab.3);
8691 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8692 // broadcasted commitment transaction.
8694 let script_weight = match broadcast_alice {
8695 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8696 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8698 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8699 // Bob force-closed and broadcasts the commitment transaction along with a
8700 // HTLC-output-claiming transaction.
8701 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8702 if broadcast_alice {
8703 assert_eq!(bob_txn.len(), 1);
8704 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8705 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8707 assert_eq!(bob_txn.len(), 2);
8708 check_spends!(bob_txn[1], txn_to_broadcast[0]);
8709 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8715 fn test_onchain_htlc_settlement_after_close() {
8716 do_test_onchain_htlc_settlement_after_close(true, true);
8717 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8718 do_test_onchain_htlc_settlement_after_close(true, false);
8719 do_test_onchain_htlc_settlement_after_close(false, false);
8723 fn test_duplicate_temporary_channel_id_from_different_peers() {
8724 // Tests that we can accept two different `OpenChannel` requests with the same
8725 // `temporary_channel_id`, as long as they are from different peers.
8726 let chanmon_cfgs = create_chanmon_cfgs(3);
8727 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8728 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8729 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8731 // Create an first channel channel
8732 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8733 let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8735 // Create an second channel
8736 nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None).unwrap();
8737 let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8739 // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8740 // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8741 open_chan_msg_chan_2_0.temporary_channel_id = open_chan_msg_chan_1_0.temporary_channel_id;
8743 // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8744 // `temporary_channel_id` as they are from different peers.
8745 nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
8747 let events = nodes[0].node.get_and_clear_pending_msg_events();
8748 assert_eq!(events.len(), 1);
8750 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8751 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8752 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8754 _ => panic!("Unexpected event"),
8758 nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
8760 let events = nodes[0].node.get_and_clear_pending_msg_events();
8761 assert_eq!(events.len(), 1);
8763 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8764 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
8765 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8767 _ => panic!("Unexpected event"),
8773 fn test_duplicate_chan_id() {
8774 // Test that if a given peer tries to open a channel with the same channel_id as one that is
8775 // already open we reject it and keep the old channel.
8777 // Previously, full_stack_target managed to figure out that if you tried to open two channels
8778 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8779 // the existing channel when we detect the duplicate new channel, screwing up our monitor
8780 // updating logic for the existing channel.
8781 let chanmon_cfgs = create_chanmon_cfgs(2);
8782 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8783 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8784 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8786 // Create an initial channel
8787 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8788 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8789 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8790 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
8792 // Try to create a second channel with the same temporary_channel_id as the first and check
8793 // that it is rejected.
8794 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8796 let events = nodes[1].node.get_and_clear_pending_msg_events();
8797 assert_eq!(events.len(), 1);
8799 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8800 // Technically, at this point, nodes[1] would be justified in thinking both the
8801 // first (valid) and second (invalid) channels are closed, given they both have
8802 // the same non-temporary channel_id. However, currently we do not, so we just
8803 // move forward with it.
8804 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8805 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8807 _ => panic!("Unexpected event"),
8811 // Move the first channel through the funding flow...
8812 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8814 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8815 check_added_monitors!(nodes[0], 0);
8817 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8818 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8820 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8821 assert_eq!(added_monitors.len(), 1);
8822 assert_eq!(added_monitors[0].0, funding_output);
8823 added_monitors.clear();
8825 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
8827 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8829 let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8830 let channel_id = funding_outpoint.to_channel_id();
8832 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8835 // First try to open a second channel with a temporary channel id equal to the txid-based one.
8836 // Technically this is allowed by the spec, but we don't support it and there's little reason
8837 // to. Still, it shouldn't cause any other issues.
8838 open_chan_msg.temporary_channel_id = channel_id;
8839 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8841 let events = nodes[1].node.get_and_clear_pending_msg_events();
8842 assert_eq!(events.len(), 1);
8844 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8845 // Technically, at this point, nodes[1] would be justified in thinking both
8846 // channels are closed, but currently we do not, so we just move forward with it.
8847 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8848 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8850 _ => panic!("Unexpected event"),
8854 // Now try to create a second channel which has a duplicate funding output.
8855 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8856 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8857 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
8858 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
8859 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
8861 let (_, funding_created) = {
8862 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
8863 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
8864 // Once we call `get_funding_created` the channel has a duplicate channel_id as
8865 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
8866 // try to create another channel. Instead, we drop the channel entirely here (leaving the
8867 // channelmanager in a possibly nonsense state instead).
8868 let mut as_chan = a_peer_state.outbound_v1_channel_by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
8869 let logger = test_utils::TestLogger::new();
8870 as_chan.get_funding_created(tx.clone(), funding_outpoint, &&logger).map_err(|_| ()).unwrap()
8872 check_added_monitors!(nodes[0], 0);
8873 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8874 // At this point we'll look up if the channel_id is present and immediately fail the channel
8875 // without trying to persist the `ChannelMonitor`.
8876 check_added_monitors!(nodes[1], 0);
8878 // ...still, nodes[1] will reject the duplicate channel.
8880 let events = nodes[1].node.get_and_clear_pending_msg_events();
8881 assert_eq!(events.len(), 1);
8883 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8884 // Technically, at this point, nodes[1] would be justified in thinking both
8885 // channels are closed, but currently we do not, so we just move forward with it.
8886 assert_eq!(msg.channel_id, channel_id);
8887 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8889 _ => panic!("Unexpected event"),
8893 // finally, finish creating the original channel and send a payment over it to make sure
8894 // everything is functional.
8895 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8897 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8898 assert_eq!(added_monitors.len(), 1);
8899 assert_eq!(added_monitors[0].0, funding_output);
8900 added_monitors.clear();
8902 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
8904 let events_4 = nodes[0].node.get_and_clear_pending_events();
8905 assert_eq!(events_4.len(), 0);
8906 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8907 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8909 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8910 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
8911 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8913 send_payment(&nodes[0], &[&nodes[1]], 8000000);
8917 fn test_error_chans_closed() {
8918 // Test that we properly handle error messages, closing appropriate channels.
8920 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8921 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8922 // we can test various edge cases around it to ensure we don't regress.
8923 let chanmon_cfgs = create_chanmon_cfgs(3);
8924 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8925 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8926 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8928 // Create some initial channels
8929 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8930 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8931 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
8933 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8934 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8935 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8937 // Closing a channel from a different peer has no effect
8938 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8939 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8941 // Closing one channel doesn't impact others
8942 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
8943 check_added_monitors!(nodes[0], 1);
8944 check_closed_broadcast!(nodes[0], false);
8945 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) },
8946 [nodes[1].node.get_our_node_id()], 100000);
8947 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
8948 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
8949 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_1.2 || nodes[0].node.list_usable_channels()[1].channel_id == chan_1.2);
8950 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2 || nodes[0].node.list_usable_channels()[1].channel_id == chan_3.2);
8952 // A null channel ID should close all channels
8953 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8954 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
8955 check_added_monitors!(nodes[0], 2);
8956 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) },
8957 [nodes[1].node.get_our_node_id(); 2], 100000);
8958 let events = nodes[0].node.get_and_clear_pending_msg_events();
8959 assert_eq!(events.len(), 2);
8961 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8962 assert_eq!(msg.contents.flags & 2, 2);
8964 _ => panic!("Unexpected event"),
8967 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8968 assert_eq!(msg.contents.flags & 2, 2);
8970 _ => panic!("Unexpected event"),
8972 // Note that at this point users of a standard PeerHandler will end up calling
8973 // peer_disconnected.
8974 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8975 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8977 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
8978 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8979 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8983 fn test_invalid_funding_tx() {
8984 // Test that we properly handle invalid funding transactions sent to us from a peer.
8986 // Previously, all other major lightning implementations had failed to properly sanitize
8987 // funding transactions from their counterparties, leading to a multi-implementation critical
8988 // security vulnerability (though we always sanitized properly, we've previously had
8989 // un-released crashes in the sanitization process).
8991 // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
8992 // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
8993 // gave up on it. We test this here by generating such a transaction.
8994 let chanmon_cfgs = create_chanmon_cfgs(2);
8995 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8996 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8997 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8999 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9000 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id()));
9001 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
9003 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9005 // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9006 // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9007 // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9009 let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9010 let wit_program_script: Script = wit_program.into();
9011 for output in tx.output.iter_mut() {
9012 // Make the confirmed funding transaction have a bogus script_pubkey
9013 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9016 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9017 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id()));
9018 check_added_monitors!(nodes[1], 1);
9019 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9021 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id()));
9022 check_added_monitors!(nodes[0], 1);
9023 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9025 let events_1 = nodes[0].node.get_and_clear_pending_events();
9026 assert_eq!(events_1.len(), 0);
9028 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9029 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9030 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9032 let expected_err = "funding tx had wrong script/value or output index";
9033 confirm_transaction_at(&nodes[1], &tx, 1);
9034 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() },
9035 [nodes[0].node.get_our_node_id()], 100000);
9036 check_added_monitors!(nodes[1], 1);
9037 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9038 assert_eq!(events_2.len(), 1);
9039 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9040 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9041 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9042 assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9043 } else { panic!(); }
9044 } else { panic!(); }
9045 assert_eq!(nodes[1].node.list_channels().len(), 0);
9047 // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9048 // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9049 // as its not 32 bytes long.
9050 let mut spend_tx = Transaction {
9051 version: 2i32, lock_time: PackedLockTime::ZERO,
9052 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9053 previous_output: BitcoinOutPoint {
9057 script_sig: Script::new(),
9058 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9059 witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9061 output: vec![TxOut {
9063 script_pubkey: Script::new(),
9066 check_spends!(spend_tx, tx);
9067 mine_transaction(&nodes[1], &spend_tx);
9070 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9071 // In the first version of the chain::Confirm interface, after a refactor was made to not
9072 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9073 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9074 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9075 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9076 // spending transaction until height N+1 (or greater). This was due to the way
9077 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9078 // spending transaction at the height the input transaction was confirmed at, not whether we
9079 // should broadcast a spending transaction at the current height.
9080 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9081 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9082 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9083 // until we learned about an additional block.
9085 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9086 // aren't broadcasting transactions too early (ie not broadcasting them at all).
9087 let chanmon_cfgs = create_chanmon_cfgs(3);
9088 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9089 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9090 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9091 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9093 create_announced_chan_between_nodes(&nodes, 0, 1);
9094 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
9095 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9096 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
9097 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9099 nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9100 check_closed_broadcast!(nodes[1], true);
9101 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[2].node.get_our_node_id()], 100000);
9102 check_added_monitors!(nodes[1], 1);
9103 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9104 assert_eq!(node_txn.len(), 1);
9106 let conf_height = nodes[1].best_block_info().1;
9107 if !test_height_before_timelock {
9108 connect_blocks(&nodes[1], 24 * 6);
9110 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9111 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9112 if test_height_before_timelock {
9113 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9114 // generate any events or broadcast any transactions
9115 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9116 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9118 // We should broadcast an HTLC transaction spending our funding transaction first
9119 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9120 assert_eq!(spending_txn.len(), 2);
9121 assert_eq!(spending_txn[0].txid(), node_txn[0].txid());
9122 check_spends!(spending_txn[1], node_txn[0]);
9123 // We should also generate a SpendableOutputs event with the to_self output (as its
9125 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9126 assert_eq!(descriptor_spend_txn.len(), 1);
9128 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9129 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9130 // additional block built on top of the current chain.
9131 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9132 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9133 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: channel_id }]);
9134 check_added_monitors!(nodes[1], 1);
9136 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9137 assert!(updates.update_add_htlcs.is_empty());
9138 assert!(updates.update_fulfill_htlcs.is_empty());
9139 assert_eq!(updates.update_fail_htlcs.len(), 1);
9140 assert!(updates.update_fail_malformed_htlcs.is_empty());
9141 assert!(updates.update_fee.is_none());
9142 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9143 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9144 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9149 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9150 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9151 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9154 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9155 let chanmon_cfgs = create_chanmon_cfgs(2);
9156 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9157 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9158 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9160 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9162 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9163 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
9164 let route = get_route!(nodes[0], payment_params, 10_000).unwrap();
9166 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9169 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9170 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9171 check_added_monitors!(nodes[0], 1);
9172 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9173 assert_eq!(events.len(), 1);
9174 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9175 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9176 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9178 expect_pending_htlcs_forwardable!(nodes[1]);
9179 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9182 // Note that we use a different PaymentId here to allow us to duplicativly pay
9183 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9184 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9185 check_added_monitors!(nodes[0], 1);
9186 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9187 assert_eq!(events.len(), 1);
9188 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9189 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9190 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9191 // At this point, nodes[1] would notice it has too much value for the payment. It will
9192 // assume the second is a privacy attack (no longer particularly relevant
9193 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9194 // the first HTLC delivered above.
9197 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9198 nodes[1].node.process_pending_htlc_forwards();
9200 if test_for_second_fail_panic {
9201 // Now we go fail back the first HTLC from the user end.
9202 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9204 let expected_destinations = vec![
9205 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9206 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9208 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], expected_destinations);
9209 nodes[1].node.process_pending_htlc_forwards();
9211 check_added_monitors!(nodes[1], 1);
9212 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9213 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9215 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9216 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9217 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9219 let failure_events = nodes[0].node.get_and_clear_pending_events();
9220 assert_eq!(failure_events.len(), 4);
9221 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9222 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9223 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9224 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9226 // Let the second HTLC fail and claim the first
9227 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9228 nodes[1].node.process_pending_htlc_forwards();
9230 check_added_monitors!(nodes[1], 1);
9231 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9232 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9233 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9235 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9237 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9242 fn test_dup_htlc_second_fail_panic() {
9243 // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9244 // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9245 // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9246 // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9247 do_test_dup_htlc_second_rejected(true);
9251 fn test_dup_htlc_second_rejected() {
9252 // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9253 // simply reject the second HTLC but are still able to claim the first HTLC.
9254 do_test_dup_htlc_second_rejected(false);
9258 fn test_inconsistent_mpp_params() {
9259 // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9260 // such HTLC and allow the second to stay.
9261 let chanmon_cfgs = create_chanmon_cfgs(4);
9262 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9263 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9264 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9266 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9267 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9268 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9269 let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9271 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9272 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
9273 let mut route = get_route!(nodes[0], payment_params, 15_000_000).unwrap();
9274 assert_eq!(route.paths.len(), 2);
9275 route.paths.sort_by(|path_a, _| {
9276 // Sort the path so that the path through nodes[1] comes first
9277 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9278 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9281 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9283 let cur_height = nodes[0].best_block_info().1;
9284 let payment_id = PaymentId([42; 32]);
9286 let session_privs = {
9287 // We create a fake route here so that we start with three pending HTLCs, which we'll
9288 // ultimately have, just not right away.
9289 let mut dup_route = route.clone();
9290 dup_route.paths.push(route.paths[1].clone());
9291 nodes[0].node.test_add_new_pending_payment(our_payment_hash,
9292 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &dup_route).unwrap()
9294 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
9295 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9296 &None, session_privs[0]).unwrap();
9297 check_added_monitors!(nodes[0], 1);
9300 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9301 assert_eq!(events.len(), 1);
9302 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9304 assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9306 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9307 RecipientOnionFields::secret_only(our_payment_secret), 14_000_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9308 check_added_monitors!(nodes[0], 1);
9311 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9312 assert_eq!(events.len(), 1);
9313 let payment_event = SendEvent::from_event(events.pop().unwrap());
9315 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9316 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9318 expect_pending_htlcs_forwardable!(nodes[2]);
9319 check_added_monitors!(nodes[2], 1);
9321 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9322 assert_eq!(events.len(), 1);
9323 let payment_event = SendEvent::from_event(events.pop().unwrap());
9325 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9326 check_added_monitors!(nodes[3], 0);
9327 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9329 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9330 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9331 // post-payment_secrets) and fail back the new HTLC.
9333 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9334 nodes[3].node.process_pending_htlc_forwards();
9335 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9336 nodes[3].node.process_pending_htlc_forwards();
9338 check_added_monitors!(nodes[3], 1);
9340 let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9341 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9342 commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9344 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }]);
9345 check_added_monitors!(nodes[2], 1);
9347 let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9348 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9349 commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9351 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9353 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9354 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9355 &None, session_privs[2]).unwrap();
9356 check_added_monitors!(nodes[0], 1);
9358 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9359 assert_eq!(events.len(), 1);
9360 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9362 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9363 expect_payment_sent(&nodes[0], our_payment_preimage, Some(None), true, true);
9367 fn test_double_partial_claim() {
9368 // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9369 // time out, the sender resends only some of the MPP parts, then the user processes the
9370 // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9372 let chanmon_cfgs = create_chanmon_cfgs(4);
9373 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9374 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9375 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9377 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9378 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9379 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9380 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9382 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9383 assert_eq!(route.paths.len(), 2);
9384 route.paths.sort_by(|path_a, _| {
9385 // Sort the path so that the path through nodes[1] comes first
9386 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9387 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9390 send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9391 // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9392 // amount of time to respond to.
9394 // Connect some blocks to time out the payment
9395 connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9396 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9398 let failed_destinations = vec![
9399 HTLCDestination::FailedPayment { payment_hash },
9400 HTLCDestination::FailedPayment { payment_hash },
9402 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9404 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
9406 // nodes[1] now retries one of the two paths...
9407 nodes[0].node.send_payment_with_route(&route, payment_hash,
9408 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9409 check_added_monitors!(nodes[0], 2);
9411 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9412 assert_eq!(events.len(), 2);
9413 let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
9414 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9416 // At this point nodes[3] has received one half of the payment, and the user goes to handle
9417 // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9418 nodes[3].node.claim_funds(payment_preimage);
9419 check_added_monitors!(nodes[3], 0);
9420 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9423 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9424 #[derive(Clone, Copy, PartialEq)]
9425 enum ExposureEvent {
9426 /// Breach occurs at HTLC forwarding (see `send_htlc`)
9428 /// Breach occurs at HTLC reception (see `update_add_htlc`)
9430 /// Breach occurs at outbound update_fee (see `send_update_fee`)
9431 AtUpdateFeeOutbound,
9434 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool, multiplier_dust_limit: bool) {
9435 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9438 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9439 // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9440 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9441 // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9442 // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9443 // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9444 // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9445 // might be available again for HTLC processing once the dust bandwidth has cleared up.
9447 let chanmon_cfgs = create_chanmon_cfgs(2);
9448 let mut config = test_default_channel_config();
9449 config.channel_config.max_dust_htlc_exposure = if multiplier_dust_limit {
9450 // Default test fee estimator rate is 253 sat/kw, so we set the multiplier to 5_000_000 / 253
9451 // to get roughly the same initial value as the default setting when this test was
9452 // originally written.
9453 MaxDustHTLCExposure::FeeRateMultiplier(5_000_000 / 253)
9454 } else { MaxDustHTLCExposure::FixedLimitMsat(5_000_000) }; // initial default setting value
9455 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9456 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9457 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9459 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9460 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9461 open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9462 open_channel.max_accepted_htlcs = 60;
9464 open_channel.dust_limit_satoshis = 546;
9466 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9467 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9468 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9470 let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
9472 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9475 let mut node_0_per_peer_lock;
9476 let mut node_0_peer_state_lock;
9477 let mut chan = get_outbound_v1_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, temporary_channel_id);
9478 chan.context.holder_dust_limit_satoshis = 546;
9481 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9482 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id()));
9483 check_added_monitors!(nodes[1], 1);
9484 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9486 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id()));
9487 check_added_monitors!(nodes[0], 1);
9488 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9490 let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9491 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9492 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9494 // Fetch a route in advance as we will be unable to once we're unable to send.
9495 let (mut route, payment_hash, _, payment_secret) =
9496 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
9498 let (dust_buffer_feerate, max_dust_htlc_exposure_msat) = {
9499 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9500 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9501 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
9502 (chan.context.get_dust_buffer_feerate(None) as u64,
9503 chan.context.get_max_dust_htlc_exposure_msat(&LowerBoundedFeeEstimator(nodes[0].fee_estimator)))
9505 let dust_outbound_htlc_on_holder_tx_msat: u64 = (dust_buffer_feerate * htlc_timeout_tx_weight(&channel_type_features) / 1000 + open_channel.dust_limit_satoshis - 1) * 1000;
9506 let dust_outbound_htlc_on_holder_tx: u64 = max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9508 let dust_inbound_htlc_on_holder_tx_msat: u64 = (dust_buffer_feerate * htlc_success_tx_weight(&channel_type_features) / 1000 + open_channel.dust_limit_satoshis - 1) * 1000;
9509 let dust_inbound_htlc_on_holder_tx: u64 = max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9511 let dust_htlc_on_counterparty_tx: u64 = 4;
9512 let dust_htlc_on_counterparty_tx_msat: u64 = max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9515 if dust_outbound_balance {
9516 // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9517 // Outbound dust balance: 4372 sats
9518 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9519 for _ in 0..dust_outbound_htlc_on_holder_tx {
9520 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9521 nodes[0].node.send_payment_with_route(&route, payment_hash,
9522 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9525 // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9526 // Inbound dust balance: 4372 sats
9527 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9528 for _ in 0..dust_inbound_htlc_on_holder_tx {
9529 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9533 if dust_outbound_balance {
9534 // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9535 // Outbound dust balance: 5000 sats
9536 for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9537 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9538 nodes[0].node.send_payment_with_route(&route, payment_hash,
9539 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9542 // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9543 // Inbound dust balance: 5000 sats
9544 for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9545 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9550 if exposure_breach_event == ExposureEvent::AtHTLCForward {
9551 route.paths[0].hops.last_mut().unwrap().fee_msat =
9552 if on_holder_tx { dust_outbound_htlc_on_holder_tx_msat } else { dust_htlc_on_counterparty_tx_msat + 1 };
9553 // With default dust exposure: 5000 sats
9555 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9556 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9557 ), true, APIError::ChannelUnavailable { .. }, {});
9559 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9560 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9561 ), true, APIError::ChannelUnavailable { .. }, {});
9563 } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9564 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], if on_holder_tx { dust_inbound_htlc_on_holder_tx_msat } else { dust_htlc_on_counterparty_tx_msat + 4 });
9565 nodes[1].node.send_payment_with_route(&route, payment_hash,
9566 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9567 check_added_monitors!(nodes[1], 1);
9568 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9569 assert_eq!(events.len(), 1);
9570 let payment_event = SendEvent::from_event(events.remove(0));
9571 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9572 // With default dust exposure: 5000 sats
9574 // Outbound dust balance: 6399 sats
9575 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9576 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9577 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on holder commitment tx", if dust_outbound_balance { dust_outbound_overflow } else { dust_inbound_overflow }, max_dust_htlc_exposure_msat), 1);
9579 // Outbound dust balance: 5200 sats
9580 nodes[0].logger.assert_log("lightning::ln::channel".to_string(),
9581 format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx",
9582 dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx - 1) + dust_htlc_on_counterparty_tx_msat + 4,
9583 max_dust_htlc_exposure_msat), 1);
9585 } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9586 route.paths[0].hops.last_mut().unwrap().fee_msat = 2_500_000;
9587 // For the multiplier dust exposure limit, since it scales with feerate,
9588 // we need to add a lot of HTLCs that will become dust at the new feerate
9589 // to cross the threshold.
9591 let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[1], Some(1_000), None);
9592 nodes[0].node.send_payment_with_route(&route, payment_hash,
9593 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9596 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9597 *feerate_lock = *feerate_lock * 10;
9599 nodes[0].node.timer_tick_occurred();
9600 check_added_monitors!(nodes[0], 1);
9601 nodes[0].logger.assert_log_contains("lightning::ln::channel", "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure", 1);
9604 let _ = nodes[0].node.get_and_clear_pending_msg_events();
9605 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9606 added_monitors.clear();
9609 fn do_test_max_dust_htlc_exposure_by_threshold_type(multiplier_dust_limit: bool) {
9610 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true, multiplier_dust_limit);
9611 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true, multiplier_dust_limit);
9612 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true, multiplier_dust_limit);
9613 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false, multiplier_dust_limit);
9614 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false, multiplier_dust_limit);
9615 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false, multiplier_dust_limit);
9616 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true, multiplier_dust_limit);
9617 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false, multiplier_dust_limit);
9618 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true, multiplier_dust_limit);
9619 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false, multiplier_dust_limit);
9620 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false, multiplier_dust_limit);
9621 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true, multiplier_dust_limit);
9625 fn test_max_dust_htlc_exposure() {
9626 do_test_max_dust_htlc_exposure_by_threshold_type(false);
9627 do_test_max_dust_htlc_exposure_by_threshold_type(true);
9631 fn test_non_final_funding_tx() {
9632 let chanmon_cfgs = create_chanmon_cfgs(2);
9633 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9634 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9635 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9637 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9638 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9639 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9640 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9641 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
9643 let best_height = nodes[0].node.best_block.read().unwrap().height();
9645 let chan_id = *nodes[0].network_chan_count.borrow();
9646 let events = nodes[0].node.get_and_clear_pending_events();
9647 let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
9648 assert_eq!(events.len(), 1);
9649 let mut tx = match events[0] {
9650 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9651 // Timelock the transaction _beyond_ the best client height + 1.
9652 Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 2), input: vec![input], output: vec![TxOut {
9653 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9656 _ => panic!("Unexpected event"),
9658 // Transaction should fail as it's evaluated as non-final for propagation.
9659 match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
9660 Err(APIError::APIMisuseError { err }) => {
9661 assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
9666 // However, transaction should be accepted if it's in a +1 headroom from best block.
9667 tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
9668 assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
9669 get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9673 fn accept_busted_but_better_fee() {
9674 // If a peer sends us a fee update that is too low, but higher than our previous channel
9675 // feerate, we should accept it. In the future we may want to consider closing the channel
9676 // later, but for now we only accept the update.
9677 let mut chanmon_cfgs = create_chanmon_cfgs(2);
9678 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9679 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9680 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9682 create_chan_between_nodes(&nodes[0], &nodes[1]);
9684 // Set nodes[1] to expect 5,000 sat/kW.
9686 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
9687 *feerate_lock = 5000;
9690 // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
9692 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9693 *feerate_lock = 1000;
9695 nodes[0].node.timer_tick_occurred();
9696 check_added_monitors!(nodes[0], 1);
9698 let events = nodes[0].node.get_and_clear_pending_msg_events();
9699 assert_eq!(events.len(), 1);
9701 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9702 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9703 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9705 _ => panic!("Unexpected event"),
9708 // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
9711 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9712 *feerate_lock = 2000;
9714 nodes[0].node.timer_tick_occurred();
9715 check_added_monitors!(nodes[0], 1);
9717 let events = nodes[0].node.get_and_clear_pending_msg_events();
9718 assert_eq!(events.len(), 1);
9720 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9721 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9722 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9724 _ => panic!("Unexpected event"),
9727 // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
9730 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9731 *feerate_lock = 1000;
9733 nodes[0].node.timer_tick_occurred();
9734 check_added_monitors!(nodes[0], 1);
9736 let events = nodes[0].node.get_and_clear_pending_msg_events();
9737 assert_eq!(events.len(), 1);
9739 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
9740 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9741 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
9742 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000 (- 250)".to_owned() },
9743 [nodes[0].node.get_our_node_id()], 100000);
9744 check_closed_broadcast!(nodes[1], true);
9745 check_added_monitors!(nodes[1], 1);
9747 _ => panic!("Unexpected event"),
9751 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
9752 let mut chanmon_cfgs = create_chanmon_cfgs(2);
9753 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9754 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9755 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9756 let min_final_cltv_expiry_delta = 120;
9757 let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
9758 min_final_cltv_expiry_delta - 2 };
9759 let recv_value = 100_000;
9761 create_chan_between_nodes(&nodes[0], &nodes[1]);
9763 let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), final_cltv_expiry_delta as u32);
9764 let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
9765 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
9766 Some(recv_value), Some(min_final_cltv_expiry_delta));
9767 (payment_hash, payment_preimage, payment_secret)
9769 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
9770 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
9772 let route = get_route!(nodes[0], payment_parameters, recv_value).unwrap();
9773 nodes[0].node.send_payment_with_route(&route, payment_hash,
9774 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9775 check_added_monitors!(nodes[0], 1);
9776 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9777 assert_eq!(events.len(), 1);
9778 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9779 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9780 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9781 expect_pending_htlcs_forwardable!(nodes[1]);
9784 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
9785 None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
9787 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9789 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
9791 check_added_monitors!(nodes[1], 1);
9793 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9794 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
9795 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
9797 expect_payment_failed!(nodes[0], payment_hash, true);
9802 fn test_payment_with_custom_min_cltv_expiry_delta() {
9803 do_payment_with_custom_min_final_cltv_expiry(false, false);
9804 do_payment_with_custom_min_final_cltv_expiry(false, true);
9805 do_payment_with_custom_min_final_cltv_expiry(true, false);
9806 do_payment_with_custom_min_final_cltv_expiry(true, true);
9810 fn test_disconnects_peer_awaiting_response_ticks() {
9811 // Tests that nodes which are awaiting on a response critical for channel responsiveness
9812 // disconnect their counterparty after `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
9813 let mut chanmon_cfgs = create_chanmon_cfgs(2);
9814 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9815 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9816 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9818 // Asserts a disconnect event is queued to the user.
9819 let check_disconnect_event = |node: &Node, should_disconnect: bool| {
9820 let disconnect_event = node.node.get_and_clear_pending_msg_events().iter().find_map(|event|
9821 if let MessageSendEvent::HandleError { action, .. } = event {
9822 if let msgs::ErrorAction::DisconnectPeerWithWarning { .. } = action {
9831 assert_eq!(disconnect_event.is_some(), should_disconnect);
9834 // Fires timer ticks ensuring we only attempt to disconnect peers after reaching
9835 // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
9836 let check_disconnect = |node: &Node| {
9837 // No disconnect without any timer ticks.
9838 check_disconnect_event(node, false);
9840 // No disconnect with 1 timer tick less than required.
9841 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS - 1 {
9842 node.node.timer_tick_occurred();
9843 check_disconnect_event(node, false);
9846 // Disconnect after reaching the required ticks.
9847 node.node.timer_tick_occurred();
9848 check_disconnect_event(node, true);
9850 // Disconnect again on the next tick if the peer hasn't been disconnected yet.
9851 node.node.timer_tick_occurred();
9852 check_disconnect_event(node, true);
9855 create_chan_between_nodes(&nodes[0], &nodes[1]);
9857 // We'll start by performing a fee update with Alice (nodes[0]) on the channel.
9858 *nodes[0].fee_estimator.sat_per_kw.lock().unwrap() *= 2;
9859 nodes[0].node.timer_tick_occurred();
9860 check_added_monitors!(&nodes[0], 1);
9861 let alice_fee_update = get_htlc_update_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
9862 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), alice_fee_update.update_fee.as_ref().unwrap());
9863 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &alice_fee_update.commitment_signed);
9864 check_added_monitors!(&nodes[1], 1);
9866 // This will prompt Bob (nodes[1]) to respond with his `CommitmentSigned` and `RevokeAndACK`.
9867 let (bob_revoke_and_ack, bob_commitment_signed) = get_revoke_commit_msgs!(&nodes[1], nodes[0].node.get_our_node_id());
9868 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revoke_and_ack);
9869 check_added_monitors!(&nodes[0], 1);
9870 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_commitment_signed);
9871 check_added_monitors(&nodes[0], 1);
9873 // Alice then needs to send her final `RevokeAndACK` to complete the commitment dance. We
9874 // pretend Bob hasn't received the message and check whether he'll disconnect Alice after
9875 // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
9876 let alice_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
9877 check_disconnect(&nodes[1]);
9879 // Now, we'll reconnect them to test awaiting a `ChannelReestablish` message.
9881 // Note that since the commitment dance didn't complete above, Alice is expected to resend her
9882 // final `RevokeAndACK` to Bob to complete it.
9883 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9884 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
9885 let bob_init = msgs::Init {
9886 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
9888 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &bob_init, true).unwrap();
9889 let alice_init = msgs::Init {
9890 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
9892 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &alice_init, true).unwrap();
9894 // Upon reconnection, Alice sends her `ChannelReestablish` to Bob. Alice, however, hasn't
9895 // received Bob's yet, so she should disconnect him after reaching
9896 // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
9897 let alice_channel_reestablish = get_event_msg!(
9898 nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id()
9900 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &alice_channel_reestablish);
9901 check_disconnect(&nodes[0]);
9903 // Bob now sends his `ChannelReestablish` to Alice to resume the channel and consider it "live".
9904 let bob_channel_reestablish = nodes[1].node.get_and_clear_pending_msg_events().iter().find_map(|event|
9905 if let MessageSendEvent::SendChannelReestablish { node_id, msg } = event {
9906 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9912 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bob_channel_reestablish);
9914 // Sanity check that Alice won't disconnect Bob since she's no longer waiting for any messages.
9915 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
9916 nodes[0].node.timer_tick_occurred();
9917 check_disconnect_event(&nodes[0], false);
9920 // However, Bob is still waiting on Alice's `RevokeAndACK`, so he should disconnect her after
9921 // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
9922 check_disconnect(&nodes[1]);
9924 // Finally, have Bob process the last message.
9925 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &alice_revoke_and_ack);
9926 check_added_monitors(&nodes[1], 1);
9928 // At this point, neither node should attempt to disconnect each other, since they aren't
9929 // waiting on any messages.
9930 for node in &nodes {
9931 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
9932 node.node.timer_tick_occurred();
9933 check_disconnect_event(node, false);
9939 fn test_remove_expired_outbound_unfunded_channels() {
9940 let chanmon_cfgs = create_chanmon_cfgs(2);
9941 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9942 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9943 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9945 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9946 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9947 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9948 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9949 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
9951 let events = nodes[0].node.get_and_clear_pending_events();
9952 assert_eq!(events.len(), 1);
9954 Event::FundingGenerationReady { .. } => (),
9955 _ => panic!("Unexpected event"),
9958 // Asserts the outbound channel has been removed from a nodes[0]'s peer state map.
9959 let check_outbound_channel_existence = |should_exist: bool| {
9960 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9961 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9962 assert_eq!(chan_lock.outbound_v1_channel_by_id.contains_key(&temp_channel_id), should_exist);
9965 // Channel should exist without any timer ticks.
9966 check_outbound_channel_existence(true);
9968 // Channel should exist with 1 timer tick less than required.
9969 for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS - 1 {
9970 nodes[0].node.timer_tick_occurred();
9971 check_outbound_channel_existence(true)
9974 // Remove channel after reaching the required ticks.
9975 nodes[0].node.timer_tick_occurred();
9976 check_outbound_channel_existence(false);
9978 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
9979 assert_eq!(msg_events.len(), 1);
9980 match msg_events[0] {
9981 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
9982 assert_eq!(msg.data, "Force-closing pending channel due to timeout awaiting establishment handshake");
9984 _ => panic!("Unexpected event"),
9986 check_closed_event(&nodes[0], 1, ClosureReason::HolderForceClosed, false, &[nodes[1].node.get_our_node_id()], 100000);
9990 fn test_remove_expired_inbound_unfunded_channels() {
9991 let chanmon_cfgs = create_chanmon_cfgs(2);
9992 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9993 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9994 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9996 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9997 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9998 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9999 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10000 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10002 let events = nodes[0].node.get_and_clear_pending_events();
10003 assert_eq!(events.len(), 1);
10005 Event::FundingGenerationReady { .. } => (),
10006 _ => panic!("Unexpected event"),
10009 // Asserts the inbound channel has been removed from a nodes[1]'s peer state map.
10010 let check_inbound_channel_existence = |should_exist: bool| {
10011 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
10012 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
10013 assert_eq!(chan_lock.inbound_v1_channel_by_id.contains_key(&temp_channel_id), should_exist);
10016 // Channel should exist without any timer ticks.
10017 check_inbound_channel_existence(true);
10019 // Channel should exist with 1 timer tick less than required.
10020 for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS - 1 {
10021 nodes[1].node.timer_tick_occurred();
10022 check_inbound_channel_existence(true)
10025 // Remove channel after reaching the required ticks.
10026 nodes[1].node.timer_tick_occurred();
10027 check_inbound_channel_existence(false);
10029 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
10030 assert_eq!(msg_events.len(), 1);
10031 match msg_events[0] {
10032 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
10033 assert_eq!(msg.data, "Force-closing pending channel due to timeout awaiting establishment handshake");
10035 _ => panic!("Unexpected event"),
10037 check_closed_event(&nodes[1], 1, ClosureReason::HolderForceClosed, false, &[nodes[0].node.get_our_node_id()], 100000);
10040 fn do_test_multi_post_event_actions(do_reload: bool) {
10041 // Tests handling multiple post-Event actions at once.
10042 // There is specific code in ChannelManager to handle channels where multiple post-Event
10043 // `ChannelMonitorUpdates` are pending at once. This test exercises that code.
10045 // Specifically, we test calling `get_and_clear_pending_events` while there are two
10046 // PaymentSents from different channels and one channel has two pending `ChannelMonitorUpdate`s
10047 // - one from an RAA and one from an inbound commitment_signed.
10048 let chanmon_cfgs = create_chanmon_cfgs(3);
10049 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10050 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10051 let (persister, chain_monitor, nodes_0_deserialized);
10052 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10054 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
10055 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 0, 2).2;
10057 send_payment(&nodes[0], &[&nodes[1]], 1_000_000);
10058 send_payment(&nodes[0], &[&nodes[2]], 1_000_000);
10060 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
10061 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[2]], 1_000_000);
10063 nodes[1].node.claim_funds(our_payment_preimage);
10064 check_added_monitors!(nodes[1], 1);
10065 expect_payment_claimed!(nodes[1], our_payment_hash, 1_000_000);
10067 nodes[2].node.claim_funds(payment_preimage_2);
10068 check_added_monitors!(nodes[2], 1);
10069 expect_payment_claimed!(nodes[2], payment_hash_2, 1_000_000);
10071 for dest in &[1, 2] {
10072 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[*dest], nodes[0].node.get_our_node_id());
10073 nodes[0].node.handle_update_fulfill_htlc(&nodes[*dest].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
10074 commitment_signed_dance!(nodes[0], nodes[*dest], htlc_fulfill_updates.commitment_signed, false);
10075 check_added_monitors(&nodes[0], 0);
10078 let (route, payment_hash_3, _, payment_secret_3) =
10079 get_route_and_payment_hash!(nodes[1], nodes[0], 100_000);
10080 let payment_id = PaymentId(payment_hash_3.0);
10081 nodes[1].node.send_payment_with_route(&route, payment_hash_3,
10082 RecipientOnionFields::secret_only(payment_secret_3), payment_id).unwrap();
10083 check_added_monitors(&nodes[1], 1);
10085 let send_event = SendEvent::from_node(&nodes[1]);
10086 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event.msgs[0]);
10087 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_event.commitment_msg);
10088 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
10091 let nodes_0_serialized = nodes[0].node.encode();
10092 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
10093 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_2).encode();
10094 reload_node!(nodes[0], test_default_channel_config(), &nodes_0_serialized, &[&chan_0_monitor_serialized, &chan_1_monitor_serialized], persister, chain_monitor, nodes_0_deserialized);
10096 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10097 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10099 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
10100 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[2]));
10103 let events = nodes[0].node.get_and_clear_pending_events();
10104 assert_eq!(events.len(), 4);
10105 if let Event::PaymentSent { payment_preimage, .. } = events[0] {
10106 assert!(payment_preimage == our_payment_preimage || payment_preimage == payment_preimage_2);
10107 } else { panic!(); }
10108 if let Event::PaymentSent { payment_preimage, .. } = events[1] {
10109 assert!(payment_preimage == our_payment_preimage || payment_preimage == payment_preimage_2);
10110 } else { panic!(); }
10111 if let Event::PaymentPathSuccessful { .. } = events[2] {} else { panic!(); }
10112 if let Event::PaymentPathSuccessful { .. } = events[3] {} else { panic!(); }
10114 // After the events are processed, the ChannelMonitorUpdates will be released and, upon their
10115 // completion, we'll respond to nodes[1] with an RAA + CS.
10116 get_revoke_commit_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
10117 check_added_monitors(&nodes[0], 3);
10121 fn test_multi_post_event_actions() {
10122 do_test_multi_post_event_actions(true);
10123 do_test_multi_post_event_actions(false);