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::{CLOSED_CHANNEL_UPDATE_ID, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
19 use crate::chain::transaction::OutPoint;
20 use crate::sign::{ecdsa::EcdsaChannelSigner, EntropySource, SignerProvider};
21 use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentPurpose, ClosureReason, HTLCDestination, PaymentFailureReason};
22 use crate::ln::{ChannelId, 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, COINBASE_MATURITY, ChannelPhase};
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, RouteParameters};
30 use crate::ln::features::{ChannelFeatures, ChannelTypeFeatures, NodeFeatures};
32 use crate::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction};
33 use crate::util::test_channel_signer::TestChannelSigner;
34 use crate::util::test_utils::{self, WatchtowerPersister};
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::locktime::absolute::LockTime;
42 use bitcoin::blockdata::script::{Builder, ScriptBuf};
43 use bitcoin::blockdata::opcodes;
44 use bitcoin::blockdata::constants::ChainHash;
45 use bitcoin::network::constants::Network;
46 use bitcoin::{Sequence, Transaction, TxIn, TxOut, Witness};
47 use bitcoin::OutPoint as BitcoinOutPoint;
49 use bitcoin::secp256k1::Secp256k1;
50 use bitcoin::secp256k1::{PublicKey,SecretKey};
55 use crate::prelude::*;
56 use alloc::collections::BTreeSet;
57 use core::default::Default;
58 use core::iter::repeat;
59 use bitcoin::hashes::Hash;
60 use crate::sync::{Arc, Mutex, RwLock};
62 use crate::ln::functional_test_utils::*;
63 use crate::ln::chan_utils::CommitmentTransaction;
65 use super::channel::UNFUNDED_CHANNEL_AGE_LIMIT_TICKS;
68 fn test_insane_channel_opens() {
69 // Stand up a network of 2 nodes
70 use crate::ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
71 let mut cfg = UserConfig::default();
72 cfg.channel_handshake_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
73 let chanmon_cfgs = create_chanmon_cfgs(2);
74 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
75 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
76 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
78 // Instantiate channel parameters where we push the maximum msats given our
80 let channel_value_sat = 31337; // same as funding satoshis
81 let channel_reserve_satoshis = get_holder_selected_channel_reserve_satoshis(channel_value_sat, &cfg);
82 let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
84 // Have node0 initiate a channel to node1 with aforementioned parameters
85 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None, None).unwrap();
87 // Extract the channel open message from node0 to node1
88 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
90 // Test helper that asserts we get the correct error string given a mutator
91 // that supposedly makes the channel open message insane
92 let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
93 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &message_mutator(open_channel_message.clone()));
94 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
95 assert_eq!(msg_events.len(), 1);
96 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
97 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
99 &ErrorAction::SendErrorMessage { .. } => {
100 nodes[1].logger.assert_log_regex("lightning::ln::channelmanager", expected_regex, 1);
102 _ => panic!("unexpected event!"),
104 } else { assert!(false); }
107 use crate::ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
109 // Test all mutations that would make the channel open message insane
110 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 });
111 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 });
113 insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
115 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 });
117 insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
119 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 });
121 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 });
123 insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
125 insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
129 fn test_funding_exceeds_no_wumbo_limit() {
130 // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
132 use crate::ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
133 let chanmon_cfgs = create_chanmon_cfgs(2);
134 let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
135 *node_cfgs[1].override_init_features.borrow_mut() = Some(channelmanager::provided_init_features(&test_default_channel_config()).clear_wumbo());
136 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
137 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
139 match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None, None) {
140 Err(APIError::APIMisuseError { err }) => {
141 assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
147 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
148 // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
149 // but only for them. Because some LSPs do it with some level of trust of the clients (for a
150 // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
151 // in normal testing, we test it explicitly here.
152 let chanmon_cfgs = create_chanmon_cfgs(2);
153 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
154 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
155 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
156 let default_config = UserConfig::default();
158 // Have node0 initiate a channel to node1 with aforementioned parameters
159 let mut push_amt = 100_000_000;
160 let feerate_per_kw = 253;
161 let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
162 push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(&channel_type_features) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
163 push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
165 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, None).unwrap();
166 let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
167 if !send_from_initiator {
168 open_channel_message.channel_reserve_satoshis = 0;
169 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
171 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
173 // Extract the channel accept message from node1 to node0
174 let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
175 if send_from_initiator {
176 accept_channel_message.channel_reserve_satoshis = 0;
177 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
179 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
181 let sender_node = if send_from_initiator { &nodes[1] } else { &nodes[0] };
182 let counterparty_node = if send_from_initiator { &nodes[0] } else { &nodes[1] };
183 let mut sender_node_per_peer_lock;
184 let mut sender_node_peer_state_lock;
186 let channel_phase = get_channel_ref!(sender_node, counterparty_node, sender_node_per_peer_lock, sender_node_peer_state_lock, temp_channel_id);
187 match channel_phase {
188 ChannelPhase::UnfundedInboundV1(_) | ChannelPhase::UnfundedOutboundV1(_) => {
189 let chan_context = channel_phase.context_mut();
190 chan_context.holder_selected_channel_reserve_satoshis = 0;
191 chan_context.holder_max_htlc_value_in_flight_msat = 100_000_000;
193 ChannelPhase::Funded(_) => assert!(false),
197 let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
198 let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
199 create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
201 // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
202 // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
203 if send_from_initiator {
204 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
205 // Note that for outbound channels we have to consider the commitment tx fee and the
206 // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
207 // well as an additional HTLC.
208 - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, &channel_type_features));
210 send_payment(&nodes[1], &[&nodes[0]], push_amt);
215 fn test_counterparty_no_reserve() {
216 do_test_counterparty_no_reserve(true);
217 do_test_counterparty_no_reserve(false);
221 fn test_async_inbound_update_fee() {
222 let chanmon_cfgs = create_chanmon_cfgs(2);
223 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
224 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
225 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
226 create_announced_chan_between_nodes(&nodes, 0, 1);
229 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
233 // send (1) commitment_signed -.
234 // <- update_add_htlc/commitment_signed
235 // send (2) RAA (awaiting remote revoke) -.
236 // (1) commitment_signed is delivered ->
237 // .- send (3) RAA (awaiting remote revoke)
238 // (2) RAA is delivered ->
239 // .- send (4) commitment_signed
240 // <- (3) RAA is delivered
241 // send (5) commitment_signed -.
242 // <- (4) commitment_signed is delivered
244 // (5) commitment_signed is delivered ->
246 // (6) RAA is delivered ->
248 // First nodes[0] generates an update_fee
250 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
253 nodes[0].node.timer_tick_occurred();
254 check_added_monitors!(nodes[0], 1);
256 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
257 assert_eq!(events_0.len(), 1);
258 let (update_msg, commitment_signed) = match events_0[0] { // (1)
259 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
260 (update_fee.as_ref(), commitment_signed)
262 _ => panic!("Unexpected event"),
265 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
267 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
268 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
269 nodes[1].node.send_payment_with_route(&route, our_payment_hash,
270 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
271 check_added_monitors!(nodes[1], 1);
273 let payment_event = {
274 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
275 assert_eq!(events_1.len(), 1);
276 SendEvent::from_event(events_1.remove(0))
278 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
279 assert_eq!(payment_event.msgs.len(), 1);
281 // ...now when the messages get delivered everyone should be happy
282 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
283 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
284 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
285 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
286 check_added_monitors!(nodes[0], 1);
288 // deliver(1), generate (3):
289 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
290 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
291 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
292 check_added_monitors!(nodes[1], 1);
294 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
295 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
296 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
297 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
298 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
299 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
300 assert!(bs_update.update_fee.is_none()); // (4)
301 check_added_monitors!(nodes[1], 1);
303 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
304 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
305 assert!(as_update.update_add_htlcs.is_empty()); // (5)
306 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
307 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
308 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
309 assert!(as_update.update_fee.is_none()); // (5)
310 check_added_monitors!(nodes[0], 1);
312 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
313 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
314 // only (6) so get_event_msg's assert(len == 1) passes
315 check_added_monitors!(nodes[0], 1);
317 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
318 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
319 check_added_monitors!(nodes[1], 1);
321 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
322 check_added_monitors!(nodes[0], 1);
324 let events_2 = nodes[0].node.get_and_clear_pending_events();
325 assert_eq!(events_2.len(), 1);
327 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
328 _ => panic!("Unexpected event"),
331 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
332 check_added_monitors!(nodes[1], 1);
336 fn test_update_fee_unordered_raa() {
337 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
338 // crash in an earlier version of the update_fee patch)
339 let chanmon_cfgs = create_chanmon_cfgs(2);
340 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
341 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
342 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
343 create_announced_chan_between_nodes(&nodes, 0, 1);
346 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
348 // First nodes[0] generates an update_fee
350 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
353 nodes[0].node.timer_tick_occurred();
354 check_added_monitors!(nodes[0], 1);
356 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
357 assert_eq!(events_0.len(), 1);
358 let update_msg = match events_0[0] { // (1)
359 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
362 _ => panic!("Unexpected event"),
365 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
367 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
368 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
369 nodes[1].node.send_payment_with_route(&route, our_payment_hash,
370 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
371 check_added_monitors!(nodes[1], 1);
373 let payment_event = {
374 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
375 assert_eq!(events_1.len(), 1);
376 SendEvent::from_event(events_1.remove(0))
378 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
379 assert_eq!(payment_event.msgs.len(), 1);
381 // ...now when the messages get delivered everyone should be happy
382 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
383 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
384 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
385 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
386 check_added_monitors!(nodes[0], 1);
388 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
389 check_added_monitors!(nodes[1], 1);
391 // We can't continue, sadly, because our (1) now has a bogus signature
395 fn test_multi_flight_update_fee() {
396 let chanmon_cfgs = create_chanmon_cfgs(2);
397 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
398 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
399 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
400 create_announced_chan_between_nodes(&nodes, 0, 1);
403 // update_fee/commitment_signed ->
404 // .- send (1) RAA and (2) commitment_signed
405 // update_fee (never committed) ->
407 // We have to manually generate the above update_fee, it is allowed by the protocol but we
408 // don't track which updates correspond to which revoke_and_ack responses so we're in
409 // AwaitingRAA mode and will not generate the update_fee yet.
410 // <- (1) RAA delivered
411 // (3) is generated and send (4) CS -.
412 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
413 // know the per_commitment_point to use for it.
414 // <- (2) commitment_signed delivered
416 // B should send no response here
417 // (4) commitment_signed delivered ->
418 // <- RAA/commitment_signed delivered
421 // First nodes[0] generates an update_fee
424 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
425 initial_feerate = *feerate_lock;
426 *feerate_lock = initial_feerate + 20;
428 nodes[0].node.timer_tick_occurred();
429 check_added_monitors!(nodes[0], 1);
431 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
432 assert_eq!(events_0.len(), 1);
433 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
434 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
435 (update_fee.as_ref().unwrap(), commitment_signed)
437 _ => panic!("Unexpected event"),
440 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
441 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
442 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
443 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
444 check_added_monitors!(nodes[1], 1);
446 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
449 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
450 *feerate_lock = initial_feerate + 40;
452 nodes[0].node.timer_tick_occurred();
453 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
454 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
456 // Create the (3) update_fee message that nodes[0] will generate before it does...
457 let mut update_msg_2 = msgs::UpdateFee {
458 channel_id: update_msg_1.channel_id.clone(),
459 feerate_per_kw: (initial_feerate + 30) as u32,
462 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
464 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
466 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
468 // Deliver (1), generating (3) and (4)
469 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
470 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
471 check_added_monitors!(nodes[0], 1);
472 assert!(as_second_update.update_add_htlcs.is_empty());
473 assert!(as_second_update.update_fulfill_htlcs.is_empty());
474 assert!(as_second_update.update_fail_htlcs.is_empty());
475 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
476 // Check that the update_fee newly generated matches what we delivered:
477 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
478 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
480 // Deliver (2) commitment_signed
481 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
482 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
483 check_added_monitors!(nodes[0], 1);
484 // No commitment_signed so get_event_msg's assert(len == 1) passes
486 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
487 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
488 check_added_monitors!(nodes[1], 1);
491 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
492 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
493 check_added_monitors!(nodes[1], 1);
495 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
496 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
497 check_added_monitors!(nodes[0], 1);
499 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
500 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
501 // No commitment_signed so get_event_msg's assert(len == 1) passes
502 check_added_monitors!(nodes[0], 1);
504 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
505 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
506 check_added_monitors!(nodes[1], 1);
509 fn do_test_sanity_on_in_flight_opens(steps: u8) {
510 // Previously, we had issues deserializing channels when we hadn't connected the first block
511 // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
512 // serialization round-trips and simply do steps towards opening a channel and then drop the
515 let chanmon_cfgs = create_chanmon_cfgs(2);
516 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
517 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
518 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
520 if steps & 0b1000_0000 != 0{
521 let block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
522 connect_block(&nodes[0], &block);
523 connect_block(&nodes[1], &block);
526 if steps & 0x0f == 0 { return; }
527 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
528 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
530 if steps & 0x0f == 1 { return; }
531 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
532 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
534 if steps & 0x0f == 2 { return; }
535 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
537 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
539 if steps & 0x0f == 3 { return; }
540 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
541 check_added_monitors!(nodes[0], 0);
542 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
544 if steps & 0x0f == 4 { return; }
545 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
547 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
548 assert_eq!(added_monitors.len(), 1);
549 assert_eq!(added_monitors[0].0, funding_output);
550 added_monitors.clear();
552 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
554 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
556 if steps & 0x0f == 5 { return; }
557 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
559 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
560 assert_eq!(added_monitors.len(), 1);
561 assert_eq!(added_monitors[0].0, funding_output);
562 added_monitors.clear();
565 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
566 let events_4 = nodes[0].node.get_and_clear_pending_events();
567 assert_eq!(events_4.len(), 0);
569 if steps & 0x0f == 6 { return; }
570 create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
572 if steps & 0x0f == 7 { return; }
573 confirm_transaction_at(&nodes[0], &tx, 2);
574 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
575 create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
576 expect_channel_ready_event(&nodes[0], &nodes[1].node.get_our_node_id());
580 fn test_sanity_on_in_flight_opens() {
581 do_test_sanity_on_in_flight_opens(0);
582 do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
583 do_test_sanity_on_in_flight_opens(1);
584 do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
585 do_test_sanity_on_in_flight_opens(2);
586 do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
587 do_test_sanity_on_in_flight_opens(3);
588 do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
589 do_test_sanity_on_in_flight_opens(4);
590 do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
591 do_test_sanity_on_in_flight_opens(5);
592 do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
593 do_test_sanity_on_in_flight_opens(6);
594 do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
595 do_test_sanity_on_in_flight_opens(7);
596 do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
597 do_test_sanity_on_in_flight_opens(8);
598 do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
602 fn test_update_fee_vanilla() {
603 let chanmon_cfgs = create_chanmon_cfgs(2);
604 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
605 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
606 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
607 create_announced_chan_between_nodes(&nodes, 0, 1);
610 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
613 nodes[0].node.timer_tick_occurred();
614 check_added_monitors!(nodes[0], 1);
616 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
617 assert_eq!(events_0.len(), 1);
618 let (update_msg, commitment_signed) = match events_0[0] {
619 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 } } => {
620 (update_fee.as_ref(), commitment_signed)
622 _ => panic!("Unexpected event"),
624 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
626 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
627 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
628 check_added_monitors!(nodes[1], 1);
630 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
631 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
632 check_added_monitors!(nodes[0], 1);
634 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
635 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
636 // No commitment_signed so get_event_msg's assert(len == 1) passes
637 check_added_monitors!(nodes[0], 1);
639 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
640 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
641 check_added_monitors!(nodes[1], 1);
645 fn test_update_fee_that_funder_cannot_afford() {
646 let chanmon_cfgs = create_chanmon_cfgs(2);
647 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
648 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
649 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
650 let channel_value = 5000;
652 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000);
653 let channel_id = chan.2;
654 let secp_ctx = Secp256k1::new();
655 let default_config = UserConfig::default();
656 let bs_channel_reserve_sats = get_holder_selected_channel_reserve_satoshis(channel_value, &default_config);
658 let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
660 // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
661 // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
662 // calculate two different feerates here - the expected local limit as well as the expected
664 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;
665 let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(&channel_type_features)) as u32;
667 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
668 *feerate_lock = feerate;
670 nodes[0].node.timer_tick_occurred();
671 check_added_monitors!(nodes[0], 1);
672 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
674 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
676 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
678 // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
680 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
682 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
683 assert_eq!(commitment_tx.output.len(), 2);
684 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, &channel_type_features) / 1000;
685 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
686 actual_fee = channel_value - actual_fee;
687 assert_eq!(total_fee, actual_fee);
691 // Increment the feerate by a small constant, accounting for rounding errors
692 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
695 nodes[0].node.timer_tick_occurred();
696 nodes[0].logger.assert_log("lightning::ln::channel", format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
697 check_added_monitors!(nodes[0], 0);
699 const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
701 // Get the TestChannelSigner for each channel, which will be used to (1) get the keys
702 // needed to sign the new commitment tx and (2) sign the new commitment tx.
703 let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
704 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
705 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
706 let local_chan = chan_lock.channel_by_id.get(&chan.2).map(
707 |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
708 ).flatten().unwrap();
709 let chan_signer = local_chan.get_signer();
710 let pubkeys = chan_signer.as_ref().pubkeys();
711 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
712 pubkeys.funding_pubkey)
714 let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
715 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
716 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
717 let remote_chan = chan_lock.channel_by_id.get(&chan.2).map(
718 |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
719 ).flatten().unwrap();
720 let chan_signer = remote_chan.get_signer();
721 let pubkeys = chan_signer.as_ref().pubkeys();
722 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
723 chan_signer.as_ref().get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
724 pubkeys.funding_pubkey)
727 // Assemble the set of keys we can use for signatures for our commitment_signed message.
728 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
729 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
732 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
733 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
734 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).map(
735 |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
736 ).flatten().unwrap();
737 let local_chan_signer = local_chan.get_signer();
738 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
739 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
740 INITIAL_COMMITMENT_NUMBER - 1,
742 channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, &channel_type_features) / 1000,
743 local_funding, remote_funding,
744 commit_tx_keys.clone(),
745 non_buffer_feerate + 4,
747 &local_chan.context.channel_transaction_parameters.as_counterparty_broadcastable()
749 local_chan_signer.as_ecdsa().unwrap().sign_counterparty_commitment(&commitment_tx, Vec::new(), Vec::new(), &secp_ctx).unwrap()
752 let commit_signed_msg = msgs::CommitmentSigned {
755 htlc_signatures: res.1,
757 partial_signature_with_nonce: None,
760 let update_fee = msgs::UpdateFee {
762 feerate_per_kw: non_buffer_feerate + 4,
765 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
767 //While producing the commitment_signed response after handling a received update_fee request the
768 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
769 //Should produce and error.
770 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
771 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Funding remote cannot afford proposed new fee", 3);
772 check_added_monitors!(nodes[1], 1);
773 check_closed_broadcast!(nodes[1], true);
774 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") },
775 [nodes[0].node.get_our_node_id()], channel_value);
779 fn test_update_fee_with_fundee_update_add_htlc() {
780 let chanmon_cfgs = create_chanmon_cfgs(2);
781 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
782 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
783 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
784 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
787 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
790 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
793 nodes[0].node.timer_tick_occurred();
794 check_added_monitors!(nodes[0], 1);
796 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
797 assert_eq!(events_0.len(), 1);
798 let (update_msg, commitment_signed) = match events_0[0] {
799 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 } } => {
800 (update_fee.as_ref(), commitment_signed)
802 _ => panic!("Unexpected event"),
804 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
805 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
806 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
807 check_added_monitors!(nodes[1], 1);
809 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
811 // nothing happens since node[1] is in AwaitingRemoteRevoke
812 nodes[1].node.send_payment_with_route(&route, our_payment_hash,
813 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
815 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
816 assert_eq!(added_monitors.len(), 0);
817 added_monitors.clear();
819 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
820 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
821 // node[1] has nothing to do
823 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
824 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
825 check_added_monitors!(nodes[0], 1);
827 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
828 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
829 // No commitment_signed so get_event_msg's assert(len == 1) passes
830 check_added_monitors!(nodes[0], 1);
831 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
832 check_added_monitors!(nodes[1], 1);
833 // AwaitingRemoteRevoke ends here
835 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
836 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
837 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
838 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
839 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
840 assert_eq!(commitment_update.update_fee.is_none(), true);
842 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
843 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
844 check_added_monitors!(nodes[0], 1);
845 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
847 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
848 check_added_monitors!(nodes[1], 1);
849 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
851 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
852 check_added_monitors!(nodes[1], 1);
853 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
854 // No commitment_signed so get_event_msg's assert(len == 1) passes
856 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
857 check_added_monitors!(nodes[0], 1);
858 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
860 expect_pending_htlcs_forwardable!(nodes[0]);
862 let events = nodes[0].node.get_and_clear_pending_events();
863 assert_eq!(events.len(), 1);
865 Event::PaymentClaimable { .. } => { },
866 _ => panic!("Unexpected event"),
869 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
871 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
872 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
873 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
874 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
875 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
879 fn test_update_fee() {
880 let chanmon_cfgs = create_chanmon_cfgs(2);
881 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
882 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
883 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
884 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
885 let channel_id = chan.2;
888 // (1) update_fee/commitment_signed ->
889 // <- (2) revoke_and_ack
890 // .- send (3) commitment_signed
891 // (4) update_fee/commitment_signed ->
892 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
893 // <- (3) commitment_signed delivered
894 // send (6) revoke_and_ack -.
895 // <- (5) deliver revoke_and_ack
896 // (6) deliver revoke_and_ack ->
897 // .- send (7) commitment_signed in response to (4)
898 // <- (7) deliver commitment_signed
901 // Create and deliver (1)...
904 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
905 feerate = *feerate_lock;
906 *feerate_lock = feerate + 20;
908 nodes[0].node.timer_tick_occurred();
909 check_added_monitors!(nodes[0], 1);
911 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
912 assert_eq!(events_0.len(), 1);
913 let (update_msg, commitment_signed) = match events_0[0] {
914 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 } } => {
915 (update_fee.as_ref(), commitment_signed)
917 _ => panic!("Unexpected event"),
919 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
921 // Generate (2) and (3):
922 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
923 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
924 check_added_monitors!(nodes[1], 1);
927 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
928 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
929 check_added_monitors!(nodes[0], 1);
931 // Create and deliver (4)...
933 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
934 *feerate_lock = feerate + 30;
936 nodes[0].node.timer_tick_occurred();
937 check_added_monitors!(nodes[0], 1);
938 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
939 assert_eq!(events_0.len(), 1);
940 let (update_msg, commitment_signed) = match events_0[0] {
941 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 } } => {
942 (update_fee.as_ref(), commitment_signed)
944 _ => panic!("Unexpected event"),
947 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
948 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
949 check_added_monitors!(nodes[1], 1);
951 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
952 // No commitment_signed so get_event_msg's assert(len == 1) passes
954 // Handle (3), creating (6):
955 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
956 check_added_monitors!(nodes[0], 1);
957 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
958 // No commitment_signed so get_event_msg's assert(len == 1) passes
961 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
962 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
963 check_added_monitors!(nodes[0], 1);
965 // Deliver (6), creating (7):
966 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
967 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
968 assert!(commitment_update.update_add_htlcs.is_empty());
969 assert!(commitment_update.update_fulfill_htlcs.is_empty());
970 assert!(commitment_update.update_fail_htlcs.is_empty());
971 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
972 assert!(commitment_update.update_fee.is_none());
973 check_added_monitors!(nodes[1], 1);
976 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
977 check_added_monitors!(nodes[0], 1);
978 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
979 // No commitment_signed so get_event_msg's assert(len == 1) passes
981 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
982 check_added_monitors!(nodes[1], 1);
983 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
985 assert_eq!(get_feerate!(nodes[0], nodes[1], channel_id), feerate + 30);
986 assert_eq!(get_feerate!(nodes[1], nodes[0], channel_id), feerate + 30);
987 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
988 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
989 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
993 fn fake_network_test() {
994 // Simple test which builds a network of ChannelManagers, connects them to each other, and
995 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
996 let chanmon_cfgs = create_chanmon_cfgs(4);
997 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
998 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
999 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1001 // Create some initial channels
1002 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1003 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1004 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
1006 // Rebalance the network a bit by relaying one payment through all the channels...
1007 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1008 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1009 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1010 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1012 // Send some more payments
1013 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
1014 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
1015 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
1017 // Test failure packets
1018 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1019 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1021 // Add a new channel that skips 3
1022 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
1024 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
1025 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
1026 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1027 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1028 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1029 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1030 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1032 // Do some rebalance loop payments, simultaneously
1033 let mut hops = Vec::with_capacity(3);
1034 hops.push(RouteHop {
1035 pubkey: nodes[2].node.get_our_node_id(),
1036 node_features: NodeFeatures::empty(),
1037 short_channel_id: chan_2.0.contents.short_channel_id,
1038 channel_features: ChannelFeatures::empty(),
1040 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32,
1041 maybe_announced_channel: true,
1043 hops.push(RouteHop {
1044 pubkey: nodes[3].node.get_our_node_id(),
1045 node_features: NodeFeatures::empty(),
1046 short_channel_id: chan_3.0.contents.short_channel_id,
1047 channel_features: ChannelFeatures::empty(),
1049 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32,
1050 maybe_announced_channel: true,
1052 hops.push(RouteHop {
1053 pubkey: nodes[1].node.get_our_node_id(),
1054 node_features: nodes[1].node.node_features(),
1055 short_channel_id: chan_4.0.contents.short_channel_id,
1056 channel_features: nodes[1].node.channel_features(),
1058 cltv_expiry_delta: TEST_FINAL_CLTV,
1059 maybe_announced_channel: true,
1061 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;
1062 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;
1063 let payment_preimage_1 = send_along_route(&nodes[1],
1064 Route { paths: vec![Path { hops, blinded_tail: None }], route_params: None },
1065 &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1067 let mut hops = Vec::with_capacity(3);
1068 hops.push(RouteHop {
1069 pubkey: nodes[3].node.get_our_node_id(),
1070 node_features: NodeFeatures::empty(),
1071 short_channel_id: chan_4.0.contents.short_channel_id,
1072 channel_features: ChannelFeatures::empty(),
1074 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32,
1075 maybe_announced_channel: true,
1077 hops.push(RouteHop {
1078 pubkey: nodes[2].node.get_our_node_id(),
1079 node_features: NodeFeatures::empty(),
1080 short_channel_id: chan_3.0.contents.short_channel_id,
1081 channel_features: ChannelFeatures::empty(),
1083 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32,
1084 maybe_announced_channel: true,
1086 hops.push(RouteHop {
1087 pubkey: nodes[1].node.get_our_node_id(),
1088 node_features: nodes[1].node.node_features(),
1089 short_channel_id: chan_2.0.contents.short_channel_id,
1090 channel_features: nodes[1].node.channel_features(),
1092 cltv_expiry_delta: TEST_FINAL_CLTV,
1093 maybe_announced_channel: true,
1095 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;
1096 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;
1097 let payment_hash_2 = send_along_route(&nodes[1],
1098 Route { paths: vec![Path { hops, blinded_tail: None }], route_params: None },
1099 &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1101 // Claim the rebalances...
1102 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1103 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1105 // Close down the channels...
1106 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1107 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1108 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
1109 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1110 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[2].node.get_our_node_id()], 100000);
1111 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1112 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1113 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure, [nodes[3].node.get_our_node_id()], 100000);
1114 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure, [nodes[2].node.get_our_node_id()], 100000);
1115 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1116 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[3].node.get_our_node_id()], 100000);
1117 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1121 fn holding_cell_htlc_counting() {
1122 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1123 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1124 // commitment dance rounds.
1125 let chanmon_cfgs = create_chanmon_cfgs(3);
1126 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1127 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1128 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1129 create_announced_chan_between_nodes(&nodes, 0, 1);
1130 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1132 // Fetch a route in advance as we will be unable to once we're unable to send.
1133 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1135 let mut payments = Vec::new();
1137 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1138 nodes[1].node.send_payment_with_route(&route, payment_hash,
1139 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1140 payments.push((payment_preimage, payment_hash));
1142 check_added_monitors!(nodes[1], 1);
1144 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1145 assert_eq!(events.len(), 1);
1146 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1147 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1149 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1150 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1153 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, payment_hash_1,
1154 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)
1155 ), true, APIError::ChannelUnavailable { .. }, {});
1156 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1159 // This should also be true if we try to forward a payment.
1160 let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1162 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1163 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1164 check_added_monitors!(nodes[0], 1);
1167 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1168 assert_eq!(events.len(), 1);
1169 let payment_event = SendEvent::from_event(events.pop().unwrap());
1170 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1172 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1173 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1174 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1175 // fails), the second will process the resulting failure and fail the HTLC backward.
1176 expect_pending_htlcs_forwardable!(nodes[1]);
1177 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 }]);
1178 check_added_monitors!(nodes[1], 1);
1180 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1181 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1182 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1184 expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1186 // Now forward all the pending HTLCs and claim them back
1187 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1188 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1189 check_added_monitors!(nodes[2], 1);
1191 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1192 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1193 check_added_monitors!(nodes[1], 1);
1194 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1196 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1197 check_added_monitors!(nodes[1], 1);
1198 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1200 for ref update in as_updates.update_add_htlcs.iter() {
1201 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1203 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1204 check_added_monitors!(nodes[2], 1);
1205 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1206 check_added_monitors!(nodes[2], 1);
1207 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1209 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1210 check_added_monitors!(nodes[1], 1);
1211 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1212 check_added_monitors!(nodes[1], 1);
1213 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1215 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1216 check_added_monitors!(nodes[2], 1);
1218 expect_pending_htlcs_forwardable!(nodes[2]);
1220 let events = nodes[2].node.get_and_clear_pending_events();
1221 assert_eq!(events.len(), payments.len());
1222 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1224 &Event::PaymentClaimable { ref payment_hash, .. } => {
1225 assert_eq!(*payment_hash, *hash);
1227 _ => panic!("Unexpected event"),
1231 for (preimage, _) in payments.drain(..) {
1232 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1235 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1239 fn duplicate_htlc_test() {
1240 // Test that we accept duplicate payment_hash HTLCs across the network and that
1241 // claiming/failing them are all separate and don't affect each other
1242 let chanmon_cfgs = create_chanmon_cfgs(6);
1243 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1244 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1245 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1247 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1248 create_announced_chan_between_nodes(&nodes, 0, 3);
1249 create_announced_chan_between_nodes(&nodes, 1, 3);
1250 create_announced_chan_between_nodes(&nodes, 2, 3);
1251 create_announced_chan_between_nodes(&nodes, 3, 4);
1252 create_announced_chan_between_nodes(&nodes, 3, 5);
1254 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1256 *nodes[0].network_payment_count.borrow_mut() -= 1;
1257 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1259 *nodes[0].network_payment_count.borrow_mut() -= 1;
1260 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1262 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1263 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1264 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1268 fn test_duplicate_htlc_different_direction_onchain() {
1269 // Test that ChannelMonitor doesn't generate 2 preimage txn
1270 // when we have 2 HTLCs with same preimage that go across a node
1271 // in opposite directions, even with the same payment secret.
1272 let chanmon_cfgs = create_chanmon_cfgs(2);
1273 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1274 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1275 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1277 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1280 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1282 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1284 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1285 let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
1286 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1288 // Provide preimage to node 0 by claiming payment
1289 nodes[0].node.claim_funds(payment_preimage);
1290 expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1291 check_added_monitors!(nodes[0], 1);
1293 // Broadcast node 1 commitment txn
1294 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1296 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1297 let mut has_both_htlcs = 0; // check htlcs match ones committed
1298 for outp in remote_txn[0].output.iter() {
1299 if outp.value == 800_000 / 1000 {
1300 has_both_htlcs += 1;
1301 } else if outp.value == 900_000 / 1000 {
1302 has_both_htlcs += 1;
1305 assert_eq!(has_both_htlcs, 2);
1307 mine_transaction(&nodes[0], &remote_txn[0]);
1308 check_added_monitors!(nodes[0], 1);
1309 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
1310 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
1312 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1313 assert_eq!(claim_txn.len(), 3);
1315 check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1316 check_spends!(claim_txn[1], remote_txn[0]);
1317 check_spends!(claim_txn[2], remote_txn[0]);
1318 let preimage_tx = &claim_txn[0];
1319 let (preimage_bump_tx, timeout_tx) = if claim_txn[1].input[0].previous_output == preimage_tx.input[0].previous_output {
1320 (&claim_txn[1], &claim_txn[2])
1322 (&claim_txn[2], &claim_txn[1])
1325 assert_eq!(preimage_tx.input.len(), 1);
1326 assert_eq!(preimage_bump_tx.input.len(), 1);
1328 assert_eq!(preimage_tx.input.len(), 1);
1329 assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1330 assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1332 assert_eq!(timeout_tx.input.len(), 1);
1333 assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1334 check_spends!(timeout_tx, remote_txn[0]);
1335 assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1337 let events = nodes[0].node.get_and_clear_pending_msg_events();
1338 assert_eq!(events.len(), 3);
1341 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1342 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::DisconnectPeer { ref msg } } => {
1343 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1344 assert_eq!(msg.as_ref().unwrap().data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1346 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, .. } } => {
1347 assert!(update_add_htlcs.is_empty());
1348 assert!(update_fail_htlcs.is_empty());
1349 assert_eq!(update_fulfill_htlcs.len(), 1);
1350 assert!(update_fail_malformed_htlcs.is_empty());
1351 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1353 _ => panic!("Unexpected event"),
1359 fn test_basic_channel_reserve() {
1360 let chanmon_cfgs = create_chanmon_cfgs(2);
1361 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1362 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1363 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1364 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1366 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1367 let channel_reserve = chan_stat.channel_reserve_msat;
1369 // The 2* and +1 are for the fee spike reserve.
1370 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));
1371 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1372 let (mut route, our_payment_hash, _, our_payment_secret) =
1373 get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
1374 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1375 let err = nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1376 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1378 PaymentSendFailure::AllFailedResendSafe(ref fails) => {
1379 if let &APIError::ChannelUnavailable { .. } = &fails[0] {}
1380 else { panic!("Unexpected error variant"); }
1382 _ => panic!("Unexpected error variant"),
1384 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1386 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1390 fn test_fee_spike_violation_fails_htlc() {
1391 let chanmon_cfgs = create_chanmon_cfgs(2);
1392 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1393 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1394 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1395 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1397 let (mut route, payment_hash, _, payment_secret) =
1398 get_route_and_payment_hash!(nodes[0], nodes[1], 3460000);
1399 route.paths[0].hops[0].fee_msat += 1;
1400 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1401 let secp_ctx = Secp256k1::new();
1402 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1404 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1406 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1407 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1408 3460001, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1409 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1410 let msg = msgs::UpdateAddHTLC {
1413 amount_msat: htlc_msat,
1414 payment_hash: payment_hash,
1415 cltv_expiry: htlc_cltv,
1416 onion_routing_packet: onion_packet,
1417 skimmed_fee_msat: None,
1418 blinding_point: None,
1421 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1423 // Now manually create the commitment_signed message corresponding to the update_add
1424 // nodes[0] just sent. In the code for construction of this message, "local" refers
1425 // to the sender of the message, and "remote" refers to the receiver.
1427 let feerate_per_kw = get_feerate!(nodes[0], nodes[1], chan.2);
1429 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1431 // Get the TestChannelSigner for each channel, which will be used to (1) get the keys
1432 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1433 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1434 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1435 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1436 let local_chan = chan_lock.channel_by_id.get(&chan.2).map(
1437 |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
1438 ).flatten().unwrap();
1439 let chan_signer = local_chan.get_signer();
1440 // Make the signer believe we validated another commitment, so we can release the secret
1441 chan_signer.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
1443 let pubkeys = chan_signer.as_ref().pubkeys();
1444 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1445 chan_signer.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1446 chan_signer.as_ref().get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1447 chan_signer.as_ref().pubkeys().funding_pubkey)
1449 let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1450 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
1451 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
1452 let remote_chan = chan_lock.channel_by_id.get(&chan.2).map(
1453 |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
1454 ).flatten().unwrap();
1455 let chan_signer = remote_chan.get_signer();
1456 let pubkeys = chan_signer.as_ref().pubkeys();
1457 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1458 chan_signer.as_ref().get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1459 chan_signer.as_ref().pubkeys().funding_pubkey)
1462 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1463 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1464 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
1466 // Build the remote commitment transaction so we can sign it, and then later use the
1467 // signature for the commitment_signed message.
1468 let local_chan_balance = 1313;
1470 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1472 amount_msat: 3460001,
1473 cltv_expiry: htlc_cltv,
1475 transaction_output_index: Some(1),
1478 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1481 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1482 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1483 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).map(
1484 |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
1485 ).flatten().unwrap();
1486 let local_chan_signer = local_chan.get_signer();
1487 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1491 local_funding, remote_funding,
1492 commit_tx_keys.clone(),
1494 &mut vec![(accepted_htlc_info, ())],
1495 &local_chan.context.channel_transaction_parameters.as_counterparty_broadcastable()
1497 local_chan_signer.as_ecdsa().unwrap().sign_counterparty_commitment(&commitment_tx, Vec::new(), Vec::new(), &secp_ctx).unwrap()
1500 let commit_signed_msg = msgs::CommitmentSigned {
1503 htlc_signatures: res.1,
1505 partial_signature_with_nonce: None,
1508 // Send the commitment_signed message to the nodes[1].
1509 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1510 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1512 // Send the RAA to nodes[1].
1513 let raa_msg = msgs::RevokeAndACK {
1515 per_commitment_secret: local_secret,
1516 next_per_commitment_point: next_local_point,
1518 next_local_nonce: None,
1520 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1522 let events = nodes[1].node.get_and_clear_pending_msg_events();
1523 assert_eq!(events.len(), 1);
1524 // Make sure the HTLC failed in the way we expect.
1526 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1527 assert_eq!(update_fail_htlcs.len(), 1);
1528 update_fail_htlcs[0].clone()
1530 _ => panic!("Unexpected event"),
1532 nodes[1].logger.assert_log("lightning::ln::channel",
1533 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", raa_msg.channel_id), 1);
1535 check_added_monitors!(nodes[1], 2);
1539 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1540 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1541 // Set the fee rate for the channel very high, to the point where the fundee
1542 // sending any above-dust amount would result in a channel reserve violation.
1543 // In this test we check that we would be prevented from sending an HTLC in
1545 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1546 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1547 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1548 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1549 let default_config = UserConfig::default();
1550 let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1552 let mut push_amt = 100_000_000;
1553 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1555 push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1557 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1559 // Fetch a route in advance as we will be unable to once we're unable to send.
1560 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1561 // Sending exactly enough to hit the reserve amount should be accepted
1562 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1563 route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1566 // However one more HTLC should be significantly over the reserve amount and fail.
1567 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1568 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1569 ), true, APIError::ChannelUnavailable { .. }, {});
1570 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1574 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1575 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1576 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1577 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1578 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1579 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1580 let default_config = UserConfig::default();
1581 let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1583 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1584 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1585 // transaction fee with 0 HTLCs (183 sats)).
1586 let mut push_amt = 100_000_000;
1587 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1588 push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1589 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1591 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1592 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1593 route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1596 let (mut route, payment_hash, _, payment_secret) =
1597 get_route_and_payment_hash!(nodes[1], nodes[0], 1000);
1598 route.paths[0].hops[0].fee_msat = 700_000;
1599 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1600 let secp_ctx = Secp256k1::new();
1601 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1602 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1603 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1604 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1605 700_000, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1606 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1607 let msg = msgs::UpdateAddHTLC {
1609 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1610 amount_msat: htlc_msat,
1611 payment_hash: payment_hash,
1612 cltv_expiry: htlc_cltv,
1613 onion_routing_packet: onion_packet,
1614 skimmed_fee_msat: None,
1615 blinding_point: None,
1618 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1619 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1620 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value", 3);
1621 assert_eq!(nodes[0].node.list_channels().len(), 0);
1622 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1623 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1624 check_added_monitors!(nodes[0], 1);
1625 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() },
1626 [nodes[1].node.get_our_node_id()], 100000);
1630 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1631 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1632 // calculating our commitment transaction fee (this was previously broken).
1633 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1634 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1636 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1637 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1638 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1639 let default_config = UserConfig::default();
1640 let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1642 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1643 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1644 // transaction fee with 0 HTLCs (183 sats)).
1645 let mut push_amt = 100_000_000;
1646 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1647 push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1648 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt);
1650 let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1651 + feerate_per_kw as u64 * htlc_success_tx_weight(&channel_type_features) / 1000 * 1000 - 1;
1652 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1653 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1654 // commitment transaction fee.
1655 route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1657 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1658 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1659 route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1662 // One more than the dust amt should fail, however.
1663 let (mut route, our_payment_hash, _, our_payment_secret) =
1664 get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt);
1665 route.paths[0].hops[0].fee_msat += 1;
1666 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1667 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1668 ), true, APIError::ChannelUnavailable { .. }, {});
1672 fn test_chan_init_feerate_unaffordability() {
1673 // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1674 // channel reserve and feerate requirements.
1675 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1676 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1677 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1678 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1679 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1680 let default_config = UserConfig::default();
1681 let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1683 // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1685 let mut push_amt = 100_000_000;
1686 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1687 assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None, None).unwrap_err(),
1688 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1690 // During open, we don't have a "counterparty channel reserve" to check against, so that
1691 // requirement only comes into play on the open_channel handling side.
1692 push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1693 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None, None).unwrap();
1694 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1695 open_channel_msg.push_msat += 1;
1696 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
1698 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1699 assert_eq!(msg_events.len(), 1);
1700 match msg_events[0] {
1701 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1702 assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1704 _ => panic!("Unexpected event"),
1709 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1710 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1711 // calculating our counterparty's commitment transaction fee (this was previously broken).
1712 let chanmon_cfgs = create_chanmon_cfgs(2);
1713 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1714 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1715 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1716 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000);
1718 let payment_amt = 46000; // Dust amount
1719 // In the previous code, these first four payments would succeed.
1720 route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1721 route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1722 route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1723 route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1725 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1726 route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1727 route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1728 route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1729 route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1730 route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1732 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1733 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1734 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1735 route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1739 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1740 let chanmon_cfgs = create_chanmon_cfgs(3);
1741 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1742 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1743 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1744 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1745 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
1748 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1749 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1750 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
1751 let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
1753 // Add a 2* and +1 for the fee spike reserve.
1754 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features);
1755 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;
1756 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1758 // Add a pending HTLC.
1759 let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1760 let payment_event_1 = {
1761 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1762 RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1763 check_added_monitors!(nodes[0], 1);
1765 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1766 assert_eq!(events.len(), 1);
1767 SendEvent::from_event(events.remove(0))
1769 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1771 // Attempt to trigger a channel reserve violation --> payment failure.
1772 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, &channel_type_features);
1773 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;
1774 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1775 let mut route_2 = route_1.clone();
1776 route_2.paths[0].hops.last_mut().unwrap().fee_msat = amt_msat_2;
1778 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1779 let secp_ctx = Secp256k1::new();
1780 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1781 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1782 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1783 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
1784 &route_2.paths[0], recv_value_2, RecipientOnionFields::spontaneous_empty(), cur_height, &None).unwrap();
1785 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1).unwrap();
1786 let msg = msgs::UpdateAddHTLC {
1789 amount_msat: htlc_msat + 1,
1790 payment_hash: our_payment_hash_1,
1791 cltv_expiry: htlc_cltv,
1792 onion_routing_packet: onion_packet,
1793 skimmed_fee_msat: None,
1794 blinding_point: None,
1797 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1798 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1799 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Remote HTLC add would put them under remote reserve value", 3);
1800 assert_eq!(nodes[1].node.list_channels().len(), 1);
1801 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1802 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1803 check_added_monitors!(nodes[1], 1);
1804 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() },
1805 [nodes[0].node.get_our_node_id()], 100000);
1809 fn test_inbound_outbound_capacity_is_not_zero() {
1810 let chanmon_cfgs = create_chanmon_cfgs(2);
1811 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1812 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1813 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1814 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1815 let channels0 = node_chanmgrs[0].list_channels();
1816 let channels1 = node_chanmgrs[1].list_channels();
1817 let default_config = UserConfig::default();
1818 assert_eq!(channels0.len(), 1);
1819 assert_eq!(channels1.len(), 1);
1821 let reserve = get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1822 assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1823 assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1825 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1826 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1829 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, channel_type_features: &ChannelTypeFeatures) -> u64 {
1830 (commitment_tx_base_weight(channel_type_features) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1834 fn test_channel_reserve_holding_cell_htlcs() {
1835 let chanmon_cfgs = create_chanmon_cfgs(3);
1836 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1837 // When this test was written, the default base fee floated based on the HTLC count.
1838 // It is now fixed, so we simply set the fee to the expected value here.
1839 let mut config = test_default_channel_config();
1840 config.channel_config.forwarding_fee_base_msat = 239;
1841 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1842 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1843 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001);
1844 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001);
1846 let mut stat01 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1847 let mut stat11 = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
1849 let mut stat12 = get_channel_value_stat!(nodes[1], nodes[2], chan_2.2);
1850 let mut stat22 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
1852 macro_rules! expect_forward {
1854 let mut events = $node.node.get_and_clear_pending_msg_events();
1855 assert_eq!(events.len(), 1);
1856 check_added_monitors!($node, 1);
1857 let payment_event = SendEvent::from_event(events.remove(0));
1862 let feemsat = 239; // set above
1863 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1864 let feerate = get_feerate!(nodes[0], nodes[1], chan_1.2);
1865 let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_1.2);
1867 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1869 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1871 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1872 .with_bolt11_features(nodes[2].node.bolt11_invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1873 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, recv_value_0);
1874 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1875 assert!(route.paths[0].hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1877 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1878 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1879 ), true, APIError::ChannelUnavailable { .. }, {});
1880 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1883 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1884 // nodes[0]'s wealth
1886 let amt_msat = recv_value_0 + total_fee_msat;
1887 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1888 // Also, ensure that each payment has enough to be over the dust limit to
1889 // ensure it'll be included in each commit tx fee calculation.
1890 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, &channel_type_features);
1891 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1892 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1896 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1897 .with_bolt11_features(nodes[2].node.bolt11_invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1898 let route = get_route!(nodes[0], payment_params, recv_value_0).unwrap();
1899 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1900 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1902 let (stat01_, stat11_, stat12_, stat22_) = (
1903 get_channel_value_stat!(nodes[0], nodes[1], chan_1.2),
1904 get_channel_value_stat!(nodes[1], nodes[0], chan_1.2),
1905 get_channel_value_stat!(nodes[1], nodes[2], chan_2.2),
1906 get_channel_value_stat!(nodes[2], nodes[1], chan_2.2),
1909 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1910 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1911 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1912 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1913 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1916 // adding pending output.
1917 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1918 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1919 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1920 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1921 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1922 // cases where 1 msat over X amount will cause a payment failure, but anything less than
1923 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1924 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1925 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1927 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features);
1928 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1929 let amt_msat_1 = recv_value_1 + total_fee_msat;
1931 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);
1932 let payment_event_1 = {
1933 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1934 RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1935 check_added_monitors!(nodes[0], 1);
1937 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1938 assert_eq!(events.len(), 1);
1939 SendEvent::from_event(events.remove(0))
1941 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1943 // channel reserve test with htlc pending output > 0
1944 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1946 let mut route = route_1.clone();
1947 route.paths[0].hops.last_mut().unwrap().fee_msat = recv_value_2 + 1;
1948 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
1949 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1950 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1951 ), true, APIError::ChannelUnavailable { .. }, {});
1952 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1955 // split the rest to test holding cell
1956 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, &channel_type_features);
1957 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1958 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1959 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1961 let stat = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1962 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);
1965 // now see if they go through on both sides
1966 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);
1967 // but this will stuck in the holding cell
1968 nodes[0].node.send_payment_with_route(&route_21, our_payment_hash_21,
1969 RecipientOnionFields::secret_only(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
1970 check_added_monitors!(nodes[0], 0);
1971 let events = nodes[0].node.get_and_clear_pending_events();
1972 assert_eq!(events.len(), 0);
1974 // test with outbound holding cell amount > 0
1976 let (mut route, our_payment_hash, _, our_payment_secret) =
1977 get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22);
1978 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1979 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1980 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1981 ), true, APIError::ChannelUnavailable { .. }, {});
1982 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1985 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);
1986 // this will also stuck in the holding cell
1987 nodes[0].node.send_payment_with_route(&route_22, our_payment_hash_22,
1988 RecipientOnionFields::secret_only(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
1989 check_added_monitors!(nodes[0], 0);
1990 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1991 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1993 // flush the pending htlc
1994 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1995 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1996 check_added_monitors!(nodes[1], 1);
1998 // the pending htlc should be promoted to committed
1999 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
2000 check_added_monitors!(nodes[0], 1);
2001 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2003 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
2004 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2005 // No commitment_signed so get_event_msg's assert(len == 1) passes
2006 check_added_monitors!(nodes[0], 1);
2008 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
2009 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2010 check_added_monitors!(nodes[1], 1);
2012 expect_pending_htlcs_forwardable!(nodes[1]);
2014 let ref payment_event_11 = expect_forward!(nodes[1]);
2015 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
2016 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
2018 expect_pending_htlcs_forwardable!(nodes[2]);
2019 expect_payment_claimable!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
2021 // flush the htlcs in the holding cell
2022 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
2023 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
2024 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
2025 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
2026 expect_pending_htlcs_forwardable!(nodes[1]);
2028 let ref payment_event_3 = expect_forward!(nodes[1]);
2029 assert_eq!(payment_event_3.msgs.len(), 2);
2030 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
2031 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
2033 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2034 expect_pending_htlcs_forwardable!(nodes[2]);
2036 let events = nodes[2].node.get_and_clear_pending_events();
2037 assert_eq!(events.len(), 2);
2039 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2040 assert_eq!(our_payment_hash_21, *payment_hash);
2041 assert_eq!(recv_value_21, amount_msat);
2042 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2043 assert_eq!(via_channel_id, Some(chan_2.2));
2045 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2046 assert!(payment_preimage.is_none());
2047 assert_eq!(our_payment_secret_21, *payment_secret);
2049 _ => panic!("expected PaymentPurpose::InvoicePayment")
2052 _ => panic!("Unexpected event"),
2055 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2056 assert_eq!(our_payment_hash_22, *payment_hash);
2057 assert_eq!(recv_value_22, amount_msat);
2058 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2059 assert_eq!(via_channel_id, Some(chan_2.2));
2061 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2062 assert!(payment_preimage.is_none());
2063 assert_eq!(our_payment_secret_22, *payment_secret);
2065 _ => panic!("expected PaymentPurpose::InvoicePayment")
2068 _ => panic!("Unexpected event"),
2071 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2072 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2073 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2075 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, &channel_type_features);
2076 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2077 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2079 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
2080 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);
2081 let stat0 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
2082 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2083 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2085 let stat2 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
2086 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2090 fn channel_reserve_in_flight_removes() {
2091 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2092 // can send to its counterparty, but due to update ordering, the other side may not yet have
2093 // considered those HTLCs fully removed.
2094 // This tests that we don't count HTLCs which will not be included in the next remote
2095 // commitment transaction towards the reserve value (as it implies no commitment transaction
2096 // will be generated which violates the remote reserve value).
2097 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2099 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2100 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2101 // you only consider the value of the first HTLC, it may not),
2102 // * start routing a third HTLC from A to B,
2103 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2104 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2105 // * deliver the first fulfill from B
2106 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2108 // * deliver A's response CS and RAA.
2109 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2110 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
2111 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2112 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2113 let chanmon_cfgs = create_chanmon_cfgs(2);
2114 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2115 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2116 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2117 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2119 let b_chan_values = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
2120 // Route the first two HTLCs.
2121 let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2122 let (payment_preimage_1, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2123 let (payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2125 // Start routing the third HTLC (this is just used to get everyone in the right state).
2126 let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2128 nodes[0].node.send_payment_with_route(&route, payment_hash_3,
2129 RecipientOnionFields::secret_only(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2130 check_added_monitors!(nodes[0], 1);
2131 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2132 assert_eq!(events.len(), 1);
2133 SendEvent::from_event(events.remove(0))
2136 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2137 // initial fulfill/CS.
2138 nodes[1].node.claim_funds(payment_preimage_1);
2139 expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2140 check_added_monitors!(nodes[1], 1);
2141 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2143 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2144 // remove the second HTLC when we send the HTLC back from B to A.
2145 nodes[1].node.claim_funds(payment_preimage_2);
2146 expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2147 check_added_monitors!(nodes[1], 1);
2148 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2150 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2151 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2152 check_added_monitors!(nodes[0], 1);
2153 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2154 expect_payment_sent(&nodes[0], payment_preimage_1, None, false, false);
2156 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2157 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2158 check_added_monitors!(nodes[1], 1);
2159 // B is already AwaitingRAA, so cant generate a CS here
2160 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2162 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2163 check_added_monitors!(nodes[1], 1);
2164 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2166 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2167 check_added_monitors!(nodes[0], 1);
2168 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2170 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2171 check_added_monitors!(nodes[1], 1);
2172 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2174 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2175 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2176 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2177 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2178 // on-chain as necessary).
2179 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2180 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2181 check_added_monitors!(nodes[0], 1);
2182 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2183 expect_payment_sent(&nodes[0], payment_preimage_2, None, false, false);
2185 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2186 check_added_monitors!(nodes[1], 1);
2187 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2189 expect_pending_htlcs_forwardable!(nodes[1]);
2190 expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2192 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2193 // resolve the second HTLC from A's point of view.
2194 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2195 check_added_monitors!(nodes[0], 1);
2196 expect_payment_path_successful!(nodes[0]);
2197 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2199 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2200 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2201 let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2203 nodes[1].node.send_payment_with_route(&route, payment_hash_4,
2204 RecipientOnionFields::secret_only(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2205 check_added_monitors!(nodes[1], 1);
2206 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2207 assert_eq!(events.len(), 1);
2208 SendEvent::from_event(events.remove(0))
2211 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2212 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2213 check_added_monitors!(nodes[0], 1);
2214 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2216 // Now just resolve all the outstanding messages/HTLCs for completeness...
2218 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2219 check_added_monitors!(nodes[1], 1);
2220 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2222 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2223 check_added_monitors!(nodes[1], 1);
2225 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2226 check_added_monitors!(nodes[0], 1);
2227 expect_payment_path_successful!(nodes[0]);
2228 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2230 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2231 check_added_monitors!(nodes[1], 1);
2232 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2234 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2235 check_added_monitors!(nodes[0], 1);
2237 expect_pending_htlcs_forwardable!(nodes[0]);
2238 expect_payment_claimable!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2240 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2241 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2245 fn channel_monitor_network_test() {
2246 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2247 // tests that ChannelMonitor is able to recover from various states.
2248 let chanmon_cfgs = create_chanmon_cfgs(5);
2249 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2250 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2251 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2253 // Create some initial channels
2254 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2255 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2256 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2257 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
2259 // Make sure all nodes are at the same starting height
2260 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2261 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2262 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2263 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2264 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2266 // Rebalance the network a bit by relaying one payment through all the channels...
2267 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2268 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2269 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2270 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2272 // Simple case with no pending HTLCs:
2273 nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2274 check_added_monitors!(nodes[1], 1);
2275 check_closed_broadcast!(nodes[1], true);
2276 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[0].node.get_our_node_id()], 100000);
2278 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2279 assert_eq!(node_txn.len(), 1);
2280 mine_transaction(&nodes[1], &node_txn[0]);
2281 if nodes[1].connect_style.borrow().updates_best_block_first() {
2282 let _ = nodes[1].tx_broadcaster.txn_broadcast();
2285 mine_transaction(&nodes[0], &node_txn[0]);
2286 check_added_monitors!(nodes[0], 1);
2287 test_txn_broadcast(&nodes[0], &chan_1, Some(node_txn[0].clone()), HTLCType::NONE);
2289 check_closed_broadcast!(nodes[0], true);
2290 assert_eq!(nodes[0].node.list_channels().len(), 0);
2291 assert_eq!(nodes[1].node.list_channels().len(), 1);
2292 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2294 // One pending HTLC is discarded by the force-close:
2295 let (payment_preimage_1, payment_hash_1, ..) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2297 // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2298 // broadcasted until we reach the timelock time).
2299 nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2300 check_closed_broadcast!(nodes[1], true);
2301 check_added_monitors!(nodes[1], 1);
2303 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2304 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2305 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2306 mine_transaction(&nodes[2], &node_txn[0]);
2307 check_added_monitors!(nodes[2], 1);
2308 test_txn_broadcast(&nodes[2], &chan_2, Some(node_txn[0].clone()), HTLCType::NONE);
2310 check_closed_broadcast!(nodes[2], true);
2311 assert_eq!(nodes[1].node.list_channels().len(), 0);
2312 assert_eq!(nodes[2].node.list_channels().len(), 1);
2313 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[2].node.get_our_node_id()], 100000);
2314 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2316 macro_rules! claim_funds {
2317 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2319 $node.node.claim_funds($preimage);
2320 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2321 check_added_monitors!($node, 1);
2323 let events = $node.node.get_and_clear_pending_msg_events();
2324 assert_eq!(events.len(), 1);
2326 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2327 assert!(update_add_htlcs.is_empty());
2328 assert!(update_fail_htlcs.is_empty());
2329 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2331 _ => panic!("Unexpected event"),
2337 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2338 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2339 nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2340 check_added_monitors!(nodes[2], 1);
2341 check_closed_broadcast!(nodes[2], true);
2342 let node2_commitment_txid;
2344 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2345 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2346 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2347 node2_commitment_txid = node_txn[0].txid();
2349 // Claim the payment on nodes[3], giving it knowledge of the preimage
2350 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2351 mine_transaction(&nodes[3], &node_txn[0]);
2352 check_added_monitors!(nodes[3], 1);
2353 check_preimage_claim(&nodes[3], &node_txn);
2355 check_closed_broadcast!(nodes[3], true);
2356 assert_eq!(nodes[2].node.list_channels().len(), 0);
2357 assert_eq!(nodes[3].node.list_channels().len(), 1);
2358 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed, [nodes[3].node.get_our_node_id()], 100000);
2359 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
2361 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2362 // confusing us in the following tests.
2363 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2365 // One pending HTLC to time out:
2366 let (payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2367 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2370 let (close_chan_update_1, close_chan_update_2) = {
2371 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2372 let events = nodes[3].node.get_and_clear_pending_msg_events();
2373 assert_eq!(events.len(), 2);
2374 let close_chan_update_1 = match events[0] {
2375 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2378 _ => panic!("Unexpected event"),
2381 MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { .. }, node_id } => {
2382 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2384 _ => panic!("Unexpected event"),
2386 check_added_monitors!(nodes[3], 1);
2388 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2390 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2391 node_txn.retain(|tx| {
2392 if tx.input[0].previous_output.txid == node2_commitment_txid {
2398 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2400 // Claim the payment on nodes[4], giving it knowledge of the preimage
2401 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2403 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2404 let events = nodes[4].node.get_and_clear_pending_msg_events();
2405 assert_eq!(events.len(), 2);
2406 let close_chan_update_2 = match events[0] {
2407 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2410 _ => panic!("Unexpected event"),
2413 MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { .. }, node_id } => {
2414 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2416 _ => panic!("Unexpected event"),
2418 check_added_monitors!(nodes[4], 1);
2419 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2420 check_closed_event!(nodes[4], 1, ClosureReason::HolderForceClosed, [nodes[3].node.get_our_node_id()], 100000);
2422 mine_transaction(&nodes[4], &node_txn[0]);
2423 check_preimage_claim(&nodes[4], &node_txn);
2424 (close_chan_update_1, close_chan_update_2)
2426 nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2427 nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2428 assert_eq!(nodes[3].node.list_channels().len(), 0);
2429 assert_eq!(nodes[4].node.list_channels().len(), 0);
2431 assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2432 Ok(ChannelMonitorUpdateStatus::Completed));
2433 check_closed_event!(nodes[3], 1, ClosureReason::HolderForceClosed, [nodes[4].node.get_our_node_id()], 100000);
2437 fn test_justice_tx_htlc_timeout() {
2438 // Test justice txn built on revoked HTLC-Timeout tx, against both sides
2439 let mut alice_config = UserConfig::default();
2440 alice_config.channel_handshake_config.announced_channel = true;
2441 alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2442 alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2443 let mut bob_config = UserConfig::default();
2444 bob_config.channel_handshake_config.announced_channel = true;
2445 bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2446 bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2447 let user_cfgs = [Some(alice_config), Some(bob_config)];
2448 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2449 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2450 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2451 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2452 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2453 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2454 // Create some new channels:
2455 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
2457 // A pending HTLC which will be revoked:
2458 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2459 // Get the will-be-revoked local txn from nodes[0]
2460 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2461 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2462 assert_eq!(revoked_local_txn[0].input.len(), 1);
2463 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2464 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2465 assert_eq!(revoked_local_txn[1].input.len(), 1);
2466 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2467 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2468 // Revoke the old state
2469 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2472 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2474 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2475 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2476 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2477 check_spends!(node_txn[0], revoked_local_txn[0]);
2478 node_txn.swap_remove(0);
2480 check_added_monitors!(nodes[1], 1);
2481 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2482 test_txn_broadcast(&nodes[1], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2484 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2485 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2486 // Verify broadcast of revoked HTLC-timeout
2487 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2488 check_added_monitors!(nodes[0], 1);
2489 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2490 // Broadcast revoked HTLC-timeout on node 1
2491 mine_transaction(&nodes[1], &node_txn[1]);
2492 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2494 get_announce_close_broadcast_events(&nodes, 0, 1);
2495 assert_eq!(nodes[0].node.list_channels().len(), 0);
2496 assert_eq!(nodes[1].node.list_channels().len(), 0);
2500 fn test_justice_tx_htlc_success() {
2501 // Test justice txn built on revoked HTLC-Success tx, against both sides
2502 let mut alice_config = UserConfig::default();
2503 alice_config.channel_handshake_config.announced_channel = true;
2504 alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2505 alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2506 let mut bob_config = UserConfig::default();
2507 bob_config.channel_handshake_config.announced_channel = true;
2508 bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2509 bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2510 let user_cfgs = [Some(alice_config), Some(bob_config)];
2511 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2512 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2513 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2514 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2515 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2516 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2517 // Create some new channels:
2518 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
2520 // A pending HTLC which will be revoked:
2521 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2522 // Get the will-be-revoked local txn from B
2523 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2524 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2525 assert_eq!(revoked_local_txn[0].input.len(), 1);
2526 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2527 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2528 // Revoke the old state
2529 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2531 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2533 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2534 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2535 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2537 check_spends!(node_txn[0], revoked_local_txn[0]);
2538 node_txn.swap_remove(0);
2540 check_added_monitors!(nodes[0], 1);
2541 test_txn_broadcast(&nodes[0], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2543 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2544 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2545 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2546 check_added_monitors!(nodes[1], 1);
2547 mine_transaction(&nodes[0], &node_txn[1]);
2548 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2549 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2551 get_announce_close_broadcast_events(&nodes, 0, 1);
2552 assert_eq!(nodes[0].node.list_channels().len(), 0);
2553 assert_eq!(nodes[1].node.list_channels().len(), 0);
2557 fn revoked_output_claim() {
2558 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2559 // transaction is broadcast by its counterparty
2560 let chanmon_cfgs = create_chanmon_cfgs(2);
2561 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2562 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2563 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2564 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2565 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2566 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2567 assert_eq!(revoked_local_txn.len(), 1);
2568 // Only output is the full channel value back to nodes[0]:
2569 assert_eq!(revoked_local_txn[0].output.len(), 1);
2570 // Send a payment through, updating everyone's latest commitment txn
2571 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2573 // Inform nodes[1] that nodes[0] broadcast a stale tx
2574 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2575 check_added_monitors!(nodes[1], 1);
2576 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2577 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2578 assert_eq!(node_txn.len(), 1); // ChannelMonitor: justice tx against revoked to_local output
2580 check_spends!(node_txn[0], revoked_local_txn[0]);
2582 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2583 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2584 get_announce_close_broadcast_events(&nodes, 0, 1);
2585 check_added_monitors!(nodes[0], 1);
2586 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2590 fn test_forming_justice_tx_from_monitor_updates() {
2591 do_test_forming_justice_tx_from_monitor_updates(true);
2592 do_test_forming_justice_tx_from_monitor_updates(false);
2595 fn do_test_forming_justice_tx_from_monitor_updates(broadcast_initial_commitment: bool) {
2596 // Simple test to make sure that the justice tx formed in WatchtowerPersister
2597 // is properly formed and can be broadcasted/confirmed successfully in the event
2598 // that a revoked commitment transaction is broadcasted
2599 // (Similar to `revoked_output_claim` test but we get the justice tx + broadcast manually)
2600 let chanmon_cfgs = create_chanmon_cfgs(2);
2601 let destination_script0 = chanmon_cfgs[0].keys_manager.get_destination_script([0; 32]).unwrap();
2602 let destination_script1 = chanmon_cfgs[1].keys_manager.get_destination_script([0; 32]).unwrap();
2603 let persisters = vec![WatchtowerPersister::new(destination_script0),
2604 WatchtowerPersister::new(destination_script1)];
2605 let node_cfgs = create_node_cfgs_with_persisters(2, &chanmon_cfgs, persisters.iter().collect());
2606 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2607 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2608 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
2609 let funding_txo = OutPoint { txid: funding_tx.txid(), index: 0 };
2611 if !broadcast_initial_commitment {
2612 // Send a payment to move the channel forward
2613 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5_000_000);
2616 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output.
2617 // We'll keep this commitment transaction to broadcast once it's revoked.
2618 let revoked_local_txn = get_local_commitment_txn!(nodes[0], channel_id);
2619 assert_eq!(revoked_local_txn.len(), 1);
2620 let revoked_commitment_tx = &revoked_local_txn[0];
2622 // Send another payment, now revoking the previous commitment tx
2623 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5_000_000);
2625 let justice_tx = persisters[1].justice_tx(funding_txo, &revoked_commitment_tx.txid()).unwrap();
2626 check_spends!(justice_tx, revoked_commitment_tx);
2628 mine_transactions(&nodes[1], &[revoked_commitment_tx, &justice_tx]);
2629 mine_transactions(&nodes[0], &[revoked_commitment_tx, &justice_tx]);
2631 check_added_monitors!(nodes[1], 1);
2632 check_closed_event(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false,
2633 &[nodes[0].node.get_our_node_id()], 100_000);
2634 get_announce_close_broadcast_events(&nodes, 1, 0);
2636 check_added_monitors!(nodes[0], 1);
2637 check_closed_event(&nodes[0], 1, ClosureReason::CommitmentTxConfirmed, false,
2638 &[nodes[1].node.get_our_node_id()], 100_000);
2640 // Check that the justice tx has sent the revoked output value to nodes[1]
2641 let monitor = get_monitor!(nodes[1], channel_id);
2642 let total_claimable_balance = monitor.get_claimable_balances().iter().fold(0, |sum, balance| {
2644 channelmonitor::Balance::ClaimableAwaitingConfirmations { amount_satoshis, .. } => sum + amount_satoshis,
2645 _ => panic!("Unexpected balance type"),
2648 // On the first commitment, node[1]'s balance was below dust so it didn't have an output
2649 let node1_channel_balance = if broadcast_initial_commitment { 0 } else { revoked_commitment_tx.output[0].value };
2650 let expected_claimable_balance = node1_channel_balance + justice_tx.output[0].value;
2651 assert_eq!(total_claimable_balance, expected_claimable_balance);
2656 fn claim_htlc_outputs_shared_tx() {
2657 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2658 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2659 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2660 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2661 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2662 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2664 // Create some new channel:
2665 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2667 // Rebalance the network to generate htlc in the two directions
2668 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2669 // 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
2670 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2671 let (_payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2673 // Get the will-be-revoked local txn from node[0]
2674 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2675 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2676 assert_eq!(revoked_local_txn[0].input.len(), 1);
2677 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2678 assert_eq!(revoked_local_txn[1].input.len(), 1);
2679 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2680 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2681 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2683 //Revoke the old state
2684 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2687 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2688 check_added_monitors!(nodes[0], 1);
2689 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2690 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2691 check_added_monitors!(nodes[1], 1);
2692 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2693 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2694 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2696 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2697 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2699 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2700 check_spends!(node_txn[0], revoked_local_txn[0]);
2702 let mut witness_lens = BTreeSet::new();
2703 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2704 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2705 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2706 assert_eq!(witness_lens.len(), 3);
2707 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2708 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2709 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2711 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2712 // ANTI_REORG_DELAY confirmations.
2713 mine_transaction(&nodes[1], &node_txn[0]);
2714 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2715 expect_payment_failed!(nodes[1], payment_hash_2, false);
2717 get_announce_close_broadcast_events(&nodes, 0, 1);
2718 assert_eq!(nodes[0].node.list_channels().len(), 0);
2719 assert_eq!(nodes[1].node.list_channels().len(), 0);
2723 fn claim_htlc_outputs_single_tx() {
2724 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2725 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2726 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2727 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2728 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2729 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2731 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2733 // Rebalance the network to generate htlc in the two directions
2734 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2735 // 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
2736 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2737 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2738 let (_payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2740 // Get the will-be-revoked local txn from node[0]
2741 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2743 //Revoke the old state
2744 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2747 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2748 check_added_monitors!(nodes[0], 1);
2749 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2750 check_added_monitors!(nodes[1], 1);
2751 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2752 let mut events = nodes[0].node.get_and_clear_pending_events();
2753 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2754 match events.last().unwrap() {
2755 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2756 _ => panic!("Unexpected event"),
2759 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2760 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2762 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcast();
2764 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2765 assert_eq!(node_txn[0].input.len(), 1);
2766 check_spends!(node_txn[0], chan_1.3);
2767 assert_eq!(node_txn[1].input.len(), 1);
2768 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2769 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2770 check_spends!(node_txn[1], node_txn[0]);
2772 // Filter out any non justice transactions.
2773 node_txn.retain(|tx| tx.input[0].previous_output.txid == revoked_local_txn[0].txid());
2774 assert!(node_txn.len() > 3);
2776 assert_eq!(node_txn[0].input.len(), 1);
2777 assert_eq!(node_txn[1].input.len(), 1);
2778 assert_eq!(node_txn[2].input.len(), 1);
2780 check_spends!(node_txn[0], revoked_local_txn[0]);
2781 check_spends!(node_txn[1], revoked_local_txn[0]);
2782 check_spends!(node_txn[2], revoked_local_txn[0]);
2784 let mut witness_lens = BTreeSet::new();
2785 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2786 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2787 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2788 assert_eq!(witness_lens.len(), 3);
2789 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2790 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2791 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2793 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2794 // ANTI_REORG_DELAY confirmations.
2795 mine_transaction(&nodes[1], &node_txn[0]);
2796 mine_transaction(&nodes[1], &node_txn[1]);
2797 mine_transaction(&nodes[1], &node_txn[2]);
2798 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2799 expect_payment_failed!(nodes[1], payment_hash_2, false);
2801 get_announce_close_broadcast_events(&nodes, 0, 1);
2802 assert_eq!(nodes[0].node.list_channels().len(), 0);
2803 assert_eq!(nodes[1].node.list_channels().len(), 0);
2807 fn test_htlc_on_chain_success() {
2808 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2809 // the preimage backward accordingly. So here we test that ChannelManager is
2810 // broadcasting the right event to other nodes in payment path.
2811 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2812 // A --------------------> B ----------------------> C (preimage)
2813 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2814 // commitment transaction was broadcast.
2815 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2817 // B should be able to claim via preimage if A then broadcasts its local tx.
2818 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2819 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2820 // PaymentSent event).
2822 let chanmon_cfgs = create_chanmon_cfgs(3);
2823 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2824 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2825 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2827 // Create some initial channels
2828 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2829 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2831 // Ensure all nodes are at the same height
2832 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2833 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2834 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2835 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2837 // Rebalance the network a bit by relaying one payment through all the channels...
2838 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2839 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2841 let (our_payment_preimage, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2842 let (our_payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2844 // Broadcast legit commitment tx from C on B's chain
2845 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2846 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2847 assert_eq!(commitment_tx.len(), 1);
2848 check_spends!(commitment_tx[0], chan_2.3);
2849 nodes[2].node.claim_funds(our_payment_preimage);
2850 expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2851 nodes[2].node.claim_funds(our_payment_preimage_2);
2852 expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2853 check_added_monitors!(nodes[2], 2);
2854 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2855 assert!(updates.update_add_htlcs.is_empty());
2856 assert!(updates.update_fail_htlcs.is_empty());
2857 assert!(updates.update_fail_malformed_htlcs.is_empty());
2858 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2860 mine_transaction(&nodes[2], &commitment_tx[0]);
2861 check_closed_broadcast!(nodes[2], true);
2862 check_added_monitors!(nodes[2], 1);
2863 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2864 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 2 (2 * HTLC-Success tx)
2865 assert_eq!(node_txn.len(), 2);
2866 check_spends!(node_txn[0], commitment_tx[0]);
2867 check_spends!(node_txn[1], commitment_tx[0]);
2868 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2869 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2870 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2871 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2872 assert_eq!(node_txn[0].lock_time, LockTime::ZERO);
2873 assert_eq!(node_txn[1].lock_time, LockTime::ZERO);
2875 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2876 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()]));
2877 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2879 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2880 assert_eq!(added_monitors.len(), 1);
2881 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2882 added_monitors.clear();
2884 let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2885 assert_eq!(forwarded_events.len(), 3);
2886 match forwarded_events[0] {
2887 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2888 _ => panic!("Unexpected event"),
2890 let chan_id = Some(chan_1.2);
2891 match forwarded_events[1] {
2892 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2893 assert_eq!(fee_earned_msat, Some(1000));
2894 assert_eq!(prev_channel_id, chan_id);
2895 assert_eq!(claim_from_onchain_tx, true);
2896 assert_eq!(next_channel_id, Some(chan_2.2));
2897 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2901 match forwarded_events[2] {
2902 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2903 assert_eq!(fee_earned_msat, Some(1000));
2904 assert_eq!(prev_channel_id, chan_id);
2905 assert_eq!(claim_from_onchain_tx, true);
2906 assert_eq!(next_channel_id, Some(chan_2.2));
2907 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2911 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2913 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2914 assert_eq!(added_monitors.len(), 2);
2915 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2916 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2917 added_monitors.clear();
2919 assert_eq!(events.len(), 3);
2921 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
2922 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
2924 match nodes_2_event {
2925 MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { .. }, node_id: _ } => {},
2926 _ => panic!("Unexpected event"),
2929 match nodes_0_event {
2930 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, .. } } => {
2931 assert!(update_add_htlcs.is_empty());
2932 assert!(update_fail_htlcs.is_empty());
2933 assert_eq!(update_fulfill_htlcs.len(), 1);
2934 assert!(update_fail_malformed_htlcs.is_empty());
2935 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2937 _ => panic!("Unexpected event"),
2940 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
2942 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2943 _ => panic!("Unexpected event"),
2946 macro_rules! check_tx_local_broadcast {
2947 ($node: expr, $htlc_offered: expr, $commitment_tx: expr) => { {
2948 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2949 assert_eq!(node_txn.len(), 2);
2950 // Node[1]: 2 * HTLC-timeout tx
2951 // Node[0]: 2 * HTLC-timeout tx
2952 check_spends!(node_txn[0], $commitment_tx);
2953 check_spends!(node_txn[1], $commitment_tx);
2954 assert_ne!(node_txn[0].lock_time, LockTime::ZERO);
2955 assert_ne!(node_txn[1].lock_time, LockTime::ZERO);
2957 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2958 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2959 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2960 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2962 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2963 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2964 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2965 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2970 // nodes[1] now broadcasts its own timeout-claim of the output that nodes[2] just claimed via success.
2971 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0]);
2973 // Broadcast legit commitment tx from A on B's chain
2974 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2975 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2976 check_spends!(node_a_commitment_tx[0], chan_1.3);
2977 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2978 check_closed_broadcast!(nodes[1], true);
2979 check_added_monitors!(nodes[1], 1);
2980 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2981 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2982 assert!(node_txn.len() == 1 || node_txn.len() == 3); // HTLC-Success, 2* RBF bumps of above HTLC txn
2983 let commitment_spend =
2984 if node_txn.len() == 1 {
2987 // Certain `ConnectStyle`s will cause RBF bumps of the previous HTLC transaction to be broadcast.
2988 // FullBlockViaListen
2989 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2990 check_spends!(node_txn[1], commitment_tx[0]);
2991 check_spends!(node_txn[2], commitment_tx[0]);
2992 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2995 check_spends!(node_txn[0], commitment_tx[0]);
2996 check_spends!(node_txn[1], commitment_tx[0]);
2997 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
3002 check_spends!(commitment_spend, node_a_commitment_tx[0]);
3003 assert_eq!(commitment_spend.input.len(), 2);
3004 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3005 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3006 assert_eq!(commitment_spend.lock_time.to_consensus_u32(), nodes[1].best_block_info().1);
3007 assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
3008 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
3009 // we already checked the same situation with A.
3011 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
3012 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()]));
3013 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
3014 check_closed_broadcast!(nodes[0], true);
3015 check_added_monitors!(nodes[0], 1);
3016 let events = nodes[0].node.get_and_clear_pending_events();
3017 assert_eq!(events.len(), 5);
3018 let mut first_claimed = false;
3019 for event in events {
3021 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3022 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
3023 assert!(!first_claimed);
3024 first_claimed = true;
3026 assert_eq!(payment_preimage, our_payment_preimage_2);
3027 assert_eq!(payment_hash, payment_hash_2);
3030 Event::PaymentPathSuccessful { .. } => {},
3031 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
3032 _ => panic!("Unexpected event"),
3035 check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0]);
3038 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
3039 // Test that in case of a unilateral close onchain, we detect the state of output and
3040 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
3041 // broadcasting the right event to other nodes in payment path.
3042 // A ------------------> B ----------------------> C (timeout)
3043 // B's commitment tx C's commitment tx
3045 // B's HTLC timeout tx B's timeout tx
3047 let chanmon_cfgs = create_chanmon_cfgs(3);
3048 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3049 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3050 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3051 *nodes[0].connect_style.borrow_mut() = connect_style;
3052 *nodes[1].connect_style.borrow_mut() = connect_style;
3053 *nodes[2].connect_style.borrow_mut() = connect_style;
3055 // Create some intial channels
3056 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
3057 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3059 // Rebalance the network a bit by relaying one payment thorugh all the channels...
3060 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
3061 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
3063 let (_payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
3065 // Broadcast legit commitment tx from C on B's chain
3066 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
3067 check_spends!(commitment_tx[0], chan_2.3);
3068 nodes[2].node.fail_htlc_backwards(&payment_hash);
3069 check_added_monitors!(nodes[2], 0);
3070 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
3071 check_added_monitors!(nodes[2], 1);
3073 let events = nodes[2].node.get_and_clear_pending_msg_events();
3074 assert_eq!(events.len(), 1);
3076 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, .. } } => {
3077 assert!(update_add_htlcs.is_empty());
3078 assert!(!update_fail_htlcs.is_empty());
3079 assert!(update_fulfill_htlcs.is_empty());
3080 assert!(update_fail_malformed_htlcs.is_empty());
3081 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
3083 _ => panic!("Unexpected event"),
3085 mine_transaction(&nodes[2], &commitment_tx[0]);
3086 check_closed_broadcast!(nodes[2], true);
3087 check_added_monitors!(nodes[2], 1);
3088 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
3089 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
3090 assert_eq!(node_txn.len(), 0);
3092 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
3093 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
3094 mine_transaction(&nodes[1], &commitment_tx[0]);
3095 check_closed_event!(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false
3096 , [nodes[2].node.get_our_node_id()], 100000);
3097 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
3099 let mut txn = nodes[1].tx_broadcaster.txn_broadcast();
3100 if nodes[1].connect_style.borrow().skips_blocks() {
3101 assert_eq!(txn.len(), 1);
3103 assert_eq!(txn.len(), 3); // Two extra fee bumps for timeout transaction
3105 txn.iter().for_each(|tx| check_spends!(tx, commitment_tx[0]));
3106 assert_eq!(txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3110 mine_transaction(&nodes[1], &timeout_tx);
3111 check_added_monitors!(nodes[1], 1);
3112 check_closed_broadcast!(nodes[1], true);
3114 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3116 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 }]);
3117 check_added_monitors!(nodes[1], 1);
3118 let events = nodes[1].node.get_and_clear_pending_msg_events();
3119 assert_eq!(events.len(), 1);
3121 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, .. } } => {
3122 assert!(update_add_htlcs.is_empty());
3123 assert!(!update_fail_htlcs.is_empty());
3124 assert!(update_fulfill_htlcs.is_empty());
3125 assert!(update_fail_malformed_htlcs.is_empty());
3126 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3128 _ => panic!("Unexpected event"),
3131 // Broadcast legit commitment tx from B on A's chain
3132 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3133 check_spends!(commitment_tx[0], chan_1.3);
3135 mine_transaction(&nodes[0], &commitment_tx[0]);
3136 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
3138 check_closed_broadcast!(nodes[0], true);
3139 check_added_monitors!(nodes[0], 1);
3140 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
3141 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // 1 timeout tx
3142 assert_eq!(node_txn.len(), 1);
3143 check_spends!(node_txn[0], commitment_tx[0]);
3144 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3148 fn test_htlc_on_chain_timeout() {
3149 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3150 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3151 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3155 fn test_simple_commitment_revoked_fail_backward() {
3156 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3157 // and fail backward accordingly.
3159 let chanmon_cfgs = create_chanmon_cfgs(3);
3160 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3161 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3162 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3164 // Create some initial channels
3165 create_announced_chan_between_nodes(&nodes, 0, 1);
3166 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3168 let (payment_preimage, _payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3169 // Get the will-be-revoked local txn from nodes[2]
3170 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3171 // Revoke the old state
3172 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3174 let (_, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3176 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3177 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
3178 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3179 check_added_monitors!(nodes[1], 1);
3180 check_closed_broadcast!(nodes[1], true);
3182 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 }]);
3183 check_added_monitors!(nodes[1], 1);
3184 let events = nodes[1].node.get_and_clear_pending_msg_events();
3185 assert_eq!(events.len(), 1);
3187 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, .. } } => {
3188 assert!(update_add_htlcs.is_empty());
3189 assert_eq!(update_fail_htlcs.len(), 1);
3190 assert!(update_fulfill_htlcs.is_empty());
3191 assert!(update_fail_malformed_htlcs.is_empty());
3192 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3194 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3195 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3196 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3198 _ => panic!("Unexpected event"),
3202 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3203 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3204 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3205 // commitment transaction anymore.
3206 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3207 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3208 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3209 // technically disallowed and we should probably handle it reasonably.
3210 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3211 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3213 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3214 // commitment_signed (implying it will be in the latest remote commitment transaction).
3215 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3216 // and once they revoke the previous commitment transaction (allowing us to send a new
3217 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3218 let chanmon_cfgs = create_chanmon_cfgs(3);
3219 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3220 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3221 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3223 // Create some initial channels
3224 create_announced_chan_between_nodes(&nodes, 0, 1);
3225 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3227 let (payment_preimage, _payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3228 // Get the will-be-revoked local txn from nodes[2]
3229 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3230 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3231 // Revoke the old state
3232 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3234 let value = if use_dust {
3235 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3236 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3237 nodes[2].node.per_peer_state.read().unwrap().get(&nodes[1].node.get_our_node_id())
3238 .unwrap().lock().unwrap().channel_by_id.get(&chan_2.2).unwrap().context().holder_dust_limit_satoshis * 1000
3241 let (_, first_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3242 let (_, second_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3243 let (_, third_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3245 nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3246 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3247 check_added_monitors!(nodes[2], 1);
3248 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3249 assert!(updates.update_add_htlcs.is_empty());
3250 assert!(updates.update_fulfill_htlcs.is_empty());
3251 assert!(updates.update_fail_malformed_htlcs.is_empty());
3252 assert_eq!(updates.update_fail_htlcs.len(), 1);
3253 assert!(updates.update_fee.is_none());
3254 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3255 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3256 // Drop the last RAA from 3 -> 2
3258 nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3259 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3260 check_added_monitors!(nodes[2], 1);
3261 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3262 assert!(updates.update_add_htlcs.is_empty());
3263 assert!(updates.update_fulfill_htlcs.is_empty());
3264 assert!(updates.update_fail_malformed_htlcs.is_empty());
3265 assert_eq!(updates.update_fail_htlcs.len(), 1);
3266 assert!(updates.update_fee.is_none());
3267 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3268 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3269 check_added_monitors!(nodes[1], 1);
3270 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3271 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3272 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3273 check_added_monitors!(nodes[2], 1);
3275 nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3276 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3277 check_added_monitors!(nodes[2], 1);
3278 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3279 assert!(updates.update_add_htlcs.is_empty());
3280 assert!(updates.update_fulfill_htlcs.is_empty());
3281 assert!(updates.update_fail_malformed_htlcs.is_empty());
3282 assert_eq!(updates.update_fail_htlcs.len(), 1);
3283 assert!(updates.update_fee.is_none());
3284 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3285 // At this point first_payment_hash has dropped out of the latest two commitment
3286 // transactions that nodes[1] is tracking...
3287 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3288 check_added_monitors!(nodes[1], 1);
3289 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3290 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3291 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3292 check_added_monitors!(nodes[2], 1);
3294 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3295 // on nodes[2]'s RAA.
3296 let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3297 nodes[1].node.send_payment_with_route(&route, fourth_payment_hash,
3298 RecipientOnionFields::secret_only(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3299 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3300 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3301 check_added_monitors!(nodes[1], 0);
3304 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3305 // One monitor for the new revocation preimage, no second on as we won't generate a new
3306 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3307 check_added_monitors!(nodes[1], 1);
3308 let events = nodes[1].node.get_and_clear_pending_events();
3309 assert_eq!(events.len(), 2);
3311 Event::PendingHTLCsForwardable { .. } => { },
3312 _ => panic!("Unexpected event"),
3315 Event::HTLCHandlingFailed { .. } => { },
3316 _ => panic!("Unexpected event"),
3318 // Deliberately don't process the pending fail-back so they all fail back at once after
3319 // block connection just like the !deliver_bs_raa case
3322 let mut failed_htlcs = HashSet::new();
3323 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3325 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3326 check_added_monitors!(nodes[1], 1);
3327 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3329 let events = nodes[1].node.get_and_clear_pending_events();
3330 assert_eq!(events.len(), if deliver_bs_raa { 3 + nodes.len() - 1 } else { 4 + nodes.len() });
3331 assert!(events.iter().any(|ev| matches!(
3333 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. }
3335 assert!(events.iter().any(|ev| matches!(
3337 Event::PaymentPathFailed { ref payment_hash, .. } if *payment_hash == fourth_payment_hash
3339 assert!(events.iter().any(|ev| matches!(
3341 Event::PaymentFailed { ref payment_hash, .. } if *payment_hash == fourth_payment_hash
3344 nodes[1].node.process_pending_htlc_forwards();
3345 check_added_monitors!(nodes[1], 1);
3347 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
3348 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3351 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3352 match nodes_2_event {
3353 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, .. } } => {
3354 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3355 assert_eq!(update_add_htlcs.len(), 1);
3356 assert!(update_fulfill_htlcs.is_empty());
3357 assert!(update_fail_htlcs.is_empty());
3358 assert!(update_fail_malformed_htlcs.is_empty());
3360 _ => panic!("Unexpected event"),
3364 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3365 match nodes_2_event {
3366 MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { msg: Some(msgs::ErrorMessage { channel_id, ref data }) }, node_id: _ } => {
3367 assert_eq!(channel_id, chan_2.2);
3368 assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3370 _ => panic!("Unexpected event"),
3373 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
3374 match nodes_0_event {
3375 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, .. } } => {
3376 assert!(update_add_htlcs.is_empty());
3377 assert_eq!(update_fail_htlcs.len(), 3);
3378 assert!(update_fulfill_htlcs.is_empty());
3379 assert!(update_fail_malformed_htlcs.is_empty());
3380 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3382 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3383 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3384 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3386 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3388 let events = nodes[0].node.get_and_clear_pending_events();
3389 assert_eq!(events.len(), 6);
3391 Event::PaymentPathFailed { ref payment_hash, ref failure, .. } => {
3392 assert!(failed_htlcs.insert(payment_hash.0));
3393 // If we delivered B's RAA we got an unknown preimage error, not something
3394 // that we should update our routing table for.
3395 if !deliver_bs_raa {
3396 if let PathFailure::OnPath { network_update: Some(_) } = failure { } else { panic!("Unexpected path failure") }
3399 _ => panic!("Unexpected event"),
3402 Event::PaymentFailed { ref payment_hash, .. } => {
3403 assert_eq!(*payment_hash, first_payment_hash);
3405 _ => panic!("Unexpected event"),
3408 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3409 assert!(failed_htlcs.insert(payment_hash.0));
3411 _ => panic!("Unexpected event"),
3414 Event::PaymentFailed { ref payment_hash, .. } => {
3415 assert_eq!(*payment_hash, second_payment_hash);
3417 _ => panic!("Unexpected event"),
3420 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3421 assert!(failed_htlcs.insert(payment_hash.0));
3423 _ => panic!("Unexpected event"),
3426 Event::PaymentFailed { ref payment_hash, .. } => {
3427 assert_eq!(*payment_hash, third_payment_hash);
3429 _ => panic!("Unexpected event"),
3432 _ => panic!("Unexpected event"),
3435 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
3437 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3438 _ => panic!("Unexpected event"),
3441 assert!(failed_htlcs.contains(&first_payment_hash.0));
3442 assert!(failed_htlcs.contains(&second_payment_hash.0));
3443 assert!(failed_htlcs.contains(&third_payment_hash.0));
3447 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3448 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3449 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3450 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3451 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3455 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3456 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3457 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3458 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3459 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3463 fn fail_backward_pending_htlc_upon_channel_failure() {
3464 let chanmon_cfgs = create_chanmon_cfgs(2);
3465 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3466 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3467 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3468 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
3470 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3472 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3473 nodes[0].node.send_payment_with_route(&route, payment_hash, RecipientOnionFields::secret_only(payment_secret),
3474 PaymentId(payment_hash.0)).unwrap();
3475 check_added_monitors!(nodes[0], 1);
3477 let payment_event = {
3478 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3479 assert_eq!(events.len(), 1);
3480 SendEvent::from_event(events.remove(0))
3482 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3483 assert_eq!(payment_event.msgs.len(), 1);
3486 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3487 let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3489 nodes[0].node.send_payment_with_route(&route, failed_payment_hash,
3490 RecipientOnionFields::secret_only(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3491 check_added_monitors!(nodes[0], 0);
3493 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3496 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3498 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3500 let secp_ctx = Secp256k1::new();
3501 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3502 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3503 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(
3504 &route.paths[0], 50_000, RecipientOnionFields::secret_only(payment_secret), current_height, &None).unwrap();
3505 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3506 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
3508 // Send a 0-msat update_add_htlc to fail the channel.
3509 let update_add_htlc = msgs::UpdateAddHTLC {
3515 onion_routing_packet,
3516 skimmed_fee_msat: None,
3517 blinding_point: None,
3519 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3521 let events = nodes[0].node.get_and_clear_pending_events();
3522 assert_eq!(events.len(), 3);
3523 // Check that Alice fails backward the pending HTLC from the second payment.
3525 Event::PaymentPathFailed { payment_hash, .. } => {
3526 assert_eq!(payment_hash, failed_payment_hash);
3528 _ => panic!("Unexpected event"),
3531 Event::PaymentFailed { payment_hash, .. } => {
3532 assert_eq!(payment_hash, failed_payment_hash);
3534 _ => panic!("Unexpected event"),
3537 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3538 assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3540 _ => panic!("Unexpected event {:?}", events[1]),
3542 check_closed_broadcast!(nodes[0], true);
3543 check_added_monitors!(nodes[0], 1);
3547 fn test_htlc_ignore_latest_remote_commitment() {
3548 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3549 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3550 let chanmon_cfgs = create_chanmon_cfgs(2);
3551 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3552 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3553 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3554 if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3555 // We rely on the ability to connect a block redundantly, which isn't allowed via
3556 // `chain::Listen`, so we never run the test if we randomly get assigned that
3560 let funding_tx = create_announced_chan_between_nodes(&nodes, 0, 1).3;
3562 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3563 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3564 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3565 check_closed_broadcast!(nodes[0], true);
3566 check_added_monitors!(nodes[0], 1);
3567 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
3569 let node_txn = nodes[0].tx_broadcaster.unique_txn_broadcast();
3570 assert_eq!(node_txn.len(), 2);
3571 check_spends!(node_txn[0], funding_tx);
3572 check_spends!(node_txn[1], node_txn[0]);
3574 let block = create_dummy_block(nodes[1].best_block_hash(), 42, vec![node_txn[0].clone()]);
3575 connect_block(&nodes[1], &block);
3576 check_closed_broadcast!(nodes[1], true);
3577 check_added_monitors!(nodes[1], 1);
3578 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
3580 // Duplicate the connect_block call since this may happen due to other listeners
3581 // registering new transactions
3582 connect_block(&nodes[1], &block);
3586 fn test_force_close_fail_back() {
3587 // Check which HTLCs are failed-backwards on channel force-closure
3588 let chanmon_cfgs = create_chanmon_cfgs(3);
3589 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3590 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3591 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3592 create_announced_chan_between_nodes(&nodes, 0, 1);
3593 create_announced_chan_between_nodes(&nodes, 1, 2);
3595 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3597 let mut payment_event = {
3598 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
3599 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3600 check_added_monitors!(nodes[0], 1);
3602 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3603 assert_eq!(events.len(), 1);
3604 SendEvent::from_event(events.remove(0))
3607 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3608 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3610 expect_pending_htlcs_forwardable!(nodes[1]);
3612 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3613 assert_eq!(events_2.len(), 1);
3614 payment_event = SendEvent::from_event(events_2.remove(0));
3615 assert_eq!(payment_event.msgs.len(), 1);
3617 check_added_monitors!(nodes[1], 1);
3618 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3619 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3620 check_added_monitors!(nodes[2], 1);
3621 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3623 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3624 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3625 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3627 nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3628 check_closed_broadcast!(nodes[2], true);
3629 check_added_monitors!(nodes[2], 1);
3630 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
3631 let commitment_tx = {
3632 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3633 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3634 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3635 // back to nodes[1] upon timeout otherwise.
3636 assert_eq!(node_txn.len(), 1);
3640 mine_transaction(&nodes[1], &commitment_tx);
3642 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3643 check_closed_broadcast!(nodes[1], true);
3644 check_added_monitors!(nodes[1], 1);
3645 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
3647 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3649 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3650 .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);
3652 mine_transaction(&nodes[2], &commitment_tx);
3653 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcast();
3654 assert_eq!(node_txn.len(), if nodes[2].connect_style.borrow().updates_best_block_first() { 2 } else { 1 });
3655 let htlc_tx = node_txn.pop().unwrap();
3656 assert_eq!(htlc_tx.input.len(), 1);
3657 assert_eq!(htlc_tx.input[0].previous_output.txid, commitment_tx.txid());
3658 assert_eq!(htlc_tx.lock_time, LockTime::ZERO); // Must be an HTLC-Success
3659 assert_eq!(htlc_tx.input[0].witness.len(), 5); // Must be an HTLC-Success
3661 check_spends!(htlc_tx, commitment_tx);
3665 fn test_dup_events_on_peer_disconnect() {
3666 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3667 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3668 // as we used to generate the event immediately upon receipt of the payment preimage in the
3669 // update_fulfill_htlc message.
3671 let chanmon_cfgs = create_chanmon_cfgs(2);
3672 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3673 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3674 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3675 create_announced_chan_between_nodes(&nodes, 0, 1);
3677 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3679 nodes[1].node.claim_funds(payment_preimage);
3680 expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3681 check_added_monitors!(nodes[1], 1);
3682 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3683 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3684 expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
3686 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3687 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3689 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3690 reconnect_args.pending_htlc_claims.0 = 1;
3691 reconnect_nodes(reconnect_args);
3692 expect_payment_path_successful!(nodes[0]);
3696 fn test_peer_disconnected_before_funding_broadcasted() {
3697 // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3698 // before the funding transaction has been broadcasted, and doesn't reconnect back within time.
3699 let chanmon_cfgs = create_chanmon_cfgs(2);
3700 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3701 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3702 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3704 // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3705 // broadcasted, even though it's created by `nodes[0]`.
3706 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, None).unwrap();
3707 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3708 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
3709 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3710 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
3712 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3713 assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3715 assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3717 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3718 assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3720 // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3721 // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3724 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3727 // The peers disconnect before the funding is broadcasted.
3728 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3729 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3731 // The time for peers to reconnect expires.
3732 for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS {
3733 nodes[0].node.timer_tick_occurred();
3736 // Ensure that the channel is closed with `ClosureReason::HolderForceClosed`
3737 // when the peers are disconnected and do not reconnect before the funding
3738 // transaction is broadcasted.
3739 check_closed_event!(&nodes[0], 2, ClosureReason::HolderForceClosed, true
3740 , [nodes[1].node.get_our_node_id()], 1000000);
3741 check_closed_event!(&nodes[1], 1, ClosureReason::DisconnectedPeer, false
3742 , [nodes[0].node.get_our_node_id()], 1000000);
3746 fn test_simple_peer_disconnect() {
3747 // Test that we can reconnect when there are no lost messages
3748 let chanmon_cfgs = create_chanmon_cfgs(3);
3749 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3750 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3751 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3752 create_announced_chan_between_nodes(&nodes, 0, 1);
3753 create_announced_chan_between_nodes(&nodes, 1, 2);
3755 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3756 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3757 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3758 reconnect_args.send_channel_ready = (true, true);
3759 reconnect_nodes(reconnect_args);
3761 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3762 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3763 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3764 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3766 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3767 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3768 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3770 let (payment_preimage_3, payment_hash_3, ..) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3771 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3772 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3773 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3775 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3776 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3778 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3779 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3781 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3782 reconnect_args.pending_cell_htlc_fails.0 = 1;
3783 reconnect_args.pending_cell_htlc_claims.0 = 1;
3784 reconnect_nodes(reconnect_args);
3786 let events = nodes[0].node.get_and_clear_pending_events();
3787 assert_eq!(events.len(), 4);
3789 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3790 assert_eq!(payment_preimage, payment_preimage_3);
3791 assert_eq!(payment_hash, payment_hash_3);
3793 _ => panic!("Unexpected event"),
3796 Event::PaymentPathSuccessful { .. } => {},
3797 _ => panic!("Unexpected event"),
3800 Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3801 assert_eq!(payment_hash, payment_hash_5);
3802 assert!(payment_failed_permanently);
3804 _ => panic!("Unexpected event"),
3807 Event::PaymentFailed { payment_hash, .. } => {
3808 assert_eq!(payment_hash, payment_hash_5);
3810 _ => panic!("Unexpected event"),
3813 check_added_monitors(&nodes[0], 1);
3815 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3816 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3819 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3820 // Test that we can reconnect when in-flight HTLC updates get dropped
3821 let chanmon_cfgs = create_chanmon_cfgs(2);
3822 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3823 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3824 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3826 let mut as_channel_ready = None;
3827 let channel_id = if messages_delivered == 0 {
3828 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3829 as_channel_ready = Some(channel_ready);
3830 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3831 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3832 // it before the channel_reestablish message.
3835 create_announced_chan_between_nodes(&nodes, 0, 1).2
3838 let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3840 let payment_event = {
3841 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
3842 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3843 check_added_monitors!(nodes[0], 1);
3845 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3846 assert_eq!(events.len(), 1);
3847 SendEvent::from_event(events.remove(0))
3849 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3851 if messages_delivered < 2 {
3852 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3854 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3855 if messages_delivered >= 3 {
3856 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3857 check_added_monitors!(nodes[1], 1);
3858 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3860 if messages_delivered >= 4 {
3861 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3862 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3863 check_added_monitors!(nodes[0], 1);
3865 if messages_delivered >= 5 {
3866 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3867 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3868 // No commitment_signed so get_event_msg's assert(len == 1) passes
3869 check_added_monitors!(nodes[0], 1);
3871 if messages_delivered >= 6 {
3872 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3873 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3874 check_added_monitors!(nodes[1], 1);
3881 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3882 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3883 if messages_delivered < 3 {
3884 if simulate_broken_lnd {
3885 // lnd has a long-standing bug where they send a channel_ready prior to a
3886 // channel_reestablish if you reconnect prior to channel_ready time.
3888 // Here we simulate that behavior, delivering a channel_ready immediately on
3889 // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3890 // in `reconnect_nodes` but we currently don't fail based on that.
3892 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3893 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3895 // Even if the channel_ready messages get exchanged, as long as nothing further was
3896 // received on either side, both sides will need to resend them.
3897 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3898 reconnect_args.send_channel_ready = (true, true);
3899 reconnect_args.pending_htlc_adds.1 = 1;
3900 reconnect_nodes(reconnect_args);
3901 } else if messages_delivered == 3 {
3902 // nodes[0] still wants its RAA + commitment_signed
3903 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3904 reconnect_args.pending_responding_commitment_signed.0 = true;
3905 reconnect_args.pending_raa.0 = true;
3906 reconnect_nodes(reconnect_args);
3907 } else if messages_delivered == 4 {
3908 // nodes[0] still wants its commitment_signed
3909 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3910 reconnect_args.pending_responding_commitment_signed.0 = true;
3911 reconnect_nodes(reconnect_args);
3912 } else if messages_delivered == 5 {
3913 // nodes[1] still wants its final RAA
3914 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3915 reconnect_args.pending_raa.1 = true;
3916 reconnect_nodes(reconnect_args);
3917 } else if messages_delivered == 6 {
3918 // Everything was delivered...
3919 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3922 let events_1 = nodes[1].node.get_and_clear_pending_events();
3923 if messages_delivered == 0 {
3924 assert_eq!(events_1.len(), 2);
3926 Event::ChannelReady { .. } => { },
3927 _ => panic!("Unexpected event"),
3930 Event::PendingHTLCsForwardable { .. } => { },
3931 _ => panic!("Unexpected event"),
3934 assert_eq!(events_1.len(), 1);
3936 Event::PendingHTLCsForwardable { .. } => { },
3937 _ => panic!("Unexpected event"),
3941 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3942 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3943 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3945 nodes[1].node.process_pending_htlc_forwards();
3947 let events_2 = nodes[1].node.get_and_clear_pending_events();
3948 assert_eq!(events_2.len(), 1);
3950 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
3951 assert_eq!(payment_hash_1, *payment_hash);
3952 assert_eq!(amount_msat, 1_000_000);
3953 assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3954 assert_eq!(via_channel_id, Some(channel_id));
3956 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3957 assert!(payment_preimage.is_none());
3958 assert_eq!(payment_secret_1, *payment_secret);
3960 _ => panic!("expected PaymentPurpose::InvoicePayment")
3963 _ => panic!("Unexpected event"),
3966 nodes[1].node.claim_funds(payment_preimage_1);
3967 check_added_monitors!(nodes[1], 1);
3968 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3970 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3971 assert_eq!(events_3.len(), 1);
3972 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3973 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3974 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3975 assert!(updates.update_add_htlcs.is_empty());
3976 assert!(updates.update_fail_htlcs.is_empty());
3977 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3978 assert!(updates.update_fail_malformed_htlcs.is_empty());
3979 assert!(updates.update_fee.is_none());
3980 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3982 _ => panic!("Unexpected event"),
3985 if messages_delivered >= 1 {
3986 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3988 let events_4 = nodes[0].node.get_and_clear_pending_events();
3989 assert_eq!(events_4.len(), 1);
3991 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3992 assert_eq!(payment_preimage_1, *payment_preimage);
3993 assert_eq!(payment_hash_1, *payment_hash);
3995 _ => panic!("Unexpected event"),
3998 if messages_delivered >= 2 {
3999 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
4000 check_added_monitors!(nodes[0], 1);
4001 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4003 if messages_delivered >= 3 {
4004 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4005 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4006 check_added_monitors!(nodes[1], 1);
4008 if messages_delivered >= 4 {
4009 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
4010 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4011 // No commitment_signed so get_event_msg's assert(len == 1) passes
4012 check_added_monitors!(nodes[1], 1);
4014 if messages_delivered >= 5 {
4015 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4016 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4017 check_added_monitors!(nodes[0], 1);
4024 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4025 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4026 if messages_delivered < 2 {
4027 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4028 reconnect_args.pending_htlc_claims.0 = 1;
4029 reconnect_nodes(reconnect_args);
4030 if messages_delivered < 1 {
4031 expect_payment_sent!(nodes[0], payment_preimage_1);
4033 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4035 } else if messages_delivered == 2 {
4036 // nodes[0] still wants its RAA + commitment_signed
4037 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4038 reconnect_args.pending_responding_commitment_signed.1 = true;
4039 reconnect_args.pending_raa.1 = true;
4040 reconnect_nodes(reconnect_args);
4041 } else if messages_delivered == 3 {
4042 // nodes[0] still wants its commitment_signed
4043 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4044 reconnect_args.pending_responding_commitment_signed.1 = true;
4045 reconnect_nodes(reconnect_args);
4046 } else if messages_delivered == 4 {
4047 // nodes[1] still wants its final RAA
4048 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4049 reconnect_args.pending_raa.0 = true;
4050 reconnect_nodes(reconnect_args);
4051 } else if messages_delivered == 5 {
4052 // Everything was delivered...
4053 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
4056 if messages_delivered == 1 || messages_delivered == 2 {
4057 expect_payment_path_successful!(nodes[0]);
4059 if messages_delivered <= 5 {
4060 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4061 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4063 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
4065 if messages_delivered > 2 {
4066 expect_payment_path_successful!(nodes[0]);
4069 // Channel should still work fine...
4070 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4071 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
4072 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4076 fn test_drop_messages_peer_disconnect_a() {
4077 do_test_drop_messages_peer_disconnect(0, true);
4078 do_test_drop_messages_peer_disconnect(0, false);
4079 do_test_drop_messages_peer_disconnect(1, false);
4080 do_test_drop_messages_peer_disconnect(2, false);
4084 fn test_drop_messages_peer_disconnect_b() {
4085 do_test_drop_messages_peer_disconnect(3, false);
4086 do_test_drop_messages_peer_disconnect(4, false);
4087 do_test_drop_messages_peer_disconnect(5, false);
4088 do_test_drop_messages_peer_disconnect(6, false);
4092 fn test_channel_ready_without_best_block_updated() {
4093 // Previously, if we were offline when a funding transaction was locked in, and then we came
4094 // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
4095 // generate a channel_ready until a later best_block_updated. This tests that we generate the
4096 // channel_ready immediately instead.
4097 let chanmon_cfgs = create_chanmon_cfgs(2);
4098 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4099 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4100 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4101 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
4103 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
4105 let conf_height = nodes[0].best_block_info().1 + 1;
4106 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4107 let block_txn = [funding_tx];
4108 let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
4109 let conf_block_header = nodes[0].get_block_header(conf_height);
4110 nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
4112 // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4113 let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4114 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4118 fn test_channel_monitor_skipping_block_when_channel_manager_is_leading() {
4119 let chanmon_cfgs = create_chanmon_cfgs(2);
4120 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4121 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4122 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4124 // Let channel_manager get ahead of chain_monitor by 1 block.
4125 // This is to emulate race-condition where newly added channel_monitor skips processing 1 block,
4126 // in case where client calls block_connect on channel_manager first and then on chain_monitor.
4127 let height_1 = nodes[0].best_block_info().1 + 1;
4128 let mut block_1 = create_dummy_block(nodes[0].best_block_hash(), height_1, Vec::new());
4130 nodes[0].blocks.lock().unwrap().push((block_1.clone(), height_1));
4131 nodes[0].node.block_connected(&block_1, height_1);
4133 // Create channel, and it gets added to chain_monitor in funding_created.
4134 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
4136 // Now, newly added channel_monitor in chain_monitor hasn't processed block_1,
4137 // but it's best_block is block_1, since that was populated by channel_manager, and channel_manager
4138 // was running ahead of chain_monitor at the time of funding_created.
4139 // Later on, subsequent blocks are connected to both channel_manager and chain_monitor.
4140 // Hence, this channel's channel_monitor skipped block_1, directly tries to process subsequent blocks.
4141 confirm_transaction_at(&nodes[0], &funding_tx, nodes[0].best_block_info().1 + 1);
4142 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4144 // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4145 let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4146 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4150 fn test_channel_monitor_skipping_block_when_channel_manager_is_lagging() {
4151 let chanmon_cfgs = create_chanmon_cfgs(2);
4152 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4153 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4154 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4156 // Let chain_monitor get ahead of channel_manager by 1 block.
4157 // This is to emulate race-condition where newly added channel_monitor skips processing 1 block,
4158 // in case where client calls block_connect on chain_monitor first and then on channel_manager.
4159 let height_1 = nodes[0].best_block_info().1 + 1;
4160 let mut block_1 = create_dummy_block(nodes[0].best_block_hash(), height_1, Vec::new());
4162 nodes[0].blocks.lock().unwrap().push((block_1.clone(), height_1));
4163 nodes[0].chain_monitor.chain_monitor.block_connected(&block_1, height_1);
4165 // Create channel, and it gets added to chain_monitor in funding_created.
4166 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
4168 // channel_manager can't really skip block_1, it should get it eventually.
4169 nodes[0].node.block_connected(&block_1, height_1);
4171 // Now, newly added channel_monitor in chain_monitor hasn't processed block_1, it's best_block is
4172 // the block before block_1, since that was populated by channel_manager, and channel_manager was
4173 // running behind at the time of funding_created.
4174 // Later on, subsequent blocks are connected to both channel_manager and chain_monitor.
4175 // Hence, this channel's channel_monitor skipped block_1, directly tries to process subsequent blocks.
4176 confirm_transaction_at(&nodes[0], &funding_tx, nodes[0].best_block_info().1 + 1);
4177 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4179 // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4180 let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4181 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4185 fn test_drop_messages_peer_disconnect_dual_htlc() {
4186 // Test that we can handle reconnecting when both sides of a channel have pending
4187 // commitment_updates when we disconnect.
4188 let chanmon_cfgs = create_chanmon_cfgs(2);
4189 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4190 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4191 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4192 create_announced_chan_between_nodes(&nodes, 0, 1);
4194 let (payment_preimage_1, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
4196 // Now try to send a second payment which will fail to send
4197 let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4198 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
4199 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
4200 check_added_monitors!(nodes[0], 1);
4202 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4203 assert_eq!(events_1.len(), 1);
4205 MessageSendEvent::UpdateHTLCs { .. } => {},
4206 _ => panic!("Unexpected event"),
4209 nodes[1].node.claim_funds(payment_preimage_1);
4210 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4211 check_added_monitors!(nodes[1], 1);
4213 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4214 assert_eq!(events_2.len(), 1);
4216 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 } } => {
4217 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4218 assert!(update_add_htlcs.is_empty());
4219 assert_eq!(update_fulfill_htlcs.len(), 1);
4220 assert!(update_fail_htlcs.is_empty());
4221 assert!(update_fail_malformed_htlcs.is_empty());
4222 assert!(update_fee.is_none());
4224 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4225 let events_3 = nodes[0].node.get_and_clear_pending_events();
4226 assert_eq!(events_3.len(), 1);
4228 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4229 assert_eq!(*payment_preimage, payment_preimage_1);
4230 assert_eq!(*payment_hash, payment_hash_1);
4232 _ => panic!("Unexpected event"),
4235 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4236 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4237 // No commitment_signed so get_event_msg's assert(len == 1) passes
4238 check_added_monitors!(nodes[0], 1);
4240 _ => panic!("Unexpected event"),
4243 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4244 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4246 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
4247 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
4249 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4250 assert_eq!(reestablish_1.len(), 1);
4251 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
4252 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
4254 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4255 assert_eq!(reestablish_2.len(), 1);
4257 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4258 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4259 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4260 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4262 assert!(as_resp.0.is_none());
4263 assert!(bs_resp.0.is_none());
4265 assert!(bs_resp.1.is_none());
4266 assert!(bs_resp.2.is_none());
4268 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4270 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4271 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4272 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4273 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4274 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4275 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4276 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4277 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4278 // No commitment_signed so get_event_msg's assert(len == 1) passes
4279 check_added_monitors!(nodes[1], 1);
4281 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4282 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4283 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4284 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4285 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4286 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4287 assert!(bs_second_commitment_signed.update_fee.is_none());
4288 check_added_monitors!(nodes[1], 1);
4290 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4291 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4292 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4293 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4294 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4295 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4296 assert!(as_commitment_signed.update_fee.is_none());
4297 check_added_monitors!(nodes[0], 1);
4299 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4300 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4301 // No commitment_signed so get_event_msg's assert(len == 1) passes
4302 check_added_monitors!(nodes[0], 1);
4304 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4305 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4306 // No commitment_signed so get_event_msg's assert(len == 1) passes
4307 check_added_monitors!(nodes[1], 1);
4309 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4310 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4311 check_added_monitors!(nodes[1], 1);
4313 expect_pending_htlcs_forwardable!(nodes[1]);
4315 let events_5 = nodes[1].node.get_and_clear_pending_events();
4316 assert_eq!(events_5.len(), 1);
4318 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4319 assert_eq!(payment_hash_2, *payment_hash);
4321 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4322 assert!(payment_preimage.is_none());
4323 assert_eq!(payment_secret_2, *payment_secret);
4325 _ => panic!("expected PaymentPurpose::InvoicePayment")
4328 _ => panic!("Unexpected event"),
4331 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4332 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4333 check_added_monitors!(nodes[0], 1);
4335 expect_payment_path_successful!(nodes[0]);
4336 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4339 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4340 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4341 // to avoid our counterparty failing the channel.
4342 let chanmon_cfgs = create_chanmon_cfgs(2);
4343 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4344 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4345 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4347 create_announced_chan_between_nodes(&nodes, 0, 1);
4349 let our_payment_hash = if send_partial_mpp {
4350 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4351 // Use the utility function send_payment_along_path to send the payment with MPP data which
4352 // indicates there are more HTLCs coming.
4353 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.
4354 let payment_id = PaymentId([42; 32]);
4355 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
4356 RecipientOnionFields::secret_only(payment_secret), payment_id, &route).unwrap();
4357 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
4358 RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id,
4359 &None, session_privs[0]).unwrap();
4360 check_added_monitors!(nodes[0], 1);
4361 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4362 assert_eq!(events.len(), 1);
4363 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4364 // hop should *not* yet generate any PaymentClaimable event(s).
4365 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4368 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4371 let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
4372 connect_block(&nodes[0], &block);
4373 connect_block(&nodes[1], &block);
4374 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4375 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4376 block.header.prev_blockhash = block.block_hash();
4377 connect_block(&nodes[0], &block);
4378 connect_block(&nodes[1], &block);
4381 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4383 check_added_monitors!(nodes[1], 1);
4384 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4385 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4386 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4387 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4388 assert!(htlc_timeout_updates.update_fee.is_none());
4390 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4391 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4392 // 100_000 msat as u64, followed by the height at which we failed back above
4393 let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4394 expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4395 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4399 fn test_htlc_timeout() {
4400 do_test_htlc_timeout(true);
4401 do_test_htlc_timeout(false);
4404 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4405 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4406 let chanmon_cfgs = create_chanmon_cfgs(3);
4407 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4408 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4409 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4410 create_announced_chan_between_nodes(&nodes, 0, 1);
4411 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4413 // Make sure all nodes are at the same starting height
4414 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4415 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4416 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4418 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4419 let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4420 nodes[1].node.send_payment_with_route(&route, first_payment_hash,
4421 RecipientOnionFields::secret_only(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4422 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4423 check_added_monitors!(nodes[1], 1);
4425 // Now attempt to route a second payment, which should be placed in the holding cell
4426 let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4427 let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4428 sending_node.node.send_payment_with_route(&route, second_payment_hash,
4429 RecipientOnionFields::secret_only(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4431 check_added_monitors!(nodes[0], 1);
4432 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4433 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4434 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4435 expect_pending_htlcs_forwardable!(nodes[1]);
4437 check_added_monitors!(nodes[1], 0);
4439 connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4440 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4441 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4442 connect_blocks(&nodes[1], 1);
4445 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 }]);
4446 check_added_monitors!(nodes[1], 1);
4447 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4448 assert_eq!(fail_commit.len(), 1);
4449 match fail_commit[0] {
4450 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4451 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4452 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4454 _ => unreachable!(),
4456 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4458 expect_payment_failed!(nodes[1], second_payment_hash, false);
4463 fn test_holding_cell_htlc_add_timeouts() {
4464 do_test_holding_cell_htlc_add_timeouts(false);
4465 do_test_holding_cell_htlc_add_timeouts(true);
4468 macro_rules! check_spendable_outputs {
4469 ($node: expr, $keysinterface: expr) => {
4471 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4472 let mut txn = Vec::new();
4473 let mut all_outputs = Vec::new();
4474 let secp_ctx = Secp256k1::new();
4475 for event in events.drain(..) {
4477 Event::SpendableOutputs { mut outputs, channel_id: _ } => {
4478 for outp in outputs.drain(..) {
4479 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());
4480 all_outputs.push(outp);
4483 _ => panic!("Unexpected event"),
4486 if all_outputs.len() > 1 {
4487 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) {
4497 fn test_claim_sizeable_push_msat() {
4498 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4499 let chanmon_cfgs = create_chanmon_cfgs(2);
4500 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4501 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4502 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4504 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4505 nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4506 check_closed_broadcast!(nodes[1], true);
4507 check_added_monitors!(nodes[1], 1);
4508 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[0].node.get_our_node_id()], 100000);
4509 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4510 assert_eq!(node_txn.len(), 1);
4511 check_spends!(node_txn[0], chan.3);
4512 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
4514 mine_transaction(&nodes[1], &node_txn[0]);
4515 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4517 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4518 assert_eq!(spend_txn.len(), 1);
4519 assert_eq!(spend_txn[0].input.len(), 1);
4520 check_spends!(spend_txn[0], node_txn[0]);
4521 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4525 fn test_claim_on_remote_sizeable_push_msat() {
4526 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4527 // to_remote output is encumbered by a P2WPKH
4528 let chanmon_cfgs = create_chanmon_cfgs(2);
4529 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4530 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4531 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4533 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4534 nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4535 check_closed_broadcast!(nodes[0], true);
4536 check_added_monitors!(nodes[0], 1);
4537 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
4539 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4540 assert_eq!(node_txn.len(), 1);
4541 check_spends!(node_txn[0], chan.3);
4542 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
4544 mine_transaction(&nodes[1], &node_txn[0]);
4545 check_closed_broadcast!(nodes[1], true);
4546 check_added_monitors!(nodes[1], 1);
4547 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4548 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4550 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4551 assert_eq!(spend_txn.len(), 1);
4552 check_spends!(spend_txn[0], node_txn[0]);
4556 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4557 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4558 // to_remote output is encumbered by a P2WPKH
4560 let chanmon_cfgs = create_chanmon_cfgs(2);
4561 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4562 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4563 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4565 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4566 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4567 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4568 assert_eq!(revoked_local_txn[0].input.len(), 1);
4569 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4571 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4572 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4573 check_closed_broadcast!(nodes[1], true);
4574 check_added_monitors!(nodes[1], 1);
4575 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4577 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4578 mine_transaction(&nodes[1], &node_txn[0]);
4579 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4581 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4582 assert_eq!(spend_txn.len(), 3);
4583 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4584 check_spends!(spend_txn[1], node_txn[0]);
4585 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4589 fn test_static_spendable_outputs_preimage_tx() {
4590 let chanmon_cfgs = create_chanmon_cfgs(2);
4591 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4592 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4593 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4595 // Create some initial channels
4596 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4598 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4600 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4601 assert_eq!(commitment_tx[0].input.len(), 1);
4602 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4604 // Settle A's commitment tx on B's chain
4605 nodes[1].node.claim_funds(payment_preimage);
4606 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4607 check_added_monitors!(nodes[1], 1);
4608 mine_transaction(&nodes[1], &commitment_tx[0]);
4609 check_added_monitors!(nodes[1], 1);
4610 let events = nodes[1].node.get_and_clear_pending_msg_events();
4612 MessageSendEvent::UpdateHTLCs { .. } => {},
4613 _ => panic!("Unexpected event"),
4616 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4617 _ => panic!("Unexepected event"),
4620 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4621 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4622 assert_eq!(node_txn.len(), 1);
4623 check_spends!(node_txn[0], commitment_tx[0]);
4624 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4626 mine_transaction(&nodes[1], &node_txn[0]);
4627 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4628 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4630 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4631 assert_eq!(spend_txn.len(), 1);
4632 check_spends!(spend_txn[0], node_txn[0]);
4636 fn test_static_spendable_outputs_timeout_tx() {
4637 let chanmon_cfgs = create_chanmon_cfgs(2);
4638 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4639 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4640 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4642 // Create some initial channels
4643 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4645 // Rebalance the network a bit by relaying one payment through all the channels ...
4646 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4648 let (_, our_payment_hash, ..) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4650 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4651 assert_eq!(commitment_tx[0].input.len(), 1);
4652 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4654 // Settle A's commitment tx on B' chain
4655 mine_transaction(&nodes[1], &commitment_tx[0]);
4656 check_added_monitors!(nodes[1], 1);
4657 let events = nodes[1].node.get_and_clear_pending_msg_events();
4659 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4660 _ => panic!("Unexpected event"),
4662 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4664 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4665 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4666 assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4667 check_spends!(node_txn[0], commitment_tx[0].clone());
4668 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4670 mine_transaction(&nodes[1], &node_txn[0]);
4671 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4672 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4673 expect_payment_failed!(nodes[1], our_payment_hash, false);
4675 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4676 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4677 check_spends!(spend_txn[0], commitment_tx[0]);
4678 check_spends!(spend_txn[1], node_txn[0]);
4679 check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4683 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4684 let chanmon_cfgs = create_chanmon_cfgs(2);
4685 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4686 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4687 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4689 // Create some initial channels
4690 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4692 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4693 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4694 assert_eq!(revoked_local_txn[0].input.len(), 1);
4695 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4697 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4699 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4700 check_closed_broadcast!(nodes[1], true);
4701 check_added_monitors!(nodes[1], 1);
4702 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4704 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4705 assert_eq!(node_txn.len(), 1);
4706 assert_eq!(node_txn[0].input.len(), 2);
4707 check_spends!(node_txn[0], revoked_local_txn[0]);
4709 mine_transaction(&nodes[1], &node_txn[0]);
4710 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4712 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4713 assert_eq!(spend_txn.len(), 1);
4714 check_spends!(spend_txn[0], node_txn[0]);
4718 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4719 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4720 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4721 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4722 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4723 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4725 // Create some initial channels
4726 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4728 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4729 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4730 assert_eq!(revoked_local_txn[0].input.len(), 1);
4731 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4733 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4735 // A will generate HTLC-Timeout from revoked commitment tx
4736 mine_transaction(&nodes[0], &revoked_local_txn[0]);
4737 check_closed_broadcast!(nodes[0], true);
4738 check_added_monitors!(nodes[0], 1);
4739 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4740 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4742 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4743 assert_eq!(revoked_htlc_txn.len(), 1);
4744 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4745 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4746 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4747 assert_ne!(revoked_htlc_txn[0].lock_time, LockTime::ZERO); // HTLC-Timeout
4749 // B will generate justice tx from A's revoked commitment/HTLC tx
4750 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4751 check_closed_broadcast!(nodes[1], true);
4752 check_added_monitors!(nodes[1], 1);
4753 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4755 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4756 assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4757 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4758 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4759 // transactions next...
4760 assert_eq!(node_txn[0].input.len(), 3);
4761 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4763 assert_eq!(node_txn[1].input.len(), 2);
4764 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4765 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4766 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4768 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4769 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4772 mine_transaction(&nodes[1], &node_txn[1]);
4773 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4775 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4776 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4777 assert_eq!(spend_txn.len(), 1);
4778 assert_eq!(spend_txn[0].input.len(), 1);
4779 check_spends!(spend_txn[0], node_txn[1]);
4783 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4784 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4785 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4786 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4787 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4788 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4790 // Create some initial channels
4791 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4793 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4794 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4795 assert_eq!(revoked_local_txn[0].input.len(), 1);
4796 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4798 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4799 assert_eq!(revoked_local_txn[0].output.len(), 2);
4801 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4803 // B will generate HTLC-Success from revoked commitment tx
4804 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4805 check_closed_broadcast!(nodes[1], true);
4806 check_added_monitors!(nodes[1], 1);
4807 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4808 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4810 assert_eq!(revoked_htlc_txn.len(), 1);
4811 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4812 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4813 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4815 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4816 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4817 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4819 // A will generate justice tx from B's revoked commitment/HTLC tx
4820 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4821 check_closed_broadcast!(nodes[0], true);
4822 check_added_monitors!(nodes[0], 1);
4823 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4825 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4826 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4828 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4829 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4830 // transactions next...
4831 assert_eq!(node_txn[0].input.len(), 2);
4832 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4833 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4834 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4836 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4837 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4840 assert_eq!(node_txn[1].input.len(), 1);
4841 check_spends!(node_txn[1], revoked_htlc_txn[0]);
4843 mine_transaction(&nodes[0], &node_txn[1]);
4844 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4846 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4847 // didn't try to generate any new transactions.
4849 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4850 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4851 assert_eq!(spend_txn.len(), 3);
4852 assert_eq!(spend_txn[0].input.len(), 1);
4853 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4854 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4855 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4856 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4860 fn test_onchain_to_onchain_claim() {
4861 // Test that in case of channel closure, we detect the state of output and claim HTLC
4862 // on downstream peer's remote commitment tx.
4863 // First, have C claim an HTLC against its own latest commitment transaction.
4864 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4866 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4869 let chanmon_cfgs = create_chanmon_cfgs(3);
4870 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4871 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4872 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4874 // Create some initial channels
4875 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4876 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4878 // Ensure all nodes are at the same height
4879 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4880 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4881 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4882 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4884 // Rebalance the network a bit by relaying one payment through all the channels ...
4885 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4886 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4888 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4889 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4890 check_spends!(commitment_tx[0], chan_2.3);
4891 nodes[2].node.claim_funds(payment_preimage);
4892 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4893 check_added_monitors!(nodes[2], 1);
4894 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4895 assert!(updates.update_add_htlcs.is_empty());
4896 assert!(updates.update_fail_htlcs.is_empty());
4897 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4898 assert!(updates.update_fail_malformed_htlcs.is_empty());
4900 mine_transaction(&nodes[2], &commitment_tx[0]);
4901 check_closed_broadcast!(nodes[2], true);
4902 check_added_monitors!(nodes[2], 1);
4903 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4905 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4906 assert_eq!(c_txn.len(), 1);
4907 check_spends!(c_txn[0], commitment_tx[0]);
4908 assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4909 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4910 assert_eq!(c_txn[0].lock_time, LockTime::ZERO); // Success tx
4912 // 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
4913 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![commitment_tx[0].clone(), c_txn[0].clone()]));
4914 check_added_monitors!(nodes[1], 1);
4915 let events = nodes[1].node.get_and_clear_pending_events();
4916 assert_eq!(events.len(), 2);
4918 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4919 _ => panic!("Unexpected event"),
4922 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
4923 assert_eq!(fee_earned_msat, Some(1000));
4924 assert_eq!(prev_channel_id, Some(chan_1.2));
4925 assert_eq!(claim_from_onchain_tx, true);
4926 assert_eq!(next_channel_id, Some(chan_2.2));
4927 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
4929 _ => panic!("Unexpected event"),
4931 check_added_monitors!(nodes[1], 1);
4932 let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4933 assert_eq!(msg_events.len(), 3);
4934 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut msg_events);
4935 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut msg_events);
4937 match nodes_2_event {
4938 MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { .. }, node_id: _ } => {},
4939 _ => panic!("Unexpected event"),
4942 match nodes_0_event {
4943 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, .. } } => {
4944 assert!(update_add_htlcs.is_empty());
4945 assert!(update_fail_htlcs.is_empty());
4946 assert_eq!(update_fulfill_htlcs.len(), 1);
4947 assert!(update_fail_malformed_htlcs.is_empty());
4948 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4950 _ => panic!("Unexpected event"),
4953 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
4954 match msg_events[0] {
4955 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4956 _ => panic!("Unexpected event"),
4959 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4960 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4961 mine_transaction(&nodes[1], &commitment_tx[0]);
4962 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4963 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4964 // ChannelMonitor: HTLC-Success tx
4965 assert_eq!(b_txn.len(), 1);
4966 check_spends!(b_txn[0], commitment_tx[0]);
4967 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4968 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4969 assert_eq!(b_txn[0].lock_time.to_consensus_u32(), nodes[1].best_block_info().1); // Success tx
4971 check_closed_broadcast!(nodes[1], true);
4972 check_added_monitors!(nodes[1], 1);
4976 fn test_duplicate_payment_hash_one_failure_one_success() {
4977 // Topology : A --> B --> C --> D
4978 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4979 // Note that because C will refuse to generate two payment secrets for the same payment hash,
4980 // we forward one of the payments onwards to D.
4981 let chanmon_cfgs = create_chanmon_cfgs(4);
4982 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4983 // When this test was written, the default base fee floated based on the HTLC count.
4984 // It is now fixed, so we simply set the fee to the expected value here.
4985 let mut config = test_default_channel_config();
4986 config.channel_config.forwarding_fee_base_msat = 196;
4987 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4988 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4989 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4991 create_announced_chan_between_nodes(&nodes, 0, 1);
4992 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4993 create_announced_chan_between_nodes(&nodes, 2, 3);
4995 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4996 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4997 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4998 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4999 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5001 let (our_payment_preimage, duplicate_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
5003 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
5004 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5005 // script push size limit so that the below script length checks match
5006 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5007 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV - 40)
5008 .with_bolt11_features(nodes[3].node.bolt11_invoice_features()).unwrap();
5009 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000);
5010 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
5012 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5013 assert_eq!(commitment_txn[0].input.len(), 1);
5014 check_spends!(commitment_txn[0], chan_2.3);
5016 mine_transaction(&nodes[1], &commitment_txn[0]);
5017 check_closed_broadcast!(nodes[1], true);
5018 check_added_monitors!(nodes[1], 1);
5019 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
5020 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
5022 let htlc_timeout_tx;
5023 { // Extract one of the two HTLC-Timeout transaction
5024 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5025 // ChannelMonitor: timeout tx * 2-or-3
5026 assert!(node_txn.len() == 2 || node_txn.len() == 3);
5028 check_spends!(node_txn[0], commitment_txn[0]);
5029 assert_eq!(node_txn[0].input.len(), 1);
5030 assert_eq!(node_txn[0].output.len(), 1);
5032 if node_txn.len() > 2 {
5033 check_spends!(node_txn[1], commitment_txn[0]);
5034 assert_eq!(node_txn[1].input.len(), 1);
5035 assert_eq!(node_txn[1].output.len(), 1);
5036 assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
5038 check_spends!(node_txn[2], commitment_txn[0]);
5039 assert_eq!(node_txn[2].input.len(), 1);
5040 assert_eq!(node_txn[2].output.len(), 1);
5041 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
5043 check_spends!(node_txn[1], commitment_txn[0]);
5044 assert_eq!(node_txn[1].input.len(), 1);
5045 assert_eq!(node_txn[1].output.len(), 1);
5046 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
5049 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5050 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5051 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
5052 // (with value 900 sats) will be claimed in the below `claim_funds` call.
5053 if node_txn.len() > 2 {
5054 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5055 htlc_timeout_tx = if node_txn[2].output[0].value < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
5057 htlc_timeout_tx = if node_txn[0].output[0].value < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
5061 nodes[2].node.claim_funds(our_payment_preimage);
5062 expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
5064 mine_transaction(&nodes[2], &commitment_txn[0]);
5065 check_added_monitors!(nodes[2], 2);
5066 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5067 let events = nodes[2].node.get_and_clear_pending_msg_events();
5069 MessageSendEvent::UpdateHTLCs { .. } => {},
5070 _ => panic!("Unexpected event"),
5073 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5074 _ => panic!("Unexepected event"),
5076 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5077 assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
5078 check_spends!(htlc_success_txn[0], commitment_txn[0]);
5079 check_spends!(htlc_success_txn[1], commitment_txn[0]);
5080 assert_eq!(htlc_success_txn[0].input.len(), 1);
5081 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5082 assert_eq!(htlc_success_txn[1].input.len(), 1);
5083 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5084 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5085 assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5087 mine_transaction(&nodes[1], &htlc_timeout_tx);
5088 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5089 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 }]);
5090 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5091 assert!(htlc_updates.update_add_htlcs.is_empty());
5092 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5093 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5094 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5095 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5096 check_added_monitors!(nodes[1], 1);
5098 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5099 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5101 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5103 expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5105 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5106 mine_transaction(&nodes[1], &htlc_success_txn[1]);
5107 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
5108 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5109 assert!(updates.update_add_htlcs.is_empty());
5110 assert!(updates.update_fail_htlcs.is_empty());
5111 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5112 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5113 assert!(updates.update_fail_malformed_htlcs.is_empty());
5114 check_added_monitors!(nodes[1], 1);
5116 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5117 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5118 expect_payment_sent(&nodes[0], our_payment_preimage, None, true, true);
5122 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5123 let chanmon_cfgs = create_chanmon_cfgs(2);
5124 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5125 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5126 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5128 // Create some initial channels
5129 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5131 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
5132 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5133 assert_eq!(local_txn.len(), 1);
5134 assert_eq!(local_txn[0].input.len(), 1);
5135 check_spends!(local_txn[0], chan_1.3);
5137 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5138 nodes[1].node.claim_funds(payment_preimage);
5139 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
5140 check_added_monitors!(nodes[1], 1);
5142 mine_transaction(&nodes[1], &local_txn[0]);
5143 check_added_monitors!(nodes[1], 1);
5144 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
5145 let events = nodes[1].node.get_and_clear_pending_msg_events();
5147 MessageSendEvent::UpdateHTLCs { .. } => {},
5148 _ => panic!("Unexpected event"),
5151 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5152 _ => panic!("Unexepected event"),
5155 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5156 assert_eq!(node_txn.len(), 1);
5157 assert_eq!(node_txn[0].input.len(), 1);
5158 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5159 check_spends!(node_txn[0], local_txn[0]);
5163 mine_transaction(&nodes[1], &node_tx);
5164 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5166 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5167 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5168 assert_eq!(spend_txn.len(), 1);
5169 assert_eq!(spend_txn[0].input.len(), 1);
5170 check_spends!(spend_txn[0], node_tx);
5171 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5174 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5175 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5176 // unrevoked commitment transaction.
5177 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5178 // a remote RAA before they could be failed backwards (and combinations thereof).
5179 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5180 // use the same payment hashes.
5181 // Thus, we use a six-node network:
5186 // And test where C fails back to A/B when D announces its latest commitment transaction
5187 let chanmon_cfgs = create_chanmon_cfgs(6);
5188 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5189 // When this test was written, the default base fee floated based on the HTLC count.
5190 // It is now fixed, so we simply set the fee to the expected value here.
5191 let mut config = test_default_channel_config();
5192 config.channel_config.forwarding_fee_base_msat = 196;
5193 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5194 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5195 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5197 let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2);
5198 let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5199 let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5200 let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
5201 let chan_3_5 = create_announced_chan_between_nodes(&nodes, 3, 5);
5203 // Rebalance and check output sanity...
5204 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5205 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5206 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
5208 let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
5209 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().context().holder_dust_limit_satoshis;
5211 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
5213 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
5214 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5216 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
5218 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
5220 let (_, payment_hash_3, ..) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5222 let (_, payment_hash_4, ..) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5223 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5225 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());
5227 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());
5230 let (_, payment_hash_5, ..) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5232 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5233 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
5236 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
5238 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5239 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());
5241 // Double-check that six of the new HTLC were added
5242 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5243 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5244 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5245 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5247 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5248 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5249 nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5250 nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5251 nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5252 nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5253 check_added_monitors!(nodes[4], 0);
5255 let failed_destinations = vec![
5256 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5257 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5258 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5259 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5261 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5262 check_added_monitors!(nodes[4], 1);
5264 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5265 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5266 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5267 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5268 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5269 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5271 // Fail 3rd below-dust and 7th above-dust HTLCs
5272 nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5273 nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5274 check_added_monitors!(nodes[5], 0);
5276 let failed_destinations_2 = vec![
5277 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5278 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5280 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5281 check_added_monitors!(nodes[5], 1);
5283 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5284 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5285 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5286 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5288 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5290 // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5291 let failed_destinations_3 = vec![
5292 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5293 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5294 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5295 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5296 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5297 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5299 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5300 check_added_monitors!(nodes[3], 1);
5301 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5302 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5303 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5304 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5305 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5306 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5307 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5308 if deliver_last_raa {
5309 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5311 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5314 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5315 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5316 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5317 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5319 // We now broadcast the latest commitment transaction, which *should* result in failures for
5320 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5321 // the non-broadcast above-dust HTLCs.
5323 // Alternatively, we may broadcast the previous commitment transaction, which should only
5324 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5325 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5327 if announce_latest {
5328 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5330 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5332 let events = nodes[2].node.get_and_clear_pending_events();
5333 let close_event = if deliver_last_raa {
5334 assert_eq!(events.len(), 2 + 6);
5335 events.last().clone().unwrap()
5337 assert_eq!(events.len(), 1);
5338 events.last().clone().unwrap()
5341 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5342 _ => panic!("Unexpected event"),
5345 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5346 check_closed_broadcast!(nodes[2], true);
5347 if deliver_last_raa {
5348 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5350 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();
5351 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5353 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5354 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5356 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5359 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5361 check_added_monitors!(nodes[2], 3);
5363 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5364 assert_eq!(cs_msgs.len(), 2);
5365 let mut a_done = false;
5366 for msg in cs_msgs {
5368 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5369 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5370 // should be failed-backwards here.
5371 let target = if *node_id == nodes[0].node.get_our_node_id() {
5372 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5373 for htlc in &updates.update_fail_htlcs {
5374 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 });
5376 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5381 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5382 for htlc in &updates.update_fail_htlcs {
5383 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5385 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5386 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5389 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5390 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5391 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5392 if announce_latest {
5393 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5394 if *node_id == nodes[0].node.get_our_node_id() {
5395 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5398 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5400 _ => panic!("Unexpected event"),
5404 let as_events = nodes[0].node.get_and_clear_pending_events();
5405 assert_eq!(as_events.len(), if announce_latest { 10 } else { 6 });
5406 let mut as_failds = HashSet::new();
5407 let mut as_updates = 0;
5408 for event in as_events.iter() {
5409 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5410 assert!(as_failds.insert(*payment_hash));
5411 if *payment_hash != payment_hash_2 {
5412 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5414 assert!(!payment_failed_permanently);
5416 if let PathFailure::OnPath { network_update: Some(_) } = failure {
5419 } else if let &Event::PaymentFailed { .. } = event {
5420 } else { panic!("Unexpected event"); }
5422 assert!(as_failds.contains(&payment_hash_1));
5423 assert!(as_failds.contains(&payment_hash_2));
5424 if announce_latest {
5425 assert!(as_failds.contains(&payment_hash_3));
5426 assert!(as_failds.contains(&payment_hash_5));
5428 assert!(as_failds.contains(&payment_hash_6));
5430 let bs_events = nodes[1].node.get_and_clear_pending_events();
5431 assert_eq!(bs_events.len(), if announce_latest { 8 } else { 6 });
5432 let mut bs_failds = HashSet::new();
5433 let mut bs_updates = 0;
5434 for event in bs_events.iter() {
5435 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5436 assert!(bs_failds.insert(*payment_hash));
5437 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5438 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5440 assert!(!payment_failed_permanently);
5442 if let PathFailure::OnPath { network_update: Some(_) } = failure {
5445 } else if let &Event::PaymentFailed { .. } = event {
5446 } else { panic!("Unexpected event"); }
5448 assert!(bs_failds.contains(&payment_hash_1));
5449 assert!(bs_failds.contains(&payment_hash_2));
5450 if announce_latest {
5451 assert!(bs_failds.contains(&payment_hash_4));
5453 assert!(bs_failds.contains(&payment_hash_5));
5455 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5456 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5457 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5458 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5459 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5460 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5464 fn test_fail_backwards_latest_remote_announce_a() {
5465 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5469 fn test_fail_backwards_latest_remote_announce_b() {
5470 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5474 fn test_fail_backwards_previous_remote_announce() {
5475 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5476 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5477 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5481 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5482 let chanmon_cfgs = create_chanmon_cfgs(2);
5483 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5484 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5485 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5487 // Create some initial channels
5488 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5490 let (_, our_payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5491 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5492 assert_eq!(local_txn[0].input.len(), 1);
5493 check_spends!(local_txn[0], chan_1.3);
5495 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5496 mine_transaction(&nodes[0], &local_txn[0]);
5497 check_closed_broadcast!(nodes[0], true);
5498 check_added_monitors!(nodes[0], 1);
5499 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5500 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5502 let htlc_timeout = {
5503 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5504 assert_eq!(node_txn.len(), 1);
5505 assert_eq!(node_txn[0].input.len(), 1);
5506 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5507 check_spends!(node_txn[0], local_txn[0]);
5511 mine_transaction(&nodes[0], &htlc_timeout);
5512 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5513 expect_payment_failed!(nodes[0], our_payment_hash, false);
5515 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5516 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5517 assert_eq!(spend_txn.len(), 3);
5518 check_spends!(spend_txn[0], local_txn[0]);
5519 assert_eq!(spend_txn[1].input.len(), 1);
5520 check_spends!(spend_txn[1], htlc_timeout);
5521 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5522 assert_eq!(spend_txn[2].input.len(), 2);
5523 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5524 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5525 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5529 fn test_key_derivation_params() {
5530 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5531 // manager rotation to test that `channel_keys_id` returned in
5532 // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5533 // then derive a `delayed_payment_key`.
5535 let chanmon_cfgs = create_chanmon_cfgs(3);
5537 // We manually create the node configuration to backup the seed.
5538 let seed = [42; 32];
5539 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5540 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);
5541 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[0].logger));
5542 let scorer = RwLock::new(test_utils::TestScorer::new());
5543 let router = test_utils::TestRouter::new(network_graph.clone(), &chanmon_cfgs[0].logger, &scorer);
5544 let message_router = test_utils::TestMessageRouter::new(network_graph.clone());
5545 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, message_router, chain_monitor, keys_manager: &keys_manager, network_graph, node_seed: seed, override_init_features: alloc::rc::Rc::new(core::cell::RefCell::new(None)) };
5546 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5547 node_cfgs.remove(0);
5548 node_cfgs.insert(0, node);
5550 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5551 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5553 // Create some initial channels
5554 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5556 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2);
5557 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5558 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5560 // Ensure all nodes are at the same height
5561 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5562 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5563 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5564 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5566 let (_, our_payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5567 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5568 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5569 assert_eq!(local_txn_1[0].input.len(), 1);
5570 check_spends!(local_txn_1[0], chan_1.3);
5572 // We check funding pubkey are unique
5573 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]));
5574 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]));
5575 if from_0_funding_key_0 == from_1_funding_key_0
5576 || from_0_funding_key_0 == from_1_funding_key_1
5577 || from_0_funding_key_1 == from_1_funding_key_0
5578 || from_0_funding_key_1 == from_1_funding_key_1 {
5579 panic!("Funding pubkeys aren't unique");
5582 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5583 mine_transaction(&nodes[0], &local_txn_1[0]);
5584 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5585 check_closed_broadcast!(nodes[0], true);
5586 check_added_monitors!(nodes[0], 1);
5587 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5589 let htlc_timeout = {
5590 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5591 assert_eq!(node_txn.len(), 1);
5592 assert_eq!(node_txn[0].input.len(), 1);
5593 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5594 check_spends!(node_txn[0], local_txn_1[0]);
5598 mine_transaction(&nodes[0], &htlc_timeout);
5599 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5600 expect_payment_failed!(nodes[0], our_payment_hash, false);
5602 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5603 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5604 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5605 assert_eq!(spend_txn.len(), 3);
5606 check_spends!(spend_txn[0], local_txn_1[0]);
5607 assert_eq!(spend_txn[1].input.len(), 1);
5608 check_spends!(spend_txn[1], htlc_timeout);
5609 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5610 assert_eq!(spend_txn[2].input.len(), 2);
5611 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5612 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5613 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5617 fn test_static_output_closing_tx() {
5618 let chanmon_cfgs = create_chanmon_cfgs(2);
5619 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5620 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5621 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5623 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5625 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5626 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5628 mine_transaction(&nodes[0], &closing_tx);
5629 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
5630 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5632 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5633 assert_eq!(spend_txn.len(), 1);
5634 check_spends!(spend_txn[0], closing_tx);
5636 mine_transaction(&nodes[1], &closing_tx);
5637 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
5638 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5640 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5641 assert_eq!(spend_txn.len(), 1);
5642 check_spends!(spend_txn[0], closing_tx);
5645 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5646 let chanmon_cfgs = create_chanmon_cfgs(2);
5647 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5648 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5649 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5650 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5652 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5654 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5655 // present in B's local commitment transaction, but none of A's commitment transactions.
5656 nodes[1].node.claim_funds(payment_preimage);
5657 check_added_monitors!(nodes[1], 1);
5658 expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5660 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5661 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5662 expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
5664 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5665 check_added_monitors!(nodes[0], 1);
5666 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5667 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5668 check_added_monitors!(nodes[1], 1);
5670 let starting_block = nodes[1].best_block_info();
5671 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5672 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5673 connect_block(&nodes[1], &block);
5674 block.header.prev_blockhash = block.block_hash();
5676 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5677 check_closed_broadcast!(nodes[1], true);
5678 check_added_monitors!(nodes[1], 1);
5679 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[0].node.get_our_node_id()], 100000);
5682 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5683 let chanmon_cfgs = create_chanmon_cfgs(2);
5684 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5685 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5686 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5687 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5689 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5690 nodes[0].node.send_payment_with_route(&route, payment_hash,
5691 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
5692 check_added_monitors!(nodes[0], 1);
5694 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5696 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5697 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5698 // to "time out" the HTLC.
5700 let starting_block = nodes[1].best_block_info();
5701 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5703 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5704 connect_block(&nodes[0], &block);
5705 block.header.prev_blockhash = block.block_hash();
5707 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5708 check_closed_broadcast!(nodes[0], true);
5709 check_added_monitors!(nodes[0], 1);
5710 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
5713 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5714 let chanmon_cfgs = create_chanmon_cfgs(3);
5715 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5716 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5717 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5718 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5720 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5721 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5722 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5723 // actually revoked.
5724 let htlc_value = if use_dust { 50000 } else { 3000000 };
5725 let (_, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5726 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5727 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5728 check_added_monitors!(nodes[1], 1);
5730 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5731 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5732 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5733 check_added_monitors!(nodes[0], 1);
5734 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5735 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5736 check_added_monitors!(nodes[1], 1);
5737 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5738 check_added_monitors!(nodes[1], 1);
5739 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5741 if check_revoke_no_close {
5742 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5743 check_added_monitors!(nodes[0], 1);
5746 let starting_block = nodes[1].best_block_info();
5747 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5748 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5749 connect_block(&nodes[0], &block);
5750 block.header.prev_blockhash = block.block_hash();
5752 if !check_revoke_no_close {
5753 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5754 check_closed_broadcast!(nodes[0], true);
5755 check_added_monitors!(nodes[0], 1);
5756 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
5758 expect_payment_failed!(nodes[0], our_payment_hash, true);
5762 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5763 // There are only a few cases to test here:
5764 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5765 // broadcastable commitment transactions result in channel closure,
5766 // * its included in an unrevoked-but-previous remote commitment transaction,
5767 // * its included in the latest remote or local commitment transactions.
5768 // We test each of the three possible commitment transactions individually and use both dust and
5770 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5771 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5772 // tested for at least one of the cases in other tests.
5774 fn htlc_claim_single_commitment_only_a() {
5775 do_htlc_claim_local_commitment_only(true);
5776 do_htlc_claim_local_commitment_only(false);
5778 do_htlc_claim_current_remote_commitment_only(true);
5779 do_htlc_claim_current_remote_commitment_only(false);
5783 fn htlc_claim_single_commitment_only_b() {
5784 do_htlc_claim_previous_remote_commitment_only(true, false);
5785 do_htlc_claim_previous_remote_commitment_only(false, false);
5786 do_htlc_claim_previous_remote_commitment_only(true, true);
5787 do_htlc_claim_previous_remote_commitment_only(false, true);
5792 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5793 let chanmon_cfgs = create_chanmon_cfgs(2);
5794 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5795 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5796 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5797 // Force duplicate randomness for every get-random call
5798 for node in nodes.iter() {
5799 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5802 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5803 let channel_value_satoshis=10000;
5804 let push_msat=10001;
5805 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).unwrap();
5806 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5807 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5808 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5810 // Create a second channel with the same random values. This used to panic due to a colliding
5811 // channel_id, but now panics due to a colliding outbound SCID alias.
5812 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).is_err());
5816 fn bolt2_open_channel_sending_node_checks_part2() {
5817 let chanmon_cfgs = create_chanmon_cfgs(2);
5818 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5819 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5820 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5822 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5823 let channel_value_satoshis=2^24;
5824 let push_msat=10001;
5825 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).is_err());
5827 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5828 let channel_value_satoshis=10000;
5829 // Test when push_msat is equal to 1000 * funding_satoshis.
5830 let push_msat=1000*channel_value_satoshis+1;
5831 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).is_err());
5833 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5834 let channel_value_satoshis=10000;
5835 let push_msat=10001;
5836 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).is_ok()); //Create a valid channel
5837 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5838 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5840 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5841 // 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
5842 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5844 // 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.
5845 assert!(BREAKDOWN_TIMEOUT>0);
5846 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5848 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5849 let chain_hash = ChainHash::using_genesis_block(Network::Testnet);
5850 assert_eq!(node0_to_1_send_open_channel.chain_hash, chain_hash);
5852 // 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.
5853 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5854 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5855 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5856 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5857 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5861 fn bolt2_open_channel_sane_dust_limit() {
5862 let chanmon_cfgs = create_chanmon_cfgs(2);
5863 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5864 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5865 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5867 let channel_value_satoshis=1000000;
5868 let push_msat=10001;
5869 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).unwrap();
5870 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5871 node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5872 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5874 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5875 let events = nodes[1].node.get_and_clear_pending_msg_events();
5876 let err_msg = match events[0] {
5877 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5880 _ => panic!("Unexpected event"),
5882 assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5885 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5886 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5887 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5888 // is no longer affordable once it's freed.
5890 fn test_fail_holding_cell_htlc_upon_free() {
5891 let chanmon_cfgs = create_chanmon_cfgs(2);
5892 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5893 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5894 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5895 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5897 // First nodes[0] generates an update_fee, setting the channel's
5898 // pending_update_fee.
5900 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5901 *feerate_lock += 20;
5903 nodes[0].node.timer_tick_occurred();
5904 check_added_monitors!(nodes[0], 1);
5906 let events = nodes[0].node.get_and_clear_pending_msg_events();
5907 assert_eq!(events.len(), 1);
5908 let (update_msg, commitment_signed) = match events[0] {
5909 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5910 (update_fee.as_ref(), commitment_signed)
5912 _ => panic!("Unexpected event"),
5915 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5917 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5918 let channel_reserve = chan_stat.channel_reserve_msat;
5919 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5920 let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
5922 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5923 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
5924 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5926 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5927 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5928 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5929 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5930 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5932 // Flush the pending fee update.
5933 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5934 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5935 check_added_monitors!(nodes[1], 1);
5936 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5937 check_added_monitors!(nodes[0], 1);
5939 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5940 // HTLC, but now that the fee has been raised the payment will now fail, causing
5941 // us to surface its failure to the user.
5942 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5943 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5944 nodes[0].logger.assert_log("lightning::ln::channel", format!("Freeing holding cell with 1 HTLC updates in channel {}", chan.2), 1);
5946 // Check that the payment failed to be sent out.
5947 let events = nodes[0].node.get_and_clear_pending_events();
5948 assert_eq!(events.len(), 2);
5950 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5951 assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5952 assert_eq!(our_payment_hash.clone(), *payment_hash);
5953 assert_eq!(*payment_failed_permanently, false);
5954 assert_eq!(*short_channel_id, Some(route.paths[0].hops[0].short_channel_id));
5956 _ => panic!("Unexpected event"),
5959 &Event::PaymentFailed { ref payment_hash, .. } => {
5960 assert_eq!(our_payment_hash.clone(), *payment_hash);
5962 _ => panic!("Unexpected event"),
5966 // Test that if multiple HTLCs are released from the holding cell and one is
5967 // valid but the other is no longer valid upon release, the valid HTLC can be
5968 // successfully completed while the other one fails as expected.
5970 fn test_free_and_fail_holding_cell_htlcs() {
5971 let chanmon_cfgs = create_chanmon_cfgs(2);
5972 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5973 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5974 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5975 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5977 // First nodes[0] generates an update_fee, setting the channel's
5978 // pending_update_fee.
5980 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5981 *feerate_lock += 200;
5983 nodes[0].node.timer_tick_occurred();
5984 check_added_monitors!(nodes[0], 1);
5986 let events = nodes[0].node.get_and_clear_pending_msg_events();
5987 assert_eq!(events.len(), 1);
5988 let (update_msg, commitment_signed) = match events[0] {
5989 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5990 (update_fee.as_ref(), commitment_signed)
5992 _ => panic!("Unexpected event"),
5995 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5997 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5998 let channel_reserve = chan_stat.channel_reserve_msat;
5999 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6000 let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
6002 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6004 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features) - amt_1;
6005 let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
6006 let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
6008 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6009 nodes[0].node.send_payment_with_route(&route_1, payment_hash_1,
6010 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
6011 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6012 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6013 let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
6014 nodes[0].node.send_payment_with_route(&route_2, payment_hash_2,
6015 RecipientOnionFields::secret_only(payment_secret_2), payment_id_2).unwrap();
6016 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6017 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6019 // Flush the pending fee update.
6020 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6021 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6022 check_added_monitors!(nodes[1], 1);
6023 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6024 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6025 check_added_monitors!(nodes[0], 2);
6027 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6028 // but now that the fee has been raised the second payment will now fail, causing us
6029 // to surface its failure to the user. The first payment should succeed.
6030 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6031 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6032 nodes[0].logger.assert_log("lightning::ln::channel", format!("Freeing holding cell with 2 HTLC updates in channel {}", chan.2), 1);
6034 // Check that the second payment failed to be sent out.
6035 let events = nodes[0].node.get_and_clear_pending_events();
6036 assert_eq!(events.len(), 2);
6038 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
6039 assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6040 assert_eq!(payment_hash_2.clone(), *payment_hash);
6041 assert_eq!(*payment_failed_permanently, false);
6042 assert_eq!(*short_channel_id, Some(route_2.paths[0].hops[0].short_channel_id));
6044 _ => panic!("Unexpected event"),
6047 &Event::PaymentFailed { ref payment_hash, .. } => {
6048 assert_eq!(payment_hash_2.clone(), *payment_hash);
6050 _ => panic!("Unexpected event"),
6053 // Complete the first payment and the RAA from the fee update.
6054 let (payment_event, send_raa_event) = {
6055 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6056 assert_eq!(msgs.len(), 2);
6057 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6059 let raa = match send_raa_event {
6060 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6061 _ => panic!("Unexpected event"),
6063 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6064 check_added_monitors!(nodes[1], 1);
6065 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6066 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6067 let events = nodes[1].node.get_and_clear_pending_events();
6068 assert_eq!(events.len(), 1);
6070 Event::PendingHTLCsForwardable { .. } => {},
6071 _ => panic!("Unexpected event"),
6073 nodes[1].node.process_pending_htlc_forwards();
6074 let events = nodes[1].node.get_and_clear_pending_events();
6075 assert_eq!(events.len(), 1);
6077 Event::PaymentClaimable { .. } => {},
6078 _ => panic!("Unexpected event"),
6080 nodes[1].node.claim_funds(payment_preimage_1);
6081 check_added_monitors!(nodes[1], 1);
6082 expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
6084 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6085 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6086 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6087 expect_payment_sent!(nodes[0], payment_preimage_1);
6090 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6091 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6092 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6095 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6096 let chanmon_cfgs = create_chanmon_cfgs(3);
6097 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6098 // Avoid having to include routing fees in calculations
6099 let mut config = test_default_channel_config();
6100 config.channel_config.forwarding_fee_base_msat = 0;
6101 config.channel_config.forwarding_fee_proportional_millionths = 0;
6102 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6103 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6104 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6105 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
6107 // First nodes[1] generates an update_fee, setting the channel's
6108 // pending_update_fee.
6110 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6111 *feerate_lock += 20;
6113 nodes[1].node.timer_tick_occurred();
6114 check_added_monitors!(nodes[1], 1);
6116 let events = nodes[1].node.get_and_clear_pending_msg_events();
6117 assert_eq!(events.len(), 1);
6118 let (update_msg, commitment_signed) = match events[0] {
6119 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6120 (update_fee.as_ref(), commitment_signed)
6122 _ => panic!("Unexpected event"),
6125 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6127 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan_0_1.2);
6128 let channel_reserve = chan_stat.channel_reserve_msat;
6129 let feerate = get_feerate!(nodes[0], nodes[1], chan_0_1.2);
6130 let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_0_1.2);
6132 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6133 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
6134 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6135 let payment_event = {
6136 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6137 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6138 check_added_monitors!(nodes[0], 1);
6140 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6141 assert_eq!(events.len(), 1);
6143 SendEvent::from_event(events.remove(0))
6145 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6146 check_added_monitors!(nodes[1], 0);
6147 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6148 expect_pending_htlcs_forwardable!(nodes[1]);
6150 chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
6151 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6153 // Flush the pending fee update.
6154 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6155 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6156 check_added_monitors!(nodes[2], 1);
6157 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6158 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6159 check_added_monitors!(nodes[1], 2);
6161 // A final RAA message is generated to finalize the fee update.
6162 let events = nodes[1].node.get_and_clear_pending_msg_events();
6163 assert_eq!(events.len(), 1);
6165 let raa_msg = match &events[0] {
6166 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6169 _ => panic!("Unexpected event"),
6172 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6173 check_added_monitors!(nodes[2], 1);
6174 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6176 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6177 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6178 assert_eq!(process_htlc_forwards_event.len(), 2);
6179 match &process_htlc_forwards_event[0] {
6180 &Event::PendingHTLCsForwardable { .. } => {},
6181 _ => panic!("Unexpected event"),
6184 // In response, we call ChannelManager's process_pending_htlc_forwards
6185 nodes[1].node.process_pending_htlc_forwards();
6186 check_added_monitors!(nodes[1], 1);
6188 // This causes the HTLC to be failed backwards.
6189 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6190 assert_eq!(fail_event.len(), 1);
6191 let (fail_msg, commitment_signed) = match &fail_event[0] {
6192 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6193 assert_eq!(updates.update_add_htlcs.len(), 0);
6194 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6195 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6196 assert_eq!(updates.update_fail_htlcs.len(), 1);
6197 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6199 _ => panic!("Unexpected event"),
6202 // Pass the failure messages back to nodes[0].
6203 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6204 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6206 // Complete the HTLC failure+removal process.
6207 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6208 check_added_monitors!(nodes[0], 1);
6209 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6210 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6211 check_added_monitors!(nodes[1], 2);
6212 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6213 assert_eq!(final_raa_event.len(), 1);
6214 let raa = match &final_raa_event[0] {
6215 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6216 _ => panic!("Unexpected event"),
6218 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6219 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6220 check_added_monitors!(nodes[0], 1);
6224 fn test_payment_route_reaching_same_channel_twice() {
6225 //A route should not go through the same channel twice
6226 //It is enforced when constructing a route.
6227 let chanmon_cfgs = create_chanmon_cfgs(2);
6228 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6229 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6230 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6231 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6233 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6234 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
6235 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);
6237 // Extend the path by itself, essentially simulating route going through same channel twice
6238 let cloned_hops = route.paths[0].hops.clone();
6239 route.paths[0].hops.extend_from_slice(&cloned_hops);
6241 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6242 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6243 ), false, APIError::InvalidRoute { ref err },
6244 assert_eq!(err, &"Path went through the same channel twice"));
6247 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6248 // 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.
6249 //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.
6252 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6253 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6254 let chanmon_cfgs = create_chanmon_cfgs(2);
6255 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6256 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6257 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6258 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6260 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6261 route.paths[0].hops[0].fee_msat = 100;
6263 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6264 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6265 ), true, APIError::ChannelUnavailable { .. }, {});
6266 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6270 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6271 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6272 let chanmon_cfgs = create_chanmon_cfgs(2);
6273 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6274 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6275 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6276 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6278 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6279 route.paths[0].hops[0].fee_msat = 0;
6280 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6281 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)),
6282 true, APIError::ChannelUnavailable { ref err },
6283 assert_eq!(err, "Cannot send 0-msat HTLC"));
6285 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6286 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send 0-msat HTLC", 1);
6290 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6291 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6292 let chanmon_cfgs = create_chanmon_cfgs(2);
6293 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6294 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6295 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6296 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6298 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6299 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6300 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6301 check_added_monitors!(nodes[0], 1);
6302 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6303 updates.update_add_htlcs[0].amount_msat = 0;
6305 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6306 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Remote side tried to send a 0-msat HTLC", 3);
6307 check_closed_broadcast!(nodes[1], true).unwrap();
6308 check_added_monitors!(nodes[1], 1);
6309 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() },
6310 [nodes[0].node.get_our_node_id()], 100000);
6314 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6315 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6316 //It is enforced when constructing a route.
6317 let chanmon_cfgs = create_chanmon_cfgs(2);
6318 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6319 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6320 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6321 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6323 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6324 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
6325 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);
6326 route.paths[0].hops.last_mut().unwrap().cltv_expiry_delta = 500000001;
6327 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6328 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6329 ), true, APIError::InvalidRoute { ref err },
6330 assert_eq!(err, &"Channel CLTV overflowed?"));
6334 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6335 //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.
6336 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6337 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6338 let chanmon_cfgs = create_chanmon_cfgs(2);
6339 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6340 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6341 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6342 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6343 let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6344 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context().counterparty_max_accepted_htlcs as u64;
6346 // Fetch a route in advance as we will be unable to once we're unable to send.
6347 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6348 for i in 0..max_accepted_htlcs {
6349 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6350 let payment_event = {
6351 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6352 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6353 check_added_monitors!(nodes[0], 1);
6355 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6356 assert_eq!(events.len(), 1);
6357 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6358 assert_eq!(htlcs[0].htlc_id, i);
6362 SendEvent::from_event(events.remove(0))
6364 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6365 check_added_monitors!(nodes[1], 0);
6366 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6368 expect_pending_htlcs_forwardable!(nodes[1]);
6369 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6371 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6372 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6373 ), true, APIError::ChannelUnavailable { .. }, {});
6375 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6379 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6380 //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.
6381 let chanmon_cfgs = create_chanmon_cfgs(2);
6382 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6383 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6384 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6385 let channel_value = 100000;
6386 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6387 let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6389 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6391 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6392 // Manually create a route over our max in flight (which our router normally automatically
6394 route.paths[0].hops[0].fee_msat = max_in_flight + 1;
6395 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6396 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6397 ), true, APIError::ChannelUnavailable { .. }, {});
6398 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6400 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6403 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6405 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6406 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6407 let chanmon_cfgs = create_chanmon_cfgs(2);
6408 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6409 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6410 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6411 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6412 let htlc_minimum_msat: u64;
6414 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6415 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6416 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6417 htlc_minimum_msat = channel.context().get_holder_htlc_minimum_msat();
6420 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6421 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6422 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6423 check_added_monitors!(nodes[0], 1);
6424 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6425 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6426 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6427 assert!(nodes[1].node.list_channels().is_empty());
6428 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6429 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()));
6430 check_added_monitors!(nodes[1], 1);
6431 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6435 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6436 //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
6437 let chanmon_cfgs = create_chanmon_cfgs(2);
6438 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6439 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6440 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6441 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6443 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6444 let channel_reserve = chan_stat.channel_reserve_msat;
6445 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6446 let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
6447 // The 2* and +1 are for the fee spike reserve.
6448 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
6450 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6451 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6452 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6453 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6454 check_added_monitors!(nodes[0], 1);
6455 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6457 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6458 // at this time channel-initiatee receivers are not required to enforce that senders
6459 // respect the fee_spike_reserve.
6460 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6461 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6463 assert!(nodes[1].node.list_channels().is_empty());
6464 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6465 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6466 check_added_monitors!(nodes[1], 1);
6467 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6471 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6472 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6473 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6474 let chanmon_cfgs = create_chanmon_cfgs(2);
6475 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6476 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6477 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6478 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6480 let send_amt = 3999999;
6481 let (mut route, our_payment_hash, _, our_payment_secret) =
6482 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
6483 route.paths[0].hops[0].fee_msat = send_amt;
6484 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6485 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6486 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6487 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
6488 &route.paths[0], send_amt, RecipientOnionFields::secret_only(our_payment_secret), cur_height, &None).unwrap();
6489 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
6491 let mut msg = msgs::UpdateAddHTLC {
6495 payment_hash: our_payment_hash,
6496 cltv_expiry: htlc_cltv,
6497 onion_routing_packet: onion_packet.clone(),
6498 skimmed_fee_msat: None,
6499 blinding_point: None,
6503 msg.htlc_id = i as u64;
6504 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6506 msg.htlc_id = (50) as u64;
6507 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6509 assert!(nodes[1].node.list_channels().is_empty());
6510 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6511 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6512 check_added_monitors!(nodes[1], 1);
6513 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6517 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6518 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD 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 mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6523 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6525 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6526 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6527 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6528 check_added_monitors!(nodes[0], 1);
6529 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6530 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;
6531 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6533 assert!(nodes[1].node.list_channels().is_empty());
6534 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6535 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6536 check_added_monitors!(nodes[1], 1);
6537 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 1000000);
6541 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6542 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6543 let chanmon_cfgs = create_chanmon_cfgs(2);
6544 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6545 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6546 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6548 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6549 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6550 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6551 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6552 check_added_monitors!(nodes[0], 1);
6553 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6554 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6555 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6557 assert!(nodes[1].node.list_channels().is_empty());
6558 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6559 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6560 check_added_monitors!(nodes[1], 1);
6561 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6565 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6566 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6567 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6568 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6569 let chanmon_cfgs = create_chanmon_cfgs(2);
6570 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6571 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6572 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6574 create_announced_chan_between_nodes(&nodes, 0, 1);
6575 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6576 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6577 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6578 check_added_monitors!(nodes[0], 1);
6579 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6580 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6582 //Disconnect and Reconnect
6583 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
6584 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
6585 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
6586 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
6588 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6589 assert_eq!(reestablish_1.len(), 1);
6590 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
6591 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
6593 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6594 assert_eq!(reestablish_2.len(), 1);
6595 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6596 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6597 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6598 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6601 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6602 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6603 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6604 check_added_monitors!(nodes[1], 1);
6605 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6607 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6609 assert!(nodes[1].node.list_channels().is_empty());
6610 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6611 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6612 check_added_monitors!(nodes[1], 1);
6613 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6617 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6618 //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.
6620 let chanmon_cfgs = create_chanmon_cfgs(2);
6621 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6622 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6623 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6624 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6625 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6626 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6627 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6629 check_added_monitors!(nodes[0], 1);
6630 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6631 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6633 let update_msg = msgs::UpdateFulfillHTLC{
6636 payment_preimage: our_payment_preimage,
6639 nodes[0].node.handle_update_fulfill_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!(regex::Regex::new(r"Remote tried to fulfill/fail HTLC \(\d+\) before it had been committed").unwrap().is_match(err_msg.data.as_str()));
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()], 100000);
6649 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6650 //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.
6652 let chanmon_cfgs = create_chanmon_cfgs(2);
6653 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6654 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6655 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6656 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6658 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6659 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6660 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6661 check_added_monitors!(nodes[0], 1);
6662 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6663 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6665 let update_msg = msgs::UpdateFailHTLC{
6668 reason: msgs::OnionErrorPacket { data: Vec::new()},
6671 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6673 assert!(nodes[0].node.list_channels().is_empty());
6674 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6675 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()));
6676 check_added_monitors!(nodes[0], 1);
6677 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6681 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6682 //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.
6684 let chanmon_cfgs = create_chanmon_cfgs(2);
6685 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6686 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6687 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6688 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6690 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6691 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6692 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6693 check_added_monitors!(nodes[0], 1);
6694 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6695 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6696 let update_msg = msgs::UpdateFailMalformedHTLC{
6699 sha256_of_onion: [1; 32],
6700 failure_code: 0x8000,
6703 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6705 assert!(nodes[0].node.list_channels().is_empty());
6706 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6707 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()));
6708 check_added_monitors!(nodes[0], 1);
6709 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6713 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6714 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6716 let chanmon_cfgs = create_chanmon_cfgs(2);
6717 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6718 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6719 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6720 create_announced_chan_between_nodes(&nodes, 0, 1);
6722 let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6724 nodes[1].node.claim_funds(our_payment_preimage);
6725 check_added_monitors!(nodes[1], 1);
6726 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6728 let events = nodes[1].node.get_and_clear_pending_msg_events();
6729 assert_eq!(events.len(), 1);
6730 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6732 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, .. } } => {
6733 assert!(update_add_htlcs.is_empty());
6734 assert_eq!(update_fulfill_htlcs.len(), 1);
6735 assert!(update_fail_htlcs.is_empty());
6736 assert!(update_fail_malformed_htlcs.is_empty());
6737 assert!(update_fee.is_none());
6738 update_fulfill_htlcs[0].clone()
6740 _ => panic!("Unexpected event"),
6744 update_fulfill_msg.htlc_id = 1;
6746 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6748 assert!(nodes[0].node.list_channels().is_empty());
6749 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6750 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6751 check_added_monitors!(nodes[0], 1);
6752 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6756 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6757 //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.
6759 let chanmon_cfgs = create_chanmon_cfgs(2);
6760 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6761 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6762 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6763 create_announced_chan_between_nodes(&nodes, 0, 1);
6765 let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6767 nodes[1].node.claim_funds(our_payment_preimage);
6768 check_added_monitors!(nodes[1], 1);
6769 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6771 let events = nodes[1].node.get_and_clear_pending_msg_events();
6772 assert_eq!(events.len(), 1);
6773 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6775 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, .. } } => {
6776 assert!(update_add_htlcs.is_empty());
6777 assert_eq!(update_fulfill_htlcs.len(), 1);
6778 assert!(update_fail_htlcs.is_empty());
6779 assert!(update_fail_malformed_htlcs.is_empty());
6780 assert!(update_fee.is_none());
6781 update_fulfill_htlcs[0].clone()
6783 _ => panic!("Unexpected event"),
6787 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6789 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6791 assert!(nodes[0].node.list_channels().is_empty());
6792 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6793 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6794 check_added_monitors!(nodes[0], 1);
6795 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6799 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6800 //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.
6802 let chanmon_cfgs = create_chanmon_cfgs(2);
6803 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6804 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6805 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6806 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6808 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6809 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6810 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6811 check_added_monitors!(nodes[0], 1);
6813 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6814 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6816 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6817 check_added_monitors!(nodes[1], 0);
6818 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6820 let events = nodes[1].node.get_and_clear_pending_msg_events();
6822 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6824 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, .. } } => {
6825 assert!(update_add_htlcs.is_empty());
6826 assert!(update_fulfill_htlcs.is_empty());
6827 assert!(update_fail_htlcs.is_empty());
6828 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6829 assert!(update_fee.is_none());
6830 update_fail_malformed_htlcs[0].clone()
6832 _ => panic!("Unexpected event"),
6835 update_msg.failure_code &= !0x8000;
6836 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6838 assert!(nodes[0].node.list_channels().is_empty());
6839 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6840 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6841 check_added_monitors!(nodes[0], 1);
6842 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 1000000);
6846 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6847 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6848 // * 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.
6850 let chanmon_cfgs = create_chanmon_cfgs(3);
6851 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6852 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6853 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6854 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6855 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000);
6857 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6860 let mut payment_event = {
6861 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6862 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6863 check_added_monitors!(nodes[0], 1);
6864 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6865 assert_eq!(events.len(), 1);
6866 SendEvent::from_event(events.remove(0))
6868 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6869 check_added_monitors!(nodes[1], 0);
6870 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6871 expect_pending_htlcs_forwardable!(nodes[1]);
6872 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6873 assert_eq!(events_2.len(), 1);
6874 check_added_monitors!(nodes[1], 1);
6875 payment_event = SendEvent::from_event(events_2.remove(0));
6876 assert_eq!(payment_event.msgs.len(), 1);
6879 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6880 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6881 check_added_monitors!(nodes[2], 0);
6882 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6884 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6885 assert_eq!(events_3.len(), 1);
6886 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6888 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 } } => {
6889 assert!(update_add_htlcs.is_empty());
6890 assert!(update_fulfill_htlcs.is_empty());
6891 assert!(update_fail_htlcs.is_empty());
6892 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6893 assert!(update_fee.is_none());
6894 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6896 _ => panic!("Unexpected event"),
6900 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6902 check_added_monitors!(nodes[1], 0);
6903 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6904 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 }]);
6905 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6906 assert_eq!(events_4.len(), 1);
6908 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6910 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, .. } } => {
6911 assert!(update_add_htlcs.is_empty());
6912 assert!(update_fulfill_htlcs.is_empty());
6913 assert_eq!(update_fail_htlcs.len(), 1);
6914 assert!(update_fail_malformed_htlcs.is_empty());
6915 assert!(update_fee.is_none());
6917 _ => panic!("Unexpected event"),
6920 check_added_monitors!(nodes[1], 1);
6924 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6925 let chanmon_cfgs = create_chanmon_cfgs(3);
6926 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6927 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6928 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6929 create_announced_chan_between_nodes(&nodes, 0, 1);
6930 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6932 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6935 let mut payment_event = {
6936 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6937 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6938 check_added_monitors!(nodes[0], 1);
6939 SendEvent::from_node(&nodes[0])
6942 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6943 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6944 expect_pending_htlcs_forwardable!(nodes[1]);
6945 check_added_monitors!(nodes[1], 1);
6946 payment_event = SendEvent::from_node(&nodes[1]);
6947 assert_eq!(payment_event.msgs.len(), 1);
6950 payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6951 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6952 check_added_monitors!(nodes[2], 0);
6953 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6955 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6956 assert_eq!(events_3.len(), 1);
6958 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6959 let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6960 // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6961 update_msg.failure_code |= 0x2000;
6963 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6964 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6966 _ => panic!("Unexpected event"),
6969 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6970 vec![HTLCDestination::NextHopChannel {
6971 node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6972 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6973 assert_eq!(events_4.len(), 1);
6974 check_added_monitors!(nodes[1], 1);
6977 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6978 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6979 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6981 _ => panic!("Unexpected event"),
6984 let events_5 = nodes[0].node.get_and_clear_pending_events();
6985 assert_eq!(events_5.len(), 2);
6987 // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6988 // the node originating the error to its next hop.
6990 Event::PaymentPathFailed { error_code, failure: PathFailure::OnPath { network_update: Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }) }, ..
6992 assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6993 assert!(is_permanent);
6994 assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
6996 _ => panic!("Unexpected event"),
6999 Event::PaymentFailed { payment_hash, .. } => {
7000 assert_eq!(payment_hash, our_payment_hash);
7002 _ => panic!("Unexpected event"),
7005 // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
7008 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7009 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7010 // 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
7011 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7013 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7014 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7015 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7016 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7017 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7018 let chan =create_announced_chan_between_nodes(&nodes, 0, 1);
7020 let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
7021 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context().holder_dust_limit_satoshis;
7023 // We route 2 dust-HTLCs between A and B
7024 let (_, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7025 let (_, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7026 route_payment(&nodes[0], &[&nodes[1]], 1000000);
7028 // Cache one local commitment tx as previous
7029 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7031 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7032 nodes[1].node.fail_htlc_backwards(&payment_hash_2);
7033 check_added_monitors!(nodes[1], 0);
7034 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7035 check_added_monitors!(nodes[1], 1);
7037 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7038 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7039 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7040 check_added_monitors!(nodes[0], 1);
7042 // Cache one local commitment tx as lastest
7043 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7045 let events = nodes[0].node.get_and_clear_pending_msg_events();
7047 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7048 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7050 _ => panic!("Unexpected event"),
7053 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7054 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7056 _ => panic!("Unexpected event"),
7059 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7060 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7061 if announce_latest {
7062 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7064 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7067 check_closed_broadcast!(nodes[0], true);
7068 check_added_monitors!(nodes[0], 1);
7069 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7071 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7072 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7073 let events = nodes[0].node.get_and_clear_pending_events();
7074 // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7075 assert_eq!(events.len(), 4);
7076 let mut first_failed = false;
7077 for event in events {
7079 Event::PaymentPathFailed { payment_hash, .. } => {
7080 if payment_hash == payment_hash_1 {
7081 assert!(!first_failed);
7082 first_failed = true;
7084 assert_eq!(payment_hash, payment_hash_2);
7087 Event::PaymentFailed { .. } => {}
7088 _ => panic!("Unexpected event"),
7094 fn test_failure_delay_dust_htlc_local_commitment() {
7095 do_test_failure_delay_dust_htlc_local_commitment(true);
7096 do_test_failure_delay_dust_htlc_local_commitment(false);
7099 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7100 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7101 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7102 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7103 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7104 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7105 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7107 let chanmon_cfgs = create_chanmon_cfgs(3);
7108 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7109 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7110 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7111 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
7113 let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
7114 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context().holder_dust_limit_satoshis;
7116 let (_payment_preimage_1, dust_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7117 let (_payment_preimage_2, non_dust_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7119 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7120 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7122 // We revoked bs_commitment_tx
7124 let (payment_preimage_3, ..) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7125 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7128 let mut timeout_tx = Vec::new();
7130 // We fail dust-HTLC 1 by broadcast of local commitment tx
7131 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7132 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7133 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7134 expect_payment_failed!(nodes[0], dust_hash, false);
7136 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7137 check_closed_broadcast!(nodes[0], true);
7138 check_added_monitors!(nodes[0], 1);
7139 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7140 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7141 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7142 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7143 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7144 mine_transaction(&nodes[0], &timeout_tx[0]);
7145 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7146 expect_payment_failed!(nodes[0], non_dust_hash, false);
7148 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7149 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7150 check_closed_broadcast!(nodes[0], true);
7151 check_added_monitors!(nodes[0], 1);
7152 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7153 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7155 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7156 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
7157 .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
7158 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
7159 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
7160 // dust HTLC should have been failed.
7161 expect_payment_failed!(nodes[0], dust_hash, false);
7164 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7166 assert_eq!(timeout_tx[0].lock_time.to_consensus_u32(), 11);
7168 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
7169 mine_transaction(&nodes[0], &timeout_tx[0]);
7170 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7171 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7172 expect_payment_failed!(nodes[0], non_dust_hash, false);
7177 fn test_sweep_outbound_htlc_failure_update() {
7178 do_test_sweep_outbound_htlc_failure_update(false, true);
7179 do_test_sweep_outbound_htlc_failure_update(false, false);
7180 do_test_sweep_outbound_htlc_failure_update(true, false);
7184 fn test_user_configurable_csv_delay() {
7185 // We test our channel constructors yield errors when we pass them absurd csv delay
7187 let mut low_our_to_self_config = UserConfig::default();
7188 low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
7189 let mut high_their_to_self_config = UserConfig::default();
7190 high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
7191 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7192 let chanmon_cfgs = create_chanmon_cfgs(2);
7193 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7194 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7195 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7197 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in OutboundV1Channel::new()
7198 if let Err(error) = OutboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7199 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[1].node.init_features(), 1000000, 1000000, 0,
7200 &low_our_to_self_config, 0, 42, None)
7203 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())); },
7204 _ => panic!("Unexpected event"),
7206 } else { assert!(false) }
7208 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in InboundV1Channel::new()
7209 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None, None).unwrap();
7210 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7211 open_channel.to_self_delay = 200;
7212 if let Err(error) = InboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7213 &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,
7214 &low_our_to_self_config, 0, &nodes[0].logger, /*is_0conf=*/false)
7217 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())); },
7218 _ => panic!("Unexpected event"),
7220 } else { assert!(false); }
7222 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7223 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None, None).unwrap();
7224 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()));
7225 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7226 accept_channel.to_self_delay = 200;
7227 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
7229 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7231 &ErrorAction::SendErrorMessage { ref msg } => {
7232 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()));
7233 reason_msg = msg.data.clone();
7237 } else { panic!(); }
7238 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg }, [nodes[1].node.get_our_node_id()], 1000000);
7240 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in InboundV1Channel::new()
7241 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None, None).unwrap();
7242 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7243 open_channel.to_self_delay = 200;
7244 if let Err(error) = InboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7245 &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,
7246 &high_their_to_self_config, 0, &nodes[0].logger, /*is_0conf=*/false)
7249 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())); },
7250 _ => panic!("Unexpected event"),
7252 } else { assert!(false); }
7256 fn test_check_htlc_underpaying() {
7257 // Send payment through A -> B but A is maliciously
7258 // sending a probe payment (i.e less than expected value0
7259 // to B, B should refuse payment.
7261 let chanmon_cfgs = create_chanmon_cfgs(2);
7262 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7263 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7264 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7266 // Create some initial channels
7267 create_announced_chan_between_nodes(&nodes, 0, 1);
7269 let scorer = test_utils::TestScorer::new();
7270 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7271 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
7272 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
7273 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 10_000);
7274 let route = get_route(&nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph.read_only(),
7275 None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes).unwrap();
7276 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7277 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, None).unwrap();
7278 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
7279 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
7280 check_added_monitors!(nodes[0], 1);
7282 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7283 assert_eq!(events.len(), 1);
7284 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7285 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7286 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7288 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7289 // and then will wait a second random delay before failing the HTLC back:
7290 expect_pending_htlcs_forwardable!(nodes[1]);
7291 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7293 // Node 3 is expecting payment of 100_000 but received 10_000,
7294 // it should fail htlc like we didn't know the preimage.
7295 nodes[1].node.process_pending_htlc_forwards();
7297 let events = nodes[1].node.get_and_clear_pending_msg_events();
7298 assert_eq!(events.len(), 1);
7299 let (update_fail_htlc, commitment_signed) = match events[0] {
7300 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 } } => {
7301 assert!(update_add_htlcs.is_empty());
7302 assert!(update_fulfill_htlcs.is_empty());
7303 assert_eq!(update_fail_htlcs.len(), 1);
7304 assert!(update_fail_malformed_htlcs.is_empty());
7305 assert!(update_fee.is_none());
7306 (update_fail_htlcs[0].clone(), commitment_signed)
7308 _ => panic!("Unexpected event"),
7310 check_added_monitors!(nodes[1], 1);
7312 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7313 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7315 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7316 let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
7317 expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
7318 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7322 fn test_announce_disable_channels() {
7323 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7324 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7326 let chanmon_cfgs = create_chanmon_cfgs(2);
7327 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7328 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7329 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7331 create_announced_chan_between_nodes(&nodes, 0, 1);
7332 create_announced_chan_between_nodes(&nodes, 1, 0);
7333 create_announced_chan_between_nodes(&nodes, 0, 1);
7336 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
7337 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
7339 for _ in 0..DISABLE_GOSSIP_TICKS + 1 {
7340 nodes[0].node.timer_tick_occurred();
7342 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7343 assert_eq!(msg_events.len(), 3);
7344 let mut chans_disabled = HashMap::new();
7345 for e in msg_events {
7347 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7348 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7349 // Check that each channel gets updated exactly once
7350 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7351 panic!("Generated ChannelUpdate for wrong chan!");
7354 _ => panic!("Unexpected event"),
7358 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
7359 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
7361 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7362 assert_eq!(reestablish_1.len(), 3);
7363 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
7364 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
7366 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7367 assert_eq!(reestablish_2.len(), 3);
7369 // Reestablish chan_1
7370 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7371 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7372 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7373 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7374 // Reestablish chan_2
7375 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7376 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7377 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7378 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7379 // Reestablish chan_3
7380 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7381 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7382 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7383 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7385 for _ in 0..ENABLE_GOSSIP_TICKS {
7386 nodes[0].node.timer_tick_occurred();
7388 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7389 nodes[0].node.timer_tick_occurred();
7390 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7391 assert_eq!(msg_events.len(), 3);
7392 for e in msg_events {
7394 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7395 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7396 match chans_disabled.remove(&msg.contents.short_channel_id) {
7397 // Each update should have a higher timestamp than the previous one, replacing
7399 Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7400 None => panic!("Generated ChannelUpdate for wrong chan!"),
7403 _ => panic!("Unexpected event"),
7406 // Check that each channel gets updated exactly once
7407 assert!(chans_disabled.is_empty());
7411 fn test_bump_penalty_txn_on_revoked_commitment() {
7412 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7413 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7415 let chanmon_cfgs = create_chanmon_cfgs(2);
7416 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7417 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7418 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7420 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7422 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7423 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7424 .with_bolt11_features(nodes[0].node.bolt11_invoice_features()).unwrap();
7425 let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000);
7426 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7428 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7429 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7430 assert_eq!(revoked_txn[0].output.len(), 4);
7431 assert_eq!(revoked_txn[0].input.len(), 1);
7432 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7433 let revoked_txid = revoked_txn[0].txid();
7435 let mut penalty_sum = 0;
7436 for outp in revoked_txn[0].output.iter() {
7437 if outp.script_pubkey.is_v0_p2wsh() {
7438 penalty_sum += outp.value;
7442 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7443 let header_114 = connect_blocks(&nodes[1], 14);
7445 // Actually revoke tx by claiming a HTLC
7446 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7447 connect_block(&nodes[1], &create_dummy_block(header_114, 42, vec![revoked_txn[0].clone()]));
7448 check_added_monitors!(nodes[1], 1);
7450 // One or more justice tx should have been broadcast, check it
7454 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7455 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7456 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7457 assert_eq!(node_txn[0].output.len(), 1);
7458 check_spends!(node_txn[0], revoked_txn[0]);
7459 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7460 feerate_1 = fee_1 * 1000 / node_txn[0].weight().to_wu();
7461 penalty_1 = node_txn[0].txid();
7465 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7466 connect_blocks(&nodes[1], 15);
7467 let mut penalty_2 = penalty_1;
7468 let mut feerate_2 = 0;
7470 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7471 assert_eq!(node_txn.len(), 1);
7472 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7473 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7474 assert_eq!(node_txn[0].output.len(), 1);
7475 check_spends!(node_txn[0], revoked_txn[0]);
7476 penalty_2 = node_txn[0].txid();
7477 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7478 assert_ne!(penalty_2, penalty_1);
7479 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7480 feerate_2 = fee_2 * 1000 / node_txn[0].weight().to_wu();
7481 // Verify 25% bump heuristic
7482 assert!(feerate_2 * 100 >= feerate_1 * 125);
7486 assert_ne!(feerate_2, 0);
7488 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7489 connect_blocks(&nodes[1], 1);
7491 let mut feerate_3 = 0;
7493 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7494 assert_eq!(node_txn.len(), 1);
7495 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7496 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7497 assert_eq!(node_txn[0].output.len(), 1);
7498 check_spends!(node_txn[0], revoked_txn[0]);
7499 penalty_3 = node_txn[0].txid();
7500 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7501 assert_ne!(penalty_3, penalty_2);
7502 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7503 feerate_3 = fee_3 * 1000 / node_txn[0].weight().to_wu();
7504 // Verify 25% bump heuristic
7505 assert!(feerate_3 * 100 >= feerate_2 * 125);
7509 assert_ne!(feerate_3, 0);
7511 nodes[1].node.get_and_clear_pending_events();
7512 nodes[1].node.get_and_clear_pending_msg_events();
7516 fn test_bump_penalty_txn_on_revoked_htlcs() {
7517 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7518 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7520 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7521 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7522 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7523 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7524 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7526 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7527 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7528 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 50).with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
7529 let scorer = test_utils::TestScorer::new();
7530 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7531 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 3_000_000);
7532 let route = get_route(&nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph.read_only(), None,
7533 nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes).unwrap();
7534 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7535 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50)
7536 .with_bolt11_features(nodes[0].node.bolt11_invoice_features()).unwrap();
7537 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 3_000_000);
7538 let route = get_route(&nodes[1].node.get_our_node_id(), &route_params, &nodes[1].network_graph.read_only(), None,
7539 nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes).unwrap();
7540 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7542 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7543 assert_eq!(revoked_local_txn[0].input.len(), 1);
7544 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7546 // Revoke local commitment tx
7547 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7549 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7550 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone()]));
7551 check_closed_broadcast!(nodes[1], true);
7552 check_added_monitors!(nodes[1], 1);
7553 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 1000000);
7554 connect_blocks(&nodes[1], 50); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7556 let revoked_htlc_txn = {
7557 let txn = nodes[1].tx_broadcaster.unique_txn_broadcast();
7558 assert_eq!(txn.len(), 2);
7560 assert_eq!(txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7561 assert_eq!(txn[0].input.len(), 1);
7562 check_spends!(txn[0], revoked_local_txn[0]);
7564 assert_eq!(txn[1].input.len(), 1);
7565 assert_eq!(txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7566 assert_eq!(txn[1].output.len(), 1);
7567 check_spends!(txn[1], revoked_local_txn[0]);
7572 // Broadcast set of revoked txn on A
7573 let hash_128 = connect_blocks(&nodes[0], 40);
7574 let block_11 = create_dummy_block(hash_128, 42, vec![revoked_local_txn[0].clone()]);
7575 connect_block(&nodes[0], &block_11);
7576 let block_129 = create_dummy_block(block_11.block_hash(), 42, vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()]);
7577 connect_block(&nodes[0], &block_129);
7578 let events = nodes[0].node.get_and_clear_pending_events();
7579 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7580 match events.last().unwrap() {
7581 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7582 _ => panic!("Unexpected event"),
7588 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7589 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7590 // Verify claim tx are spending revoked HTLC txn
7592 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7593 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7594 // which are included in the same block (they are broadcasted because we scan the
7595 // transactions linearly and generate claims as we go, they likely should be removed in the
7597 assert_eq!(node_txn[0].input.len(), 1);
7598 check_spends!(node_txn[0], revoked_local_txn[0]);
7599 assert_eq!(node_txn[1].input.len(), 1);
7600 check_spends!(node_txn[1], revoked_local_txn[0]);
7601 assert_eq!(node_txn[2].input.len(), 1);
7602 check_spends!(node_txn[2], revoked_local_txn[0]);
7604 // Each of the three justice transactions claim a separate (single) output of the three
7605 // available, which we check here:
7606 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7607 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7608 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7610 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7611 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7613 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7614 // output, checked above).
7615 assert_eq!(node_txn[3].input.len(), 2);
7616 assert_eq!(node_txn[3].output.len(), 1);
7617 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7619 first = node_txn[3].txid();
7620 // Store both feerates for later comparison
7621 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7622 feerate_1 = fee_1 * 1000 / node_txn[3].weight().to_wu();
7623 penalty_txn = vec![node_txn[2].clone()];
7627 // Connect one more block to see if bumped penalty are issued for HTLC txn
7628 let block_130 = create_dummy_block(block_129.block_hash(), 42, penalty_txn);
7629 connect_block(&nodes[0], &block_130);
7630 let block_131 = create_dummy_block(block_130.block_hash(), 42, Vec::new());
7631 connect_block(&nodes[0], &block_131);
7633 // Few more blocks to confirm penalty txn
7634 connect_blocks(&nodes[0], 4);
7635 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7636 let header_144 = connect_blocks(&nodes[0], 9);
7638 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7639 assert_eq!(node_txn.len(), 1);
7641 assert_eq!(node_txn[0].input.len(), 2);
7642 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7643 // Verify bumped tx is different and 25% bump heuristic
7644 assert_ne!(first, node_txn[0].txid());
7645 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7646 let feerate_2 = fee_2 * 1000 / node_txn[0].weight().to_wu();
7647 assert!(feerate_2 * 100 > feerate_1 * 125);
7648 let txn = vec![node_txn[0].clone()];
7652 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7653 connect_block(&nodes[0], &create_dummy_block(header_144, 42, node_txn));
7654 connect_blocks(&nodes[0], 20);
7656 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7657 // We verify than no new transaction has been broadcast because previously
7658 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7659 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7660 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7661 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7662 // up bumped justice generation.
7663 assert_eq!(node_txn.len(), 0);
7666 check_closed_broadcast!(nodes[0], true);
7667 check_added_monitors!(nodes[0], 1);
7671 fn test_bump_penalty_txn_on_remote_commitment() {
7672 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7673 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7676 // Provide preimage for one
7677 // Check aggregation
7679 let chanmon_cfgs = create_chanmon_cfgs(2);
7680 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7681 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7682 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7684 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7685 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7686 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7688 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7689 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7690 assert_eq!(remote_txn[0].output.len(), 4);
7691 assert_eq!(remote_txn[0].input.len(), 1);
7692 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7694 // Claim a HTLC without revocation (provide B monitor with preimage)
7695 nodes[1].node.claim_funds(payment_preimage);
7696 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7697 mine_transaction(&nodes[1], &remote_txn[0]);
7698 check_added_monitors!(nodes[1], 2);
7699 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7701 // One or more claim tx should have been broadcast, check it
7705 let feerate_timeout;
7706 let feerate_preimage;
7708 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7709 // 3 transactions including:
7710 // preimage and timeout sweeps from remote commitment + preimage sweep bump
7711 assert_eq!(node_txn.len(), 3);
7712 assert_eq!(node_txn[0].input.len(), 1);
7713 assert_eq!(node_txn[1].input.len(), 1);
7714 assert_eq!(node_txn[2].input.len(), 1);
7715 check_spends!(node_txn[0], remote_txn[0]);
7716 check_spends!(node_txn[1], remote_txn[0]);
7717 check_spends!(node_txn[2], remote_txn[0]);
7719 preimage = node_txn[0].txid();
7720 let index = node_txn[0].input[0].previous_output.vout;
7721 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7722 feerate_preimage = fee * 1000 / node_txn[0].weight().to_wu();
7724 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7725 (node_txn[2].clone(), node_txn[1].clone())
7727 (node_txn[1].clone(), node_txn[2].clone())
7730 preimage_bump = preimage_bump_tx;
7731 check_spends!(preimage_bump, remote_txn[0]);
7732 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7734 timeout = timeout_tx.txid();
7735 let index = timeout_tx.input[0].previous_output.vout;
7736 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7737 feerate_timeout = fee * 1000 / timeout_tx.weight().to_wu();
7741 assert_ne!(feerate_timeout, 0);
7742 assert_ne!(feerate_preimage, 0);
7744 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7745 connect_blocks(&nodes[1], 1);
7747 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7748 assert_eq!(node_txn.len(), 1);
7749 assert_eq!(node_txn[0].input.len(), 1);
7750 assert_eq!(preimage_bump.input.len(), 1);
7751 check_spends!(node_txn[0], remote_txn[0]);
7752 check_spends!(preimage_bump, remote_txn[0]);
7754 let index = preimage_bump.input[0].previous_output.vout;
7755 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7756 let new_feerate = fee * 1000 / preimage_bump.weight().to_wu();
7757 assert!(new_feerate * 100 > feerate_timeout * 125);
7758 assert_ne!(timeout, preimage_bump.txid());
7760 let index = node_txn[0].input[0].previous_output.vout;
7761 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7762 let new_feerate = fee * 1000 / node_txn[0].weight().to_wu();
7763 assert!(new_feerate * 100 > feerate_preimage * 125);
7764 assert_ne!(preimage, node_txn[0].txid());
7769 nodes[1].node.get_and_clear_pending_events();
7770 nodes[1].node.get_and_clear_pending_msg_events();
7774 fn test_counterparty_raa_skip_no_crash() {
7775 // Previously, if our counterparty sent two RAAs in a row without us having provided a
7776 // commitment transaction, we would have happily carried on and provided them the next
7777 // commitment transaction based on one RAA forward. This would probably eventually have led to
7778 // channel closure, but it would not have resulted in funds loss. Still, our
7779 // TestChannelSigner would have panicked as it doesn't like jumps into the future. Here, we
7780 // check simply that the channel is closed in response to such an RAA, but don't check whether
7781 // we decide to punish our counterparty for revoking their funds (as we don't currently
7783 let chanmon_cfgs = create_chanmon_cfgs(2);
7784 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7785 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7786 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7787 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7789 let per_commitment_secret;
7790 let next_per_commitment_point;
7792 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7793 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7794 let keys = guard.channel_by_id.get_mut(&channel_id).map(
7795 |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
7796 ).flatten().unwrap().get_signer();
7798 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7800 // Make signer believe we got a counterparty signature, so that it allows the revocation
7801 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7802 per_commitment_secret = keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7804 // Must revoke without gaps
7805 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7806 keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7808 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7809 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7810 &SecretKey::from_slice(&keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7813 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7814 &msgs::RevokeAndACK {
7816 per_commitment_secret,
7817 next_per_commitment_point,
7819 next_local_nonce: None,
7821 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7822 check_added_monitors!(nodes[1], 1);
7823 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() }
7824 , [nodes[0].node.get_our_node_id()], 100000);
7828 fn test_bump_txn_sanitize_tracking_maps() {
7829 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7830 // verify we clean then right after expiration of ANTI_REORG_DELAY.
7832 let chanmon_cfgs = create_chanmon_cfgs(2);
7833 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7834 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7835 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7837 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7838 // Lock HTLC in both directions
7839 let (payment_preimage_1, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7840 let (_, payment_hash_2, ..) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7842 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7843 assert_eq!(revoked_local_txn[0].input.len(), 1);
7844 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7846 // Revoke local commitment tx
7847 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7849 // Broadcast set of revoked txn on A
7850 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7851 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7852 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7854 mine_transaction(&nodes[0], &revoked_local_txn[0]);
7855 check_closed_broadcast!(nodes[0], true);
7856 check_added_monitors!(nodes[0], 1);
7857 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 1000000);
7859 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7860 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7861 check_spends!(node_txn[0], revoked_local_txn[0]);
7862 check_spends!(node_txn[1], revoked_local_txn[0]);
7863 check_spends!(node_txn[2], revoked_local_txn[0]);
7864 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7868 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, penalty_txn));
7869 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7871 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7872 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7873 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7878 fn test_channel_conf_timeout() {
7879 // Tests that, for inbound channels, we give up on them if the funding transaction does not
7880 // confirm within 2016 blocks, as recommended by BOLT 2.
7881 let chanmon_cfgs = create_chanmon_cfgs(2);
7882 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7883 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7884 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7886 let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7888 // The outbound node should wait forever for confirmation:
7889 // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7890 // copied here instead of directly referencing the constant.
7891 connect_blocks(&nodes[0], 2016);
7892 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7894 // The inbound node should fail the channel after exactly 2016 blocks
7895 connect_blocks(&nodes[1], 2015);
7896 check_added_monitors!(nodes[1], 0);
7897 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7899 connect_blocks(&nodes[1], 1);
7900 check_added_monitors!(nodes[1], 1);
7901 check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut, [nodes[0].node.get_our_node_id()], 1000000);
7902 let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7903 assert_eq!(close_ev.len(), 1);
7905 MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { ref msg }, ref node_id } => {
7906 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7907 assert_eq!(msg.as_ref().unwrap().data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7909 _ => panic!("Unexpected event"),
7914 fn test_override_channel_config() {
7915 let chanmon_cfgs = create_chanmon_cfgs(2);
7916 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7917 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7918 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7920 // Node0 initiates a channel to node1 using the override config.
7921 let mut override_config = UserConfig::default();
7922 override_config.channel_handshake_config.our_to_self_delay = 200;
7924 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, None, Some(override_config)).unwrap();
7926 // Assert the channel created by node0 is using the override config.
7927 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7928 assert_eq!(res.channel_flags, 0);
7929 assert_eq!(res.to_self_delay, 200);
7933 fn test_override_0msat_htlc_minimum() {
7934 let mut zero_config = UserConfig::default();
7935 zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7936 let chanmon_cfgs = create_chanmon_cfgs(2);
7937 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7938 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7939 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7941 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, None, Some(zero_config)).unwrap();
7942 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7943 assert_eq!(res.htlc_minimum_msat, 1);
7945 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7946 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7947 assert_eq!(res.htlc_minimum_msat, 1);
7951 fn test_channel_update_has_correct_htlc_maximum_msat() {
7952 // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7953 // Bolt 7 specifies that if present `htlc_maximum_msat`:
7954 // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7955 // 90% of the `channel_value`.
7956 // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7958 let mut config_30_percent = UserConfig::default();
7959 config_30_percent.channel_handshake_config.announced_channel = true;
7960 config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7961 let mut config_50_percent = UserConfig::default();
7962 config_50_percent.channel_handshake_config.announced_channel = true;
7963 config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7964 let mut config_95_percent = UserConfig::default();
7965 config_95_percent.channel_handshake_config.announced_channel = true;
7966 config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7967 let mut config_100_percent = UserConfig::default();
7968 config_100_percent.channel_handshake_config.announced_channel = true;
7969 config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7971 let chanmon_cfgs = create_chanmon_cfgs(4);
7972 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7973 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)]);
7974 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7976 let channel_value_satoshis = 100000;
7977 let channel_value_msat = channel_value_satoshis * 1000;
7978 let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7979 let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7980 let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7982 let (node_0_chan_update, node_1_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
7983 let (node_2_chan_update, node_3_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
7985 // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7986 // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7987 assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7988 // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7989 // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7990 assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7992 // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7993 // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7995 assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7996 // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7997 // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7999 assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
8003 fn test_manually_accept_inbound_channel_request() {
8004 let mut manually_accept_conf = UserConfig::default();
8005 manually_accept_conf.manually_accept_inbound_channels = true;
8006 let chanmon_cfgs = create_chanmon_cfgs(2);
8007 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8008 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8009 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8011 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, Some(manually_accept_conf)).unwrap();
8012 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8014 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
8016 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8017 // accepting the inbound channel request.
8018 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8020 let events = nodes[1].node.get_and_clear_pending_events();
8022 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8023 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
8025 _ => panic!("Unexpected event"),
8028 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8029 assert_eq!(accept_msg_ev.len(), 1);
8031 match accept_msg_ev[0] {
8032 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8033 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8035 _ => panic!("Unexpected event"),
8038 nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8040 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8041 assert_eq!(close_msg_ev.len(), 1);
8043 let events = nodes[1].node.get_and_clear_pending_events();
8045 Event::ChannelClosed { user_channel_id, .. } => {
8046 assert_eq!(user_channel_id, 23);
8048 _ => panic!("Unexpected event"),
8053 fn test_manually_reject_inbound_channel_request() {
8054 let mut manually_accept_conf = UserConfig::default();
8055 manually_accept_conf.manually_accept_inbound_channels = true;
8056 let chanmon_cfgs = create_chanmon_cfgs(2);
8057 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8058 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8059 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8061 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, Some(manually_accept_conf)).unwrap();
8062 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8064 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
8066 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8067 // rejecting the inbound channel request.
8068 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8070 let events = nodes[1].node.get_and_clear_pending_events();
8072 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8073 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8075 _ => panic!("Unexpected event"),
8078 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8079 assert_eq!(close_msg_ev.len(), 1);
8081 match close_msg_ev[0] {
8082 MessageSendEvent::HandleError { ref node_id, .. } => {
8083 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8085 _ => panic!("Unexpected event"),
8088 // There should be no more events to process, as the channel was never opened.
8089 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
8093 fn test_can_not_accept_inbound_channel_twice() {
8094 let mut manually_accept_conf = UserConfig::default();
8095 manually_accept_conf.manually_accept_inbound_channels = true;
8096 let chanmon_cfgs = create_chanmon_cfgs(2);
8097 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8098 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8099 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8101 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, Some(manually_accept_conf)).unwrap();
8102 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8104 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
8106 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8107 // accepting the inbound channel request.
8108 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8110 let events = nodes[1].node.get_and_clear_pending_events();
8112 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8113 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
8114 let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
8116 Err(APIError::APIMisuseError { err }) => {
8117 assert_eq!(err, "No such channel awaiting to be accepted.");
8119 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8120 Err(e) => panic!("Unexpected Error {:?}", e),
8123 _ => panic!("Unexpected event"),
8126 // Ensure that the channel wasn't closed after attempting to accept it twice.
8127 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8128 assert_eq!(accept_msg_ev.len(), 1);
8130 match accept_msg_ev[0] {
8131 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8132 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8134 _ => panic!("Unexpected event"),
8139 fn test_can_not_accept_unknown_inbound_channel() {
8140 let chanmon_cfg = create_chanmon_cfgs(2);
8141 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8142 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8143 let nodes = create_network(2, &node_cfg, &node_chanmgr);
8145 let unknown_channel_id = ChannelId::new_zero();
8146 let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
8148 Err(APIError::APIMisuseError { err }) => {
8149 assert_eq!(err, "No such channel awaiting to be accepted.");
8151 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8152 Err(e) => panic!("Unexpected Error: {:?}", e),
8157 fn test_onion_value_mpp_set_calculation() {
8158 // Test that we use the onion value `amt_to_forward` when
8159 // calculating whether we've reached the `total_msat` of an MPP
8160 // by having a routing node forward more than `amt_to_forward`
8161 // and checking that the receiving node doesn't generate
8162 // a PaymentClaimable event too early
8164 let chanmon_cfgs = create_chanmon_cfgs(node_count);
8165 let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8166 let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8167 let mut nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8169 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8170 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8171 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8172 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8174 let total_msat = 100_000;
8175 let expected_paths: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
8176 let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], total_msat);
8177 let sample_path = route.paths.pop().unwrap();
8179 let mut path_1 = sample_path.clone();
8180 path_1.hops[0].pubkey = nodes[1].node.get_our_node_id();
8181 path_1.hops[0].short_channel_id = chan_1_id;
8182 path_1.hops[1].pubkey = nodes[3].node.get_our_node_id();
8183 path_1.hops[1].short_channel_id = chan_3_id;
8184 path_1.hops[1].fee_msat = 100_000;
8185 route.paths.push(path_1);
8187 let mut path_2 = sample_path.clone();
8188 path_2.hops[0].pubkey = nodes[2].node.get_our_node_id();
8189 path_2.hops[0].short_channel_id = chan_2_id;
8190 path_2.hops[1].pubkey = nodes[3].node.get_our_node_id();
8191 path_2.hops[1].short_channel_id = chan_4_id;
8192 path_2.hops[1].fee_msat = 1_000;
8193 route.paths.push(path_2);
8196 let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
8197 let onion_session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
8198 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8199 nodes[0].node.test_send_payment_internal(&route, our_payment_hash,
8200 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8201 check_added_monitors!(nodes[0], expected_paths.len());
8203 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8204 assert_eq!(events.len(), expected_paths.len());
8207 let ev = remove_first_msg_event_to_node(&expected_paths[0][0].node.get_our_node_id(), &mut events);
8208 let mut payment_event = SendEvent::from_event(ev);
8209 let mut prev_node = &nodes[0];
8211 for (idx, &node) in expected_paths[0].iter().enumerate() {
8212 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
8214 if idx == 0 { // routing node
8215 let session_priv = [3; 32];
8216 let height = nodes[0].best_block_info().1;
8217 let session_priv = SecretKey::from_slice(&session_priv).unwrap();
8218 let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
8219 let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], 100_000,
8220 RecipientOnionFields::secret_only(our_payment_secret), height + 1, &None).unwrap();
8221 // Edit amt_to_forward to simulate the sender having set
8222 // the final amount and the routing node taking less fee
8223 if let msgs::OutboundOnionPayload::Receive {
8224 ref mut sender_intended_htlc_amt_msat, ..
8225 } = onion_payloads[1] {
8226 *sender_intended_htlc_amt_msat = 99_000;
8228 let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
8229 payment_event.msgs[0].onion_routing_packet = new_onion_packet;
8232 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
8233 check_added_monitors!(node, 0);
8234 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
8235 expect_pending_htlcs_forwardable!(node);
8238 let mut events_2 = node.node.get_and_clear_pending_msg_events();
8239 assert_eq!(events_2.len(), 1);
8240 check_added_monitors!(node, 1);
8241 payment_event = SendEvent::from_event(events_2.remove(0));
8242 assert_eq!(payment_event.msgs.len(), 1);
8244 let events_2 = node.node.get_and_clear_pending_events();
8245 assert!(events_2.is_empty());
8252 let ev = remove_first_msg_event_to_node(&expected_paths[1][0].node.get_our_node_id(), &mut events);
8253 pass_along_path(&nodes[0], expected_paths[1], 101_000, our_payment_hash.clone(), Some(our_payment_secret), ev, true, None);
8255 claim_payment_along_route(&nodes[0], expected_paths, false, our_payment_preimage);
8258 fn do_test_overshoot_mpp(msat_amounts: &[u64], total_msat: u64) {
8260 let routing_node_count = msat_amounts.len();
8261 let node_count = routing_node_count + 2;
8263 let chanmon_cfgs = create_chanmon_cfgs(node_count);
8264 let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8265 let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8266 let nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8271 // Create channels for each amount
8272 let mut expected_paths = Vec::with_capacity(routing_node_count);
8273 let mut src_chan_ids = Vec::with_capacity(routing_node_count);
8274 let mut dst_chan_ids = Vec::with_capacity(routing_node_count);
8275 for i in 0..routing_node_count {
8276 let routing_node = 2 + i;
8277 let src_chan_id = create_announced_chan_between_nodes(&nodes, src_idx, routing_node).0.contents.short_channel_id;
8278 src_chan_ids.push(src_chan_id);
8279 let dst_chan_id = create_announced_chan_between_nodes(&nodes, routing_node, dst_idx).0.contents.short_channel_id;
8280 dst_chan_ids.push(dst_chan_id);
8281 let path = vec![&nodes[routing_node], &nodes[dst_idx]];
8282 expected_paths.push(path);
8284 let expected_paths: Vec<&[&Node]> = expected_paths.iter().map(|route| route.as_slice()).collect();
8286 // Create a route for each amount
8287 let example_amount = 100000;
8288 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);
8289 let sample_path = route.paths.pop().unwrap();
8290 for i in 0..routing_node_count {
8291 let routing_node = 2 + i;
8292 let mut path = sample_path.clone();
8293 path.hops[0].pubkey = nodes[routing_node].node.get_our_node_id();
8294 path.hops[0].short_channel_id = src_chan_ids[i];
8295 path.hops[1].pubkey = nodes[dst_idx].node.get_our_node_id();
8296 path.hops[1].short_channel_id = dst_chan_ids[i];
8297 path.hops[1].fee_msat = msat_amounts[i];
8298 route.paths.push(path);
8301 // Send payment with manually set total_msat
8302 let payment_id = PaymentId(nodes[src_idx].keys_manager.backing.get_secure_random_bytes());
8303 let onion_session_privs = nodes[src_idx].node.test_add_new_pending_payment(our_payment_hash,
8304 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8305 nodes[src_idx].node.test_send_payment_internal(&route, our_payment_hash,
8306 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8307 check_added_monitors!(nodes[src_idx], expected_paths.len());
8309 let mut events = nodes[src_idx].node.get_and_clear_pending_msg_events();
8310 assert_eq!(events.len(), expected_paths.len());
8311 let mut amount_received = 0;
8312 for (path_idx, expected_path) in expected_paths.iter().enumerate() {
8313 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
8315 let current_path_amount = msat_amounts[path_idx];
8316 amount_received += current_path_amount;
8317 let became_claimable_now = amount_received >= total_msat && amount_received - current_path_amount < total_msat;
8318 pass_along_path(&nodes[src_idx], expected_path, amount_received, our_payment_hash.clone(), Some(our_payment_secret), ev, became_claimable_now, None);
8321 claim_payment_along_route(&nodes[src_idx], &expected_paths, false, our_payment_preimage);
8325 fn test_overshoot_mpp() {
8326 do_test_overshoot_mpp(&[100_000, 101_000], 200_000);
8327 do_test_overshoot_mpp(&[100_000, 10_000, 100_000], 200_000);
8331 fn test_simple_mpp() {
8332 // Simple test of sending a multi-path payment.
8333 let chanmon_cfgs = create_chanmon_cfgs(4);
8334 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8335 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8336 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8338 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8339 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8340 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8341 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8343 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8344 let path = route.paths[0].clone();
8345 route.paths.push(path);
8346 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
8347 route.paths[0].hops[0].short_channel_id = chan_1_id;
8348 route.paths[0].hops[1].short_channel_id = chan_3_id;
8349 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
8350 route.paths[1].hops[0].short_channel_id = chan_2_id;
8351 route.paths[1].hops[1].short_channel_id = chan_4_id;
8352 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8353 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8357 fn test_preimage_storage() {
8358 // Simple test of payment preimage storage allowing no client-side storage to claim payments
8359 let chanmon_cfgs = create_chanmon_cfgs(2);
8360 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8361 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8362 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8364 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8367 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
8368 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8369 nodes[0].node.send_payment_with_route(&route, payment_hash,
8370 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8371 check_added_monitors!(nodes[0], 1);
8372 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8373 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8374 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8375 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8377 // Note that after leaving the above scope we have no knowledge of any arguments or return
8378 // values from previous calls.
8379 expect_pending_htlcs_forwardable!(nodes[1]);
8380 let events = nodes[1].node.get_and_clear_pending_events();
8381 assert_eq!(events.len(), 1);
8383 Event::PaymentClaimable { ref purpose, .. } => {
8385 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8386 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8388 _ => panic!("expected PaymentPurpose::InvoicePayment")
8391 _ => panic!("Unexpected event"),
8396 fn test_bad_secret_hash() {
8397 // Simple test of unregistered payment hash/invalid payment secret handling
8398 let chanmon_cfgs = create_chanmon_cfgs(2);
8399 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8400 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8401 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8403 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8405 let random_payment_hash = PaymentHash([42; 32]);
8406 let random_payment_secret = PaymentSecret([43; 32]);
8407 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8408 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8410 // All the below cases should end up being handled exactly identically, so we macro the
8411 // resulting events.
8412 macro_rules! handle_unknown_invalid_payment_data {
8413 ($payment_hash: expr) => {
8414 check_added_monitors!(nodes[0], 1);
8415 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8416 let payment_event = SendEvent::from_event(events.pop().unwrap());
8417 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8418 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8420 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8421 // again to process the pending backwards-failure of the HTLC
8422 expect_pending_htlcs_forwardable!(nodes[1]);
8423 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8424 check_added_monitors!(nodes[1], 1);
8426 // We should fail the payment back
8427 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8428 match events.pop().unwrap() {
8429 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8430 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8431 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8433 _ => panic!("Unexpected event"),
8438 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8439 // Error data is the HTLC value (100,000) and current block height
8440 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8442 // Send a payment with the right payment hash but the wrong payment secret
8443 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
8444 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8445 handle_unknown_invalid_payment_data!(our_payment_hash);
8446 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8448 // Send a payment with a random payment hash, but the right payment secret
8449 nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8450 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8451 handle_unknown_invalid_payment_data!(random_payment_hash);
8452 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8454 // Send a payment with a random payment hash and random payment secret
8455 nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8456 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8457 handle_unknown_invalid_payment_data!(random_payment_hash);
8458 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8462 fn test_update_err_monitor_lockdown() {
8463 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8464 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8465 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8468 // This scenario may happen in a watchtower setup, where watchtower process a block height
8469 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8470 // commitment at same time.
8472 let chanmon_cfgs = create_chanmon_cfgs(2);
8473 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8474 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8475 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8477 // Create some initial channel
8478 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8479 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8481 // Rebalance the network to generate htlc in the two directions
8482 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8484 // Route a HTLC from node 0 to node 1 (but don't settle)
8485 let (preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8487 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8488 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8489 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8490 let persister = test_utils::TestPersister::new();
8493 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8494 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8495 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8496 assert!(new_monitor == *monitor);
8499 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);
8500 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), Ok(ChannelMonitorUpdateStatus::Completed));
8503 let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8504 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8505 // transaction lock time requirements here.
8506 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 200));
8507 watchtower.chain_monitor.block_connected(&block, 200);
8509 // Try to update ChannelMonitor
8510 nodes[1].node.claim_funds(preimage);
8511 check_added_monitors!(nodes[1], 1);
8512 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8514 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8515 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8516 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8518 let mut node_0_per_peer_lock;
8519 let mut node_0_peer_state_lock;
8520 if let ChannelPhase::Funded(ref mut channel) = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2) {
8521 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8522 assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::InProgress);
8523 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8524 } else { assert!(false); }
8529 // Our local monitor is in-sync and hasn't processed yet timeout
8530 check_added_monitors!(nodes[0], 1);
8531 let events = nodes[0].node.get_and_clear_pending_events();
8532 assert_eq!(events.len(), 1);
8536 fn test_concurrent_monitor_claim() {
8537 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8538 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8539 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8540 // state N+1 confirms. Alice claims output from state N+1.
8542 let chanmon_cfgs = create_chanmon_cfgs(2);
8543 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8544 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8545 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8547 // Create some initial channel
8548 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8549 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8551 // Rebalance the network to generate htlc in the two directions
8552 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8554 // Route a HTLC from node 0 to node 1 (but don't settle)
8555 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8557 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8558 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8559 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8560 let persister = test_utils::TestPersister::new();
8561 let alice_broadcaster = test_utils::TestBroadcaster::with_blocks(
8562 Arc::new(Mutex::new(nodes[0].blocks.lock().unwrap().clone())),
8564 let watchtower_alice = {
8566 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8567 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8568 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8569 assert!(new_monitor == *monitor);
8572 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &alice_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8573 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), Ok(ChannelMonitorUpdateStatus::Completed));
8576 let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8577 // Make Alice aware of enough blocks that it doesn't think we're violating transaction lock time
8578 // requirements here.
8579 const HTLC_TIMEOUT_BROADCAST: u32 = CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS;
8580 alice_broadcaster.blocks.lock().unwrap().resize((HTLC_TIMEOUT_BROADCAST) as usize, (block.clone(), HTLC_TIMEOUT_BROADCAST));
8581 watchtower_alice.chain_monitor.block_connected(&block, HTLC_TIMEOUT_BROADCAST);
8583 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8585 let mut txn = alice_broadcaster.txn_broadcast();
8586 assert_eq!(txn.len(), 2);
8587 check_spends!(txn[0], chan_1.3);
8588 check_spends!(txn[1], txn[0]);
8591 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8592 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8593 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8594 let persister = test_utils::TestPersister::new();
8595 let bob_broadcaster = test_utils::TestBroadcaster::with_blocks(Arc::clone(&alice_broadcaster.blocks));
8596 let watchtower_bob = {
8598 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8599 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8600 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8601 assert!(new_monitor == *monitor);
8604 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &bob_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8605 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), Ok(ChannelMonitorUpdateStatus::Completed));
8608 watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST - 1);
8610 // Route another payment to generate another update with still previous HTLC pending
8611 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8612 nodes[1].node.send_payment_with_route(&route, payment_hash,
8613 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8614 check_added_monitors!(nodes[1], 1);
8616 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8617 assert_eq!(updates.update_add_htlcs.len(), 1);
8618 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8620 let mut node_0_per_peer_lock;
8621 let mut node_0_peer_state_lock;
8622 if let ChannelPhase::Funded(ref mut channel) = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2) {
8623 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8624 // Watchtower Alice should already have seen the block and reject the update
8625 assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::InProgress);
8626 assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8627 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8628 } else { assert!(false); }
8633 // Our local monitor is in-sync and hasn't processed yet timeout
8634 check_added_monitors!(nodes[0], 1);
8636 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8637 watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST);
8639 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8642 let mut txn = bob_broadcaster.txn_broadcast();
8643 assert_eq!(txn.len(), 2);
8644 bob_state_y = txn.remove(0);
8647 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8648 let height = HTLC_TIMEOUT_BROADCAST + 1;
8649 connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
8650 check_closed_broadcast(&nodes[0], 1, true);
8651 check_closed_event!(&nodes[0], 1, ClosureReason::HolderForceClosed, false,
8652 [nodes[1].node.get_our_node_id()], 100000);
8653 watchtower_alice.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, vec![bob_state_y.clone()]), height);
8654 check_added_monitors(&nodes[0], 1);
8656 let htlc_txn = alice_broadcaster.txn_broadcast();
8657 assert_eq!(htlc_txn.len(), 1);
8658 check_spends!(htlc_txn[0], bob_state_y);
8663 fn test_pre_lockin_no_chan_closed_update() {
8664 // Test that if a peer closes a channel in response to a funding_created message we don't
8665 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8668 // Doing so would imply a channel monitor update before the initial channel monitor
8669 // registration, violating our API guarantees.
8671 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8672 // then opening a second channel with the same funding output as the first (which is not
8673 // rejected because the first channel does not exist in the ChannelManager) and closing it
8674 // before receiving funding_signed.
8675 let chanmon_cfgs = create_chanmon_cfgs(2);
8676 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8677 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8678 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8680 // Create an initial channel
8681 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
8682 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8683 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8684 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8685 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8687 // Move the first channel through the funding flow...
8688 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8690 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8691 check_added_monitors!(nodes[0], 0);
8693 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8694 let channel_id = ChannelId::v1_from_funding_outpoint(crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index });
8695 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8696 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8697 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("Hi".to_string()) }, true,
8698 [nodes[1].node.get_our_node_id()], 100000);
8702 fn test_htlc_no_detection() {
8703 // This test is a mutation to underscore the detection logic bug we had
8704 // before #653. HTLC value routed is above the remaining balance, thus
8705 // inverting HTLC and `to_remote` output. HTLC will come second and
8706 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8707 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8708 // outputs order detection for correct spending children filtring.
8710 let chanmon_cfgs = create_chanmon_cfgs(2);
8711 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8712 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8713 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8715 // Create some initial channels
8716 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8718 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8719 let (_, our_payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8720 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8721 assert_eq!(local_txn[0].input.len(), 1);
8722 assert_eq!(local_txn[0].output.len(), 3);
8723 check_spends!(local_txn[0], chan_1.3);
8725 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8726 let block = create_dummy_block(nodes[0].best_block_hash(), 42, vec![local_txn[0].clone()]);
8727 connect_block(&nodes[0], &block);
8728 // We deliberately connect the local tx twice as this should provoke a failure calling
8729 // this test before #653 fix.
8730 chain::Listen::block_connected(&nodes[0].chain_monitor.chain_monitor, &block, nodes[0].best_block_info().1 + 1);
8731 check_closed_broadcast!(nodes[0], true);
8732 check_added_monitors!(nodes[0], 1);
8733 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
8734 connect_blocks(&nodes[0], TEST_FINAL_CLTV);
8736 let htlc_timeout = {
8737 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8738 assert_eq!(node_txn.len(), 1);
8739 assert_eq!(node_txn[0].input.len(), 1);
8740 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8741 check_spends!(node_txn[0], local_txn[0]);
8745 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![htlc_timeout.clone()]));
8746 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8747 expect_payment_failed!(nodes[0], our_payment_hash, false);
8750 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8751 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8752 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8753 // Carol, Alice would be the upstream node, and Carol the downstream.)
8755 // Steps of the test:
8756 // 1) Alice sends a HTLC to Carol through Bob.
8757 // 2) Carol doesn't settle the HTLC.
8758 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8759 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8760 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8761 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8762 // 5) Carol release the preimage to Bob off-chain.
8763 // 6) Bob claims the offered output on the broadcasted commitment.
8764 let chanmon_cfgs = create_chanmon_cfgs(3);
8765 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8766 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8767 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8769 // Create some initial channels
8770 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8771 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8773 // Steps (1) and (2):
8774 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8775 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8777 // Check that Alice's commitment transaction now contains an output for this HTLC.
8778 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8779 check_spends!(alice_txn[0], chan_ab.3);
8780 assert_eq!(alice_txn[0].output.len(), 2);
8781 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8782 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8783 assert_eq!(alice_txn.len(), 2);
8785 // Steps (3) and (4):
8786 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8787 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8788 let mut force_closing_node = 0; // Alice force-closes
8789 let mut counterparty_node = 1; // Bob if Alice force-closes
8792 if !broadcast_alice {
8793 force_closing_node = 1;
8794 counterparty_node = 0;
8796 nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8797 check_closed_broadcast!(nodes[force_closing_node], true);
8798 check_added_monitors!(nodes[force_closing_node], 1);
8799 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed, [nodes[counterparty_node].node.get_our_node_id()], 100000);
8800 if go_onchain_before_fulfill {
8801 let txn_to_broadcast = match broadcast_alice {
8802 true => alice_txn.clone(),
8803 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8805 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8806 if broadcast_alice {
8807 check_closed_broadcast!(nodes[1], true);
8808 check_added_monitors!(nodes[1], 1);
8809 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
8814 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8815 // process of removing the HTLC from their commitment transactions.
8816 nodes[2].node.claim_funds(payment_preimage);
8817 check_added_monitors!(nodes[2], 1);
8818 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8820 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8821 assert!(carol_updates.update_add_htlcs.is_empty());
8822 assert!(carol_updates.update_fail_htlcs.is_empty());
8823 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8824 assert!(carol_updates.update_fee.is_none());
8825 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8827 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8828 let went_onchain = go_onchain_before_fulfill || force_closing_node == 1;
8829 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if went_onchain { None } else { Some(1000) }, went_onchain, false);
8830 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8831 if !go_onchain_before_fulfill && broadcast_alice {
8832 let events = nodes[1].node.get_and_clear_pending_msg_events();
8833 assert_eq!(events.len(), 1);
8835 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8836 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8838 _ => panic!("Unexpected event"),
8841 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8842 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8843 // Carol<->Bob's updated commitment transaction info.
8844 check_added_monitors!(nodes[1], 2);
8846 let events = nodes[1].node.get_and_clear_pending_msg_events();
8847 assert_eq!(events.len(), 2);
8848 let bob_revocation = match events[0] {
8849 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8850 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8853 _ => panic!("Unexpected event"),
8855 let bob_updates = match events[1] {
8856 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8857 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8860 _ => panic!("Unexpected event"),
8863 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8864 check_added_monitors!(nodes[2], 1);
8865 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8866 check_added_monitors!(nodes[2], 1);
8868 let events = nodes[2].node.get_and_clear_pending_msg_events();
8869 assert_eq!(events.len(), 1);
8870 let carol_revocation = match events[0] {
8871 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8872 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8875 _ => panic!("Unexpected event"),
8877 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8878 check_added_monitors!(nodes[1], 1);
8880 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8881 // here's where we put said channel's commitment tx on-chain.
8882 let mut txn_to_broadcast = alice_txn.clone();
8883 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8884 if !go_onchain_before_fulfill {
8885 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8886 // If Bob was the one to force-close, he will have already passed these checks earlier.
8887 if broadcast_alice {
8888 check_closed_broadcast!(nodes[1], true);
8889 check_added_monitors!(nodes[1], 1);
8890 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
8892 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8893 if broadcast_alice {
8894 assert_eq!(bob_txn.len(), 1);
8895 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8897 if nodes[1].connect_style.borrow().updates_best_block_first() {
8898 assert_eq!(bob_txn.len(), 3);
8899 assert_eq!(bob_txn[0].txid(), bob_txn[1].txid());
8901 assert_eq!(bob_txn.len(), 2);
8903 check_spends!(bob_txn[0], chan_ab.3);
8908 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8909 // broadcasted commitment transaction.
8911 let script_weight = match broadcast_alice {
8912 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8913 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8915 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8916 // Bob force-closed and broadcasts the commitment transaction along with a
8917 // HTLC-output-claiming transaction.
8918 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8919 if broadcast_alice {
8920 assert_eq!(bob_txn.len(), 1);
8921 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8922 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8924 assert_eq!(bob_txn.len(), if nodes[1].connect_style.borrow().updates_best_block_first() { 3 } else { 2 });
8925 let htlc_tx = bob_txn.pop().unwrap();
8926 check_spends!(htlc_tx, txn_to_broadcast[0]);
8927 assert_eq!(htlc_tx.input[0].witness.last().unwrap().len(), script_weight);
8933 fn test_onchain_htlc_settlement_after_close() {
8934 do_test_onchain_htlc_settlement_after_close(true, true);
8935 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8936 do_test_onchain_htlc_settlement_after_close(true, false);
8937 do_test_onchain_htlc_settlement_after_close(false, false);
8941 fn test_duplicate_temporary_channel_id_from_different_peers() {
8942 // Tests that we can accept two different `OpenChannel` requests with the same
8943 // `temporary_channel_id`, as long as they are from different peers.
8944 let chanmon_cfgs = create_chanmon_cfgs(3);
8945 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8946 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8947 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8949 // Create an first channel channel
8950 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
8951 let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8953 // Create an second channel
8954 nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None, None).unwrap();
8955 let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8957 // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8958 // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8959 open_chan_msg_chan_2_0.temporary_channel_id = open_chan_msg_chan_1_0.temporary_channel_id;
8961 // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8962 // `temporary_channel_id` as they are from different peers.
8963 nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
8965 let events = nodes[0].node.get_and_clear_pending_msg_events();
8966 assert_eq!(events.len(), 1);
8968 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8969 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8970 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8972 _ => panic!("Unexpected event"),
8976 nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
8978 let events = nodes[0].node.get_and_clear_pending_msg_events();
8979 assert_eq!(events.len(), 1);
8981 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8982 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
8983 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8985 _ => panic!("Unexpected event"),
8991 fn test_peer_funding_sidechannel() {
8992 // Test that if a peer somehow learns which txid we'll use for our channel funding before we
8993 // receive `funding_transaction_generated` the peer cannot cause us to crash. We'd previously
8994 // assumed that LDK would receive `funding_transaction_generated` prior to our peer learning
8995 // the txid and panicked if the peer tried to open a redundant channel to us with the same
8996 // funding outpoint.
8998 // While this assumption is generally safe, some users may have out-of-band protocols where
8999 // they notify their LSP about a funding outpoint first, or this may be violated in the future
9000 // with collaborative transaction construction protocols, i.e. dual-funding.
9001 let chanmon_cfgs = create_chanmon_cfgs(3);
9002 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9003 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9004 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9006 let temp_chan_id_ab = exchange_open_accept_chan(&nodes[0], &nodes[1], 1_000_000, 0);
9007 let temp_chan_id_ca = exchange_open_accept_chan(&nodes[2], &nodes[0], 1_000_000, 0);
9009 let (_, tx, funding_output) =
9010 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9012 let cs_funding_events = nodes[2].node.get_and_clear_pending_events();
9013 assert_eq!(cs_funding_events.len(), 1);
9014 match cs_funding_events[0] {
9015 Event::FundingGenerationReady { .. } => {}
9016 _ => panic!("Unexpected event {:?}", cs_funding_events),
9019 nodes[2].node.funding_transaction_generated_unchecked(&temp_chan_id_ca, &nodes[0].node.get_our_node_id(), tx.clone(), funding_output.index).unwrap();
9020 let funding_created_msg = get_event_msg!(nodes[2], MessageSendEvent::SendFundingCreated, nodes[0].node.get_our_node_id());
9021 nodes[0].node.handle_funding_created(&nodes[2].node.get_our_node_id(), &funding_created_msg);
9022 get_event_msg!(nodes[0], MessageSendEvent::SendFundingSigned, nodes[2].node.get_our_node_id());
9023 expect_channel_pending_event(&nodes[0], &nodes[2].node.get_our_node_id());
9024 check_added_monitors!(nodes[0], 1);
9026 let res = nodes[0].node.funding_transaction_generated(&temp_chan_id_ab, &nodes[1].node.get_our_node_id(), tx.clone());
9027 let err_msg = format!("{:?}", res.unwrap_err());
9028 assert!(err_msg.contains("An existing channel using outpoint "));
9029 assert!(err_msg.contains(" is open with peer"));
9030 // Even though the last funding_transaction_generated errored, it still generated a
9031 // SendFundingCreated. However, when the peer responds with a funding_signed it will send the
9032 // appropriate error message.
9033 let as_funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9034 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &as_funding_created);
9035 check_added_monitors!(nodes[1], 1);
9036 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9037 let reason = ClosureReason::ProcessingError { err: format!("An existing channel using outpoint {} is open with peer {}", funding_output, nodes[2].node.get_our_node_id()), };
9038 check_closed_events(&nodes[0], &[ExpectedCloseEvent::from_id_reason(ChannelId::v1_from_funding_outpoint(funding_output), true, reason)]);
9040 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9041 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
9042 get_err_msg(&nodes[0], &nodes[1].node.get_our_node_id());
9046 fn test_duplicate_conflicting_funding_from_second_peer() {
9047 // Test that if a user tries to fund a channel with a funding outpoint they'd previously used
9048 // we don't try to remove the previous ChannelMonitor. This is largely a test to ensure we
9049 // don't regress in the fuzzer, as such funding getting passed our outpoint-matches checks
9050 // implies the user (and our counterparty) has reused cryptographic keys across channels, which
9051 // we require the user not do.
9052 let chanmon_cfgs = create_chanmon_cfgs(4);
9053 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9054 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9055 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9057 let temp_chan_id = exchange_open_accept_chan(&nodes[0], &nodes[1], 1_000_000, 0);
9059 let (_, tx, funding_output) =
9060 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9062 // Now that we have a funding outpoint, create a dummy `ChannelMonitor` and insert it into
9063 // nodes[0]'s ChainMonitor so that the initial `ChannelMonitor` write fails.
9064 let dummy_chan_id = create_chan_between_nodes(&nodes[2], &nodes[3]).3;
9065 let dummy_monitor = get_monitor!(nodes[2], dummy_chan_id).clone();
9066 nodes[0].chain_monitor.chain_monitor.watch_channel(funding_output, dummy_monitor).unwrap();
9068 nodes[0].node.funding_transaction_generated(&temp_chan_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9070 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9071 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9072 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9073 check_added_monitors!(nodes[1], 1);
9074 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9076 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9077 // At this point, the channel should be closed, after having generated one monitor write (the
9078 // watch_channel call which failed), but zero monitor updates.
9079 check_added_monitors!(nodes[0], 1);
9080 get_err_msg(&nodes[0], &nodes[1].node.get_our_node_id());
9081 let err_reason = ClosureReason::ProcessingError { err: "Channel funding outpoint was a duplicate".to_owned() };
9082 check_closed_events(&nodes[0], &[ExpectedCloseEvent::from_id_reason(funding_signed_msg.channel_id, true, err_reason)]);
9086 fn test_duplicate_funding_err_in_funding() {
9087 // Test that if we have a live channel with one peer, then another peer comes along and tries
9088 // to create a second channel with the same txid we'll fail and not overwrite the
9089 // outpoint_to_peer map in `ChannelManager`.
9091 // This was previously broken.
9092 let chanmon_cfgs = create_chanmon_cfgs(3);
9093 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9094 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9095 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9097 let (_, _, _, real_channel_id, funding_tx) = create_chan_between_nodes(&nodes[0], &nodes[1]);
9098 let real_chan_funding_txo = chain::transaction::OutPoint { txid: funding_tx.txid(), index: 0 };
9099 assert_eq!(ChannelId::v1_from_funding_outpoint(real_chan_funding_txo), real_channel_id);
9101 nodes[2].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
9102 let mut open_chan_msg = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9103 let node_c_temp_chan_id = open_chan_msg.temporary_channel_id;
9104 open_chan_msg.temporary_channel_id = real_channel_id;
9105 nodes[1].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg);
9106 let mut accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[2].node.get_our_node_id());
9107 accept_chan_msg.temporary_channel_id = node_c_temp_chan_id;
9108 nodes[2].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
9110 // Now that we have a second channel with the same funding txo, send a bogus funding message
9111 // and let nodes[1] remove the inbound channel.
9112 let (_, funding_tx, _) = create_funding_transaction(&nodes[2], &nodes[1].node.get_our_node_id(), 100_000, 42);
9114 nodes[2].node.funding_transaction_generated(&node_c_temp_chan_id, &nodes[1].node.get_our_node_id(), funding_tx).unwrap();
9116 let mut funding_created_msg = get_event_msg!(nodes[2], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9117 funding_created_msg.temporary_channel_id = real_channel_id;
9118 // Make the signature invalid by changing the funding output
9119 funding_created_msg.funding_output_index += 10;
9120 nodes[1].node.handle_funding_created(&nodes[2].node.get_our_node_id(), &funding_created_msg);
9121 get_err_msg(&nodes[1], &nodes[2].node.get_our_node_id());
9122 let err = "Invalid funding_created signature from peer".to_owned();
9123 let reason = ClosureReason::ProcessingError { err };
9124 let expected_closing = ExpectedCloseEvent::from_id_reason(real_channel_id, false, reason);
9125 check_closed_events(&nodes[1], &[expected_closing]);
9128 *nodes[1].node.outpoint_to_peer.lock().unwrap().get(&real_chan_funding_txo).unwrap(),
9129 nodes[0].node.get_our_node_id()
9134 fn test_duplicate_chan_id() {
9135 // Test that if a given peer tries to open a channel with the same channel_id as one that is
9136 // already open we reject it and keep the old channel.
9138 // Previously, full_stack_target managed to figure out that if you tried to open two channels
9139 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
9140 // the existing channel when we detect the duplicate new channel, screwing up our monitor
9141 // updating logic for the existing channel.
9142 let chanmon_cfgs = create_chanmon_cfgs(2);
9143 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9144 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9145 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9147 // Create an initial channel
9148 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
9149 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9150 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
9151 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()));
9153 // Try to create a second channel with the same temporary_channel_id as the first and check
9154 // that it is rejected.
9155 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
9157 let events = nodes[1].node.get_and_clear_pending_msg_events();
9158 assert_eq!(events.len(), 1);
9160 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9161 // Technically, at this point, nodes[1] would be justified in thinking both the
9162 // first (valid) and second (invalid) channels are closed, given they both have
9163 // the same non-temporary channel_id. However, currently we do not, so we just
9164 // move forward with it.
9165 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9166 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9168 _ => panic!("Unexpected event"),
9172 // Move the first channel through the funding flow...
9173 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9175 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9176 check_added_monitors!(nodes[0], 0);
9178 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9179 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9181 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9182 assert_eq!(added_monitors.len(), 1);
9183 assert_eq!(added_monitors[0].0, funding_output);
9184 added_monitors.clear();
9186 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9188 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9190 let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
9191 let channel_id = ChannelId::v1_from_funding_outpoint(funding_outpoint);
9193 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
9196 // First try to open a second channel with a temporary channel id equal to the txid-based one.
9197 // Technically this is allowed by the spec, but we don't support it and there's little reason
9198 // to. Still, it shouldn't cause any other issues.
9199 open_chan_msg.temporary_channel_id = channel_id;
9200 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
9202 let events = nodes[1].node.get_and_clear_pending_msg_events();
9203 assert_eq!(events.len(), 1);
9205 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9206 // Technically, at this point, nodes[1] would be justified in thinking both
9207 // channels are closed, but currently we do not, so we just move forward with it.
9208 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9209 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9211 _ => panic!("Unexpected event"),
9215 // Now try to create a second channel which has a duplicate funding output.
9216 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
9217 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9218 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
9219 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()));
9220 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
9222 let funding_created = {
9223 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9224 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9225 // Once we call `get_funding_created` the channel has a duplicate channel_id as
9226 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
9227 // try to create another channel. Instead, we drop the channel entirely here (leaving the
9228 // channelmanager in a possibly nonsense state instead).
9229 match a_peer_state.channel_by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap() {
9230 ChannelPhase::UnfundedOutboundV1(mut chan) => {
9231 let logger = test_utils::TestLogger::new();
9232 chan.get_funding_created(tx.clone(), funding_outpoint, false, &&logger).map_err(|_| ()).unwrap()
9234 _ => panic!("Unexpected ChannelPhase variant"),
9237 check_added_monitors!(nodes[0], 0);
9238 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9239 // At this point we'll look up if the channel_id is present and immediately fail the channel
9240 // without trying to persist the `ChannelMonitor`.
9241 check_added_monitors!(nodes[1], 0);
9243 check_closed_events(&nodes[1], &[
9244 ExpectedCloseEvent::from_id_reason(funding_created.temporary_channel_id, false, ClosureReason::ProcessingError {
9245 err: "Already had channel with the new channel_id".to_owned()
9249 // ...still, nodes[1] will reject the duplicate channel.
9251 let events = nodes[1].node.get_and_clear_pending_msg_events();
9252 assert_eq!(events.len(), 1);
9254 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9255 // Technically, at this point, nodes[1] would be justified in thinking both
9256 // channels are closed, but currently we do not, so we just move forward with it.
9257 assert_eq!(msg.channel_id, channel_id);
9258 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9260 _ => panic!("Unexpected event"),
9264 // finally, finish creating the original channel and send a payment over it to make sure
9265 // everything is functional.
9266 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9268 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9269 assert_eq!(added_monitors.len(), 1);
9270 assert_eq!(added_monitors[0].0, funding_output);
9271 added_monitors.clear();
9273 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9275 let events_4 = nodes[0].node.get_and_clear_pending_events();
9276 assert_eq!(events_4.len(), 0);
9277 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9278 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9280 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9281 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9282 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9284 send_payment(&nodes[0], &[&nodes[1]], 8000000);
9288 fn test_error_chans_closed() {
9289 // Test that we properly handle error messages, closing appropriate channels.
9291 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9292 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9293 // we can test various edge cases around it to ensure we don't regress.
9294 let chanmon_cfgs = create_chanmon_cfgs(3);
9295 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9296 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9297 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9299 // Create some initial channels
9300 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9301 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9302 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
9304 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9305 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9306 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9308 // Closing a channel from a different peer has no effect
9309 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9310 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9312 // Closing one channel doesn't impact others
9313 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9314 check_added_monitors!(nodes[0], 1);
9315 check_closed_broadcast!(nodes[0], false);
9316 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) },
9317 [nodes[1].node.get_our_node_id()], 100000);
9318 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9319 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9320 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);
9321 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);
9323 // A null channel ID should close all channels
9324 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9325 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: ChannelId::new_zero(), data: "ERR".to_owned() });
9326 check_added_monitors!(nodes[0], 2);
9327 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) },
9328 [nodes[1].node.get_our_node_id(); 2], 100000);
9329 let events = nodes[0].node.get_and_clear_pending_msg_events();
9330 assert_eq!(events.len(), 2);
9332 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9333 assert_eq!(msg.contents.flags & 2, 2);
9335 _ => panic!("Unexpected event"),
9338 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9339 assert_eq!(msg.contents.flags & 2, 2);
9341 _ => panic!("Unexpected event"),
9343 // Note that at this point users of a standard PeerHandler will end up calling
9344 // peer_disconnected.
9345 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9346 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9348 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9349 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9350 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9354 fn test_invalid_funding_tx() {
9355 // Test that we properly handle invalid funding transactions sent to us from a peer.
9357 // Previously, all other major lightning implementations had failed to properly sanitize
9358 // funding transactions from their counterparties, leading to a multi-implementation critical
9359 // security vulnerability (though we always sanitized properly, we've previously had
9360 // un-released crashes in the sanitization process).
9362 // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9363 // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9364 // gave up on it. We test this here by generating such a transaction.
9365 let chanmon_cfgs = create_chanmon_cfgs(2);
9366 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9367 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9368 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9370 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None, None).unwrap();
9371 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()));
9372 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()));
9374 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9376 // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9377 // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9378 // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9380 let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9381 let wit_program_script: ScriptBuf = wit_program.into();
9382 for output in tx.output.iter_mut() {
9383 // Make the confirmed funding transaction have a bogus script_pubkey
9384 output.script_pubkey = ScriptBuf::new_v0_p2wsh(&wit_program_script.wscript_hash());
9387 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9388 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()));
9389 check_added_monitors!(nodes[1], 1);
9390 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9392 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()));
9393 check_added_monitors!(nodes[0], 1);
9394 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9396 let events_1 = nodes[0].node.get_and_clear_pending_events();
9397 assert_eq!(events_1.len(), 0);
9399 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9400 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9401 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9403 let expected_err = "funding tx had wrong script/value or output index";
9404 confirm_transaction_at(&nodes[1], &tx, 1);
9405 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() },
9406 [nodes[0].node.get_our_node_id()], 100000);
9407 check_added_monitors!(nodes[1], 1);
9408 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9409 assert_eq!(events_2.len(), 1);
9410 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9411 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9412 if let msgs::ErrorAction::DisconnectPeer { msg } = action {
9413 assert_eq!(msg.as_ref().unwrap().data, "Channel closed because of an exception: ".to_owned() + expected_err);
9414 } else { panic!(); }
9415 } else { panic!(); }
9416 assert_eq!(nodes[1].node.list_channels().len(), 0);
9418 // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9419 // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9420 // as its not 32 bytes long.
9421 let mut spend_tx = Transaction {
9422 version: 2i32, lock_time: LockTime::ZERO,
9423 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9424 previous_output: BitcoinOutPoint {
9428 script_sig: ScriptBuf::new(),
9429 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9430 witness: Witness::from_slice(&channelmonitor::deliberately_bogus_accepted_htlc_witness())
9432 output: vec![TxOut {
9434 script_pubkey: ScriptBuf::new(),
9437 check_spends!(spend_tx, tx);
9438 mine_transaction(&nodes[1], &spend_tx);
9442 fn test_coinbase_funding_tx() {
9443 // Miners are able to fund channels directly from coinbase transactions, however
9444 // by consensus rules, outputs of a coinbase transaction are encumbered by a 100
9445 // block maturity timelock. To ensure that a (non-0conf) channel like this is enforceable
9446 // on-chain, the minimum depth is updated to 100 blocks for coinbase funding transactions.
9448 // Note that 0conf channels with coinbase funding transactions are unaffected and are
9449 // immediately operational after opening.
9450 let chanmon_cfgs = create_chanmon_cfgs(2);
9451 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9452 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9453 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9455 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
9456 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9458 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9459 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9461 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9463 // Create the coinbase funding transaction.
9464 let (temporary_channel_id, tx, _) = create_coinbase_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9466 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9467 check_added_monitors!(nodes[0], 0);
9468 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9470 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9471 check_added_monitors!(nodes[1], 1);
9472 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9474 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9476 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
9477 check_added_monitors!(nodes[0], 1);
9479 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9480 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
9482 // Starting at height 0, we "confirm" the coinbase at height 1.
9483 confirm_transaction_at(&nodes[0], &tx, 1);
9484 // We connect 98 more blocks to have 99 confirmations for the coinbase transaction.
9485 connect_blocks(&nodes[0], COINBASE_MATURITY - 2);
9486 // Check that we have no pending message events (we have not queued a `channel_ready` yet).
9487 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
9488 // Now connect one more block which results in 100 confirmations of the coinbase transaction.
9489 connect_blocks(&nodes[0], 1);
9490 // There should now be a `channel_ready` which can be handled.
9491 let _ = &nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &get_event_msg!(&nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id()));
9493 confirm_transaction_at(&nodes[1], &tx, 1);
9494 connect_blocks(&nodes[1], COINBASE_MATURITY - 2);
9495 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9496 connect_blocks(&nodes[1], 1);
9497 expect_channel_ready_event(&nodes[1], &nodes[0].node.get_our_node_id());
9498 create_chan_between_nodes_with_value_confirm_second(&nodes[0], &nodes[1]);
9501 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9502 // In the first version of the chain::Confirm interface, after a refactor was made to not
9503 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9504 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9505 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9506 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9507 // spending transaction until height N+1 (or greater). This was due to the way
9508 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9509 // spending transaction at the height the input transaction was confirmed at, not whether we
9510 // should broadcast a spending transaction at the current height.
9511 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9512 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9513 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9514 // until we learned about an additional block.
9516 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9517 // aren't broadcasting transactions too early (ie not broadcasting them at all).
9518 let chanmon_cfgs = create_chanmon_cfgs(3);
9519 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9520 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9521 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9522 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9524 create_announced_chan_between_nodes(&nodes, 0, 1);
9525 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
9526 let (_, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9527 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
9528 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9530 nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9531 check_closed_broadcast!(nodes[1], true);
9532 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[2].node.get_our_node_id()], 100000);
9533 check_added_monitors!(nodes[1], 1);
9534 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9535 assert_eq!(node_txn.len(), 1);
9537 let conf_height = nodes[1].best_block_info().1;
9538 if !test_height_before_timelock {
9539 connect_blocks(&nodes[1], 24 * 6);
9541 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9542 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9543 if test_height_before_timelock {
9544 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9545 // generate any events or broadcast any transactions
9546 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9547 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9549 // We should broadcast an HTLC transaction spending our funding transaction first
9550 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9551 assert_eq!(spending_txn.len(), 2);
9552 let htlc_tx = if spending_txn[0].txid() == node_txn[0].txid() {
9557 check_spends!(htlc_tx, node_txn[0]);
9558 // We should also generate a SpendableOutputs event with the to_self output (as its
9560 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9561 assert_eq!(descriptor_spend_txn.len(), 1);
9563 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9564 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9565 // additional block built on top of the current chain.
9566 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9567 &nodes[1].get_block_header(conf_height + 1), &[(0, htlc_tx)], conf_height + 1);
9568 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 }]);
9569 check_added_monitors!(nodes[1], 1);
9571 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9572 assert!(updates.update_add_htlcs.is_empty());
9573 assert!(updates.update_fulfill_htlcs.is_empty());
9574 assert_eq!(updates.update_fail_htlcs.len(), 1);
9575 assert!(updates.update_fail_malformed_htlcs.is_empty());
9576 assert!(updates.update_fee.is_none());
9577 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9578 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9579 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9584 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9585 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9586 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9589 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9590 let chanmon_cfgs = create_chanmon_cfgs(2);
9591 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9592 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9593 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9595 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9597 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9598 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
9599 let route = get_route!(nodes[0], payment_params, 10_000).unwrap();
9601 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9604 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9605 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9606 check_added_monitors!(nodes[0], 1);
9607 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9608 assert_eq!(events.len(), 1);
9609 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9610 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9611 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9613 expect_pending_htlcs_forwardable!(nodes[1]);
9614 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9617 // Note that we use a different PaymentId here to allow us to duplicativly pay
9618 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9619 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9620 check_added_monitors!(nodes[0], 1);
9621 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9622 assert_eq!(events.len(), 1);
9623 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9624 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9625 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9626 // At this point, nodes[1] would notice it has too much value for the payment. It will
9627 // assume the second is a privacy attack (no longer particularly relevant
9628 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9629 // the first HTLC delivered above.
9632 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9633 nodes[1].node.process_pending_htlc_forwards();
9635 if test_for_second_fail_panic {
9636 // Now we go fail back the first HTLC from the user end.
9637 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9639 let expected_destinations = vec![
9640 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9641 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9643 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], expected_destinations);
9644 nodes[1].node.process_pending_htlc_forwards();
9646 check_added_monitors!(nodes[1], 1);
9647 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9648 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9650 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9651 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9652 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9654 let failure_events = nodes[0].node.get_and_clear_pending_events();
9655 assert_eq!(failure_events.len(), 4);
9656 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9657 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9658 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9659 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9661 // Let the second HTLC fail and claim the first
9662 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9663 nodes[1].node.process_pending_htlc_forwards();
9665 check_added_monitors!(nodes[1], 1);
9666 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9667 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9668 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9670 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9672 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9677 fn test_dup_htlc_second_fail_panic() {
9678 // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9679 // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9680 // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9681 // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9682 do_test_dup_htlc_second_rejected(true);
9686 fn test_dup_htlc_second_rejected() {
9687 // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9688 // simply reject the second HTLC but are still able to claim the first HTLC.
9689 do_test_dup_htlc_second_rejected(false);
9693 fn test_inconsistent_mpp_params() {
9694 // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9695 // such HTLC and allow the second to stay.
9696 let chanmon_cfgs = create_chanmon_cfgs(4);
9697 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9698 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9699 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9701 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9702 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9703 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9704 let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9706 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9707 .with_bolt11_features(nodes[3].node.bolt11_invoice_features()).unwrap();
9708 let mut route = get_route!(nodes[0], payment_params, 15_000_000).unwrap();
9709 assert_eq!(route.paths.len(), 2);
9710 route.paths.sort_by(|path_a, _| {
9711 // Sort the path so that the path through nodes[1] comes first
9712 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9713 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9716 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9718 let cur_height = nodes[0].best_block_info().1;
9719 let payment_id = PaymentId([42; 32]);
9721 let session_privs = {
9722 // We create a fake route here so that we start with three pending HTLCs, which we'll
9723 // ultimately have, just not right away.
9724 let mut dup_route = route.clone();
9725 dup_route.paths.push(route.paths[1].clone());
9726 nodes[0].node.test_add_new_pending_payment(our_payment_hash,
9727 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &dup_route).unwrap()
9729 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
9730 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9731 &None, session_privs[0]).unwrap();
9732 check_added_monitors!(nodes[0], 1);
9735 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9736 assert_eq!(events.len(), 1);
9737 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9739 assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9741 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9742 RecipientOnionFields::secret_only(our_payment_secret), 14_000_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9743 check_added_monitors!(nodes[0], 1);
9746 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9747 assert_eq!(events.len(), 1);
9748 let payment_event = SendEvent::from_event(events.pop().unwrap());
9750 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9751 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9753 expect_pending_htlcs_forwardable!(nodes[2]);
9754 check_added_monitors!(nodes[2], 1);
9756 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9757 assert_eq!(events.len(), 1);
9758 let payment_event = SendEvent::from_event(events.pop().unwrap());
9760 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9761 check_added_monitors!(nodes[3], 0);
9762 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9764 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9765 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9766 // post-payment_secrets) and fail back the new HTLC.
9768 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9769 nodes[3].node.process_pending_htlc_forwards();
9770 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9771 nodes[3].node.process_pending_htlc_forwards();
9773 check_added_monitors!(nodes[3], 1);
9775 let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9776 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9777 commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9779 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 }]);
9780 check_added_monitors!(nodes[2], 1);
9782 let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9783 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9784 commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9786 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9788 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9789 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9790 &None, session_privs[2]).unwrap();
9791 check_added_monitors!(nodes[0], 1);
9793 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9794 assert_eq!(events.len(), 1);
9795 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9797 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9798 expect_payment_sent(&nodes[0], our_payment_preimage, Some(None), true, true);
9802 fn test_double_partial_claim() {
9803 // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9804 // time out, the sender resends only some of the MPP parts, then the user processes the
9805 // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9807 let chanmon_cfgs = create_chanmon_cfgs(4);
9808 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9809 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9810 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9812 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9813 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9814 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9815 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9817 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9818 assert_eq!(route.paths.len(), 2);
9819 route.paths.sort_by(|path_a, _| {
9820 // Sort the path so that the path through nodes[1] comes first
9821 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9822 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9825 send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9826 // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9827 // amount of time to respond to.
9829 // Connect some blocks to time out the payment
9830 connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9831 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9833 let failed_destinations = vec![
9834 HTLCDestination::FailedPayment { payment_hash },
9835 HTLCDestination::FailedPayment { payment_hash },
9837 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9839 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
9841 // nodes[1] now retries one of the two paths...
9842 nodes[0].node.send_payment_with_route(&route, payment_hash,
9843 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9844 check_added_monitors!(nodes[0], 2);
9846 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9847 assert_eq!(events.len(), 2);
9848 let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
9849 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9851 // At this point nodes[3] has received one half of the payment, and the user goes to handle
9852 // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9853 nodes[3].node.claim_funds(payment_preimage);
9854 check_added_monitors!(nodes[3], 0);
9855 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9858 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9859 #[derive(Clone, Copy, PartialEq)]
9860 enum ExposureEvent {
9861 /// Breach occurs at HTLC forwarding (see `send_htlc`)
9863 /// Breach occurs at HTLC reception (see `update_add_htlc`)
9865 /// Breach occurs at outbound update_fee (see `send_update_fee`)
9866 AtUpdateFeeOutbound,
9869 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool, multiplier_dust_limit: bool) {
9870 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9873 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9874 // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9875 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9876 // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9877 // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9878 // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9879 // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9880 // might be available again for HTLC processing once the dust bandwidth has cleared up.
9882 let chanmon_cfgs = create_chanmon_cfgs(2);
9883 let mut config = test_default_channel_config();
9884 config.channel_config.max_dust_htlc_exposure = if multiplier_dust_limit {
9885 // Default test fee estimator rate is 253 sat/kw, so we set the multiplier to 5_000_000 / 253
9886 // to get roughly the same initial value as the default setting when this test was
9887 // originally written.
9888 MaxDustHTLCExposure::FeeRateMultiplier(5_000_000 / 253)
9889 } else { MaxDustHTLCExposure::FixedLimitMsat(5_000_000) }; // initial default setting value
9890 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9891 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9892 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9894 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None, None).unwrap();
9895 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9896 open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9897 open_channel.max_accepted_htlcs = 60;
9899 open_channel.dust_limit_satoshis = 546;
9901 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9902 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9903 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9905 let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
9907 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9910 let mut node_0_per_peer_lock;
9911 let mut node_0_peer_state_lock;
9912 match get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, temporary_channel_id) {
9913 ChannelPhase::UnfundedOutboundV1(chan) => {
9914 chan.context.holder_dust_limit_satoshis = 546;
9916 _ => panic!("Unexpected ChannelPhase variant"),
9920 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9921 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()));
9922 check_added_monitors!(nodes[1], 1);
9923 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9925 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()));
9926 check_added_monitors!(nodes[0], 1);
9927 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9929 let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9930 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9931 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9933 // Fetch a route in advance as we will be unable to once we're unable to send.
9934 let (mut route, payment_hash, _, payment_secret) =
9935 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
9937 let (dust_buffer_feerate, max_dust_htlc_exposure_msat) = {
9938 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9939 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9940 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
9941 (chan.context().get_dust_buffer_feerate(None) as u64,
9942 chan.context().get_max_dust_htlc_exposure_msat(&LowerBoundedFeeEstimator(nodes[0].fee_estimator)))
9944 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;
9945 let dust_outbound_htlc_on_holder_tx: u64 = max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9947 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;
9948 let dust_inbound_htlc_on_holder_tx: u64 = max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9950 let dust_htlc_on_counterparty_tx: u64 = 4;
9951 let dust_htlc_on_counterparty_tx_msat: u64 = max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9954 if dust_outbound_balance {
9955 // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9956 // Outbound dust balance: 4372 sats
9957 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9958 for _ in 0..dust_outbound_htlc_on_holder_tx {
9959 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9960 nodes[0].node.send_payment_with_route(&route, payment_hash,
9961 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9964 // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9965 // Inbound dust balance: 4372 sats
9966 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9967 for _ in 0..dust_inbound_htlc_on_holder_tx {
9968 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9972 if dust_outbound_balance {
9973 // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9974 // Outbound dust balance: 5000 sats
9975 for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9976 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9977 nodes[0].node.send_payment_with_route(&route, payment_hash,
9978 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9981 // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9982 // Inbound dust balance: 5000 sats
9983 for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9984 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9989 if exposure_breach_event == ExposureEvent::AtHTLCForward {
9990 route.paths[0].hops.last_mut().unwrap().fee_msat =
9991 if on_holder_tx { dust_outbound_htlc_on_holder_tx_msat } else { dust_htlc_on_counterparty_tx_msat + 1 };
9992 // With default dust exposure: 5000 sats
9994 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9995 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9996 ), true, APIError::ChannelUnavailable { .. }, {});
9998 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9999 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
10000 ), true, APIError::ChannelUnavailable { .. }, {});
10002 } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
10003 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 });
10004 nodes[1].node.send_payment_with_route(&route, payment_hash,
10005 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
10006 check_added_monitors!(nodes[1], 1);
10007 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
10008 assert_eq!(events.len(), 1);
10009 let payment_event = SendEvent::from_event(events.remove(0));
10010 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
10011 // With default dust exposure: 5000 sats
10013 // Outbound dust balance: 6399 sats
10014 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
10015 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
10016 nodes[0].logger.assert_log("lightning::ln::channel", 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);
10018 // Outbound dust balance: 5200 sats
10019 nodes[0].logger.assert_log("lightning::ln::channel",
10020 format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx",
10021 dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx - 1) + dust_htlc_on_counterparty_tx_msat + 4,
10022 max_dust_htlc_exposure_msat), 1);
10024 } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
10025 route.paths[0].hops.last_mut().unwrap().fee_msat = 2_500_000;
10026 // For the multiplier dust exposure limit, since it scales with feerate,
10027 // we need to add a lot of HTLCs that will become dust at the new feerate
10028 // to cross the threshold.
10030 let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[1], Some(1_000), None);
10031 nodes[0].node.send_payment_with_route(&route, payment_hash,
10032 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
10035 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10036 *feerate_lock = *feerate_lock * 10;
10038 nodes[0].node.timer_tick_occurred();
10039 check_added_monitors!(nodes[0], 1);
10040 nodes[0].logger.assert_log_contains("lightning::ln::channel", "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure", 1);
10043 let _ = nodes[0].node.get_and_clear_pending_msg_events();
10044 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
10045 added_monitors.clear();
10048 fn do_test_max_dust_htlc_exposure_by_threshold_type(multiplier_dust_limit: bool) {
10049 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true, multiplier_dust_limit);
10050 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true, multiplier_dust_limit);
10051 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true, multiplier_dust_limit);
10052 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false, multiplier_dust_limit);
10053 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false, multiplier_dust_limit);
10054 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false, multiplier_dust_limit);
10055 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true, multiplier_dust_limit);
10056 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false, multiplier_dust_limit);
10057 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true, multiplier_dust_limit);
10058 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false, multiplier_dust_limit);
10059 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false, multiplier_dust_limit);
10060 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true, multiplier_dust_limit);
10064 fn test_max_dust_htlc_exposure() {
10065 do_test_max_dust_htlc_exposure_by_threshold_type(false);
10066 do_test_max_dust_htlc_exposure_by_threshold_type(true);
10070 fn test_non_final_funding_tx() {
10071 let chanmon_cfgs = create_chanmon_cfgs(2);
10072 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10073 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10074 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10076 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
10077 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10078 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10079 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10080 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10082 let best_height = nodes[0].node.best_block.read().unwrap().height();
10084 let chan_id = *nodes[0].network_chan_count.borrow();
10085 let events = nodes[0].node.get_and_clear_pending_events();
10086 let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::ScriptBuf::new(), sequence: Sequence(1), witness: Witness::from_slice(&[&[1]]) };
10087 assert_eq!(events.len(), 1);
10088 let mut tx = match events[0] {
10089 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
10090 // Timelock the transaction _beyond_ the best client height + 1.
10091 Transaction { version: chan_id as i32, lock_time: LockTime::from_height(best_height + 2).unwrap(), input: vec![input], output: vec![TxOut {
10092 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
10095 _ => panic!("Unexpected event"),
10097 // Transaction should fail as it's evaluated as non-final for propagation.
10098 match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
10099 Err(APIError::APIMisuseError { err }) => {
10100 assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
10104 let events = nodes[0].node.get_and_clear_pending_events();
10105 assert_eq!(events.len(), 1);
10107 Event::ChannelClosed { channel_id, .. } => {
10108 assert_eq!(channel_id, temp_channel_id);
10110 _ => panic!("Unexpected event"),
10115 fn test_non_final_funding_tx_within_headroom() {
10116 let chanmon_cfgs = create_chanmon_cfgs(2);
10117 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10118 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10119 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10121 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
10122 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10123 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10124 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10125 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10127 let best_height = nodes[0].node.best_block.read().unwrap().height();
10129 let chan_id = *nodes[0].network_chan_count.borrow();
10130 let events = nodes[0].node.get_and_clear_pending_events();
10131 let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::ScriptBuf::new(), sequence: Sequence(1), witness: Witness::from_slice(&[[1]]) };
10132 assert_eq!(events.len(), 1);
10133 let mut tx = match events[0] {
10134 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
10135 // Timelock the transaction within a +1 headroom from the best block.
10136 Transaction { version: chan_id as i32, lock_time: LockTime::from_consensus(best_height + 1), input: vec![input], output: vec![TxOut {
10137 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
10140 _ => panic!("Unexpected event"),
10143 // Transaction should be accepted if it's in a +1 headroom from best block.
10144 assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
10145 get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
10149 fn accept_busted_but_better_fee() {
10150 // If a peer sends us a fee update that is too low, but higher than our previous channel
10151 // feerate, we should accept it. In the future we may want to consider closing the channel
10152 // later, but for now we only accept the update.
10153 let mut chanmon_cfgs = create_chanmon_cfgs(2);
10154 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10155 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10156 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10158 create_chan_between_nodes(&nodes[0], &nodes[1]);
10160 // Set nodes[1] to expect 5,000 sat/kW.
10162 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
10163 *feerate_lock = 5000;
10166 // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
10168 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10169 *feerate_lock = 1000;
10171 nodes[0].node.timer_tick_occurred();
10172 check_added_monitors!(nodes[0], 1);
10174 let events = nodes[0].node.get_and_clear_pending_msg_events();
10175 assert_eq!(events.len(), 1);
10177 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
10178 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
10179 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
10181 _ => panic!("Unexpected event"),
10184 // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
10187 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10188 *feerate_lock = 2000;
10190 nodes[0].node.timer_tick_occurred();
10191 check_added_monitors!(nodes[0], 1);
10193 let events = nodes[0].node.get_and_clear_pending_msg_events();
10194 assert_eq!(events.len(), 1);
10196 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
10197 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
10198 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
10200 _ => panic!("Unexpected event"),
10203 // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
10206 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10207 *feerate_lock = 1000;
10209 nodes[0].node.timer_tick_occurred();
10210 check_added_monitors!(nodes[0], 1);
10212 let events = nodes[0].node.get_and_clear_pending_msg_events();
10213 assert_eq!(events.len(), 1);
10215 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
10216 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
10217 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
10218 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000".to_owned() },
10219 [nodes[0].node.get_our_node_id()], 100000);
10220 check_closed_broadcast!(nodes[1], true);
10221 check_added_monitors!(nodes[1], 1);
10223 _ => panic!("Unexpected event"),
10227 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
10228 let mut chanmon_cfgs = create_chanmon_cfgs(2);
10229 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10230 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10231 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10232 let min_final_cltv_expiry_delta = 120;
10233 let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
10234 min_final_cltv_expiry_delta - 2 };
10235 let recv_value = 100_000;
10237 create_chan_between_nodes(&nodes[0], &nodes[1]);
10239 let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), final_cltv_expiry_delta as u32);
10240 let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
10241 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
10242 Some(recv_value), Some(min_final_cltv_expiry_delta));
10243 (payment_hash, payment_preimage, payment_secret)
10245 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
10246 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
10248 let route = get_route!(nodes[0], payment_parameters, recv_value).unwrap();
10249 nodes[0].node.send_payment_with_route(&route, payment_hash,
10250 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
10251 check_added_monitors!(nodes[0], 1);
10252 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10253 assert_eq!(events.len(), 1);
10254 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
10255 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
10256 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
10257 expect_pending_htlcs_forwardable!(nodes[1]);
10260 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
10261 None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
10263 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
10265 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
10267 check_added_monitors!(nodes[1], 1);
10269 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
10270 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
10271 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
10273 expect_payment_failed!(nodes[0], payment_hash, true);
10278 fn test_payment_with_custom_min_cltv_expiry_delta() {
10279 do_payment_with_custom_min_final_cltv_expiry(false, false);
10280 do_payment_with_custom_min_final_cltv_expiry(false, true);
10281 do_payment_with_custom_min_final_cltv_expiry(true, false);
10282 do_payment_with_custom_min_final_cltv_expiry(true, true);
10286 fn test_disconnects_peer_awaiting_response_ticks() {
10287 // Tests that nodes which are awaiting on a response critical for channel responsiveness
10288 // disconnect their counterparty after `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10289 let mut chanmon_cfgs = create_chanmon_cfgs(2);
10290 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10291 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10292 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10294 // Asserts a disconnect event is queued to the user.
10295 let check_disconnect_event = |node: &Node, should_disconnect: bool| {
10296 let disconnect_event = node.node.get_and_clear_pending_msg_events().iter().find_map(|event|
10297 if let MessageSendEvent::HandleError { action, .. } = event {
10298 if let msgs::ErrorAction::DisconnectPeerWithWarning { .. } = action {
10307 assert_eq!(disconnect_event.is_some(), should_disconnect);
10310 // Fires timer ticks ensuring we only attempt to disconnect peers after reaching
10311 // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10312 let check_disconnect = |node: &Node| {
10313 // No disconnect without any timer ticks.
10314 check_disconnect_event(node, false);
10316 // No disconnect with 1 timer tick less than required.
10317 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS - 1 {
10318 node.node.timer_tick_occurred();
10319 check_disconnect_event(node, false);
10322 // Disconnect after reaching the required ticks.
10323 node.node.timer_tick_occurred();
10324 check_disconnect_event(node, true);
10326 // Disconnect again on the next tick if the peer hasn't been disconnected yet.
10327 node.node.timer_tick_occurred();
10328 check_disconnect_event(node, true);
10331 create_chan_between_nodes(&nodes[0], &nodes[1]);
10333 // We'll start by performing a fee update with Alice (nodes[0]) on the channel.
10334 *nodes[0].fee_estimator.sat_per_kw.lock().unwrap() *= 2;
10335 nodes[0].node.timer_tick_occurred();
10336 check_added_monitors!(&nodes[0], 1);
10337 let alice_fee_update = get_htlc_update_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
10338 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), alice_fee_update.update_fee.as_ref().unwrap());
10339 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &alice_fee_update.commitment_signed);
10340 check_added_monitors!(&nodes[1], 1);
10342 // This will prompt Bob (nodes[1]) to respond with his `CommitmentSigned` and `RevokeAndACK`.
10343 let (bob_revoke_and_ack, bob_commitment_signed) = get_revoke_commit_msgs!(&nodes[1], nodes[0].node.get_our_node_id());
10344 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revoke_and_ack);
10345 check_added_monitors!(&nodes[0], 1);
10346 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_commitment_signed);
10347 check_added_monitors(&nodes[0], 1);
10349 // Alice then needs to send her final `RevokeAndACK` to complete the commitment dance. We
10350 // pretend Bob hasn't received the message and check whether he'll disconnect Alice after
10351 // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10352 let alice_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
10353 check_disconnect(&nodes[1]);
10355 // Now, we'll reconnect them to test awaiting a `ChannelReestablish` message.
10357 // Note that since the commitment dance didn't complete above, Alice is expected to resend her
10358 // final `RevokeAndACK` to Bob to complete it.
10359 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
10360 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10361 let bob_init = msgs::Init {
10362 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
10364 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &bob_init, true).unwrap();
10365 let alice_init = msgs::Init {
10366 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
10368 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &alice_init, true).unwrap();
10370 // Upon reconnection, Alice sends her `ChannelReestablish` to Bob. Alice, however, hasn't
10371 // received Bob's yet, so she should disconnect him after reaching
10372 // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10373 let alice_channel_reestablish = get_event_msg!(
10374 nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id()
10376 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &alice_channel_reestablish);
10377 check_disconnect(&nodes[0]);
10379 // Bob now sends his `ChannelReestablish` to Alice to resume the channel and consider it "live".
10380 let bob_channel_reestablish = nodes[1].node.get_and_clear_pending_msg_events().iter().find_map(|event|
10381 if let MessageSendEvent::SendChannelReestablish { node_id, msg } = event {
10382 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
10388 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bob_channel_reestablish);
10390 // Sanity check that Alice won't disconnect Bob since she's no longer waiting for any messages.
10391 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
10392 nodes[0].node.timer_tick_occurred();
10393 check_disconnect_event(&nodes[0], false);
10396 // However, Bob is still waiting on Alice's `RevokeAndACK`, so he should disconnect her after
10397 // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10398 check_disconnect(&nodes[1]);
10400 // Finally, have Bob process the last message.
10401 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &alice_revoke_and_ack);
10402 check_added_monitors(&nodes[1], 1);
10404 // At this point, neither node should attempt to disconnect each other, since they aren't
10405 // waiting on any messages.
10406 for node in &nodes {
10407 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
10408 node.node.timer_tick_occurred();
10409 check_disconnect_event(node, false);
10415 fn test_remove_expired_outbound_unfunded_channels() {
10416 let chanmon_cfgs = create_chanmon_cfgs(2);
10417 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10418 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10419 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10421 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
10422 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10423 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10424 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10425 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10427 let events = nodes[0].node.get_and_clear_pending_events();
10428 assert_eq!(events.len(), 1);
10430 Event::FundingGenerationReady { .. } => (),
10431 _ => panic!("Unexpected event"),
10434 // Asserts the outbound channel has been removed from a nodes[0]'s peer state map.
10435 let check_outbound_channel_existence = |should_exist: bool| {
10436 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
10437 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
10438 assert_eq!(chan_lock.channel_by_id.contains_key(&temp_channel_id), should_exist);
10441 // Channel should exist without any timer ticks.
10442 check_outbound_channel_existence(true);
10444 // Channel should exist with 1 timer tick less than required.
10445 for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS - 1 {
10446 nodes[0].node.timer_tick_occurred();
10447 check_outbound_channel_existence(true)
10450 // Remove channel after reaching the required ticks.
10451 nodes[0].node.timer_tick_occurred();
10452 check_outbound_channel_existence(false);
10454 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
10455 assert_eq!(msg_events.len(), 1);
10456 match msg_events[0] {
10457 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
10458 assert_eq!(msg.data, "Force-closing pending channel due to timeout awaiting establishment handshake");
10460 _ => panic!("Unexpected event"),
10462 check_closed_event(&nodes[0], 1, ClosureReason::HolderForceClosed, false, &[nodes[1].node.get_our_node_id()], 100000);
10466 fn test_remove_expired_inbound_unfunded_channels() {
10467 let chanmon_cfgs = create_chanmon_cfgs(2);
10468 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10469 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10470 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10472 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
10473 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10474 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10475 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10476 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10478 let events = nodes[0].node.get_and_clear_pending_events();
10479 assert_eq!(events.len(), 1);
10481 Event::FundingGenerationReady { .. } => (),
10482 _ => panic!("Unexpected event"),
10485 // Asserts the inbound channel has been removed from a nodes[1]'s peer state map.
10486 let check_inbound_channel_existence = |should_exist: bool| {
10487 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
10488 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
10489 assert_eq!(chan_lock.channel_by_id.contains_key(&temp_channel_id), should_exist);
10492 // Channel should exist without any timer ticks.
10493 check_inbound_channel_existence(true);
10495 // Channel should exist with 1 timer tick less than required.
10496 for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS - 1 {
10497 nodes[1].node.timer_tick_occurred();
10498 check_inbound_channel_existence(true)
10501 // Remove channel after reaching the required ticks.
10502 nodes[1].node.timer_tick_occurred();
10503 check_inbound_channel_existence(false);
10505 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
10506 assert_eq!(msg_events.len(), 1);
10507 match msg_events[0] {
10508 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
10509 assert_eq!(msg.data, "Force-closing pending channel due to timeout awaiting establishment handshake");
10511 _ => panic!("Unexpected event"),
10513 check_closed_event(&nodes[1], 1, ClosureReason::HolderForceClosed, false, &[nodes[0].node.get_our_node_id()], 100000);
10516 fn do_test_multi_post_event_actions(do_reload: bool) {
10517 // Tests handling multiple post-Event actions at once.
10518 // There is specific code in ChannelManager to handle channels where multiple post-Event
10519 // `ChannelMonitorUpdates` are pending at once. This test exercises that code.
10521 // Specifically, we test calling `get_and_clear_pending_events` while there are two
10522 // PaymentSents from different channels and one channel has two pending `ChannelMonitorUpdate`s
10523 // - one from an RAA and one from an inbound commitment_signed.
10524 let chanmon_cfgs = create_chanmon_cfgs(3);
10525 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10526 let (persister, chain_monitor);
10527 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10528 let nodes_0_deserialized;
10529 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10531 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
10532 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 0, 2).2;
10534 send_payment(&nodes[0], &[&nodes[1]], 1_000_000);
10535 send_payment(&nodes[0], &[&nodes[2]], 1_000_000);
10537 let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
10538 let (payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[2]], 1_000_000);
10540 nodes[1].node.claim_funds(our_payment_preimage);
10541 check_added_monitors!(nodes[1], 1);
10542 expect_payment_claimed!(nodes[1], our_payment_hash, 1_000_000);
10544 nodes[2].node.claim_funds(payment_preimage_2);
10545 check_added_monitors!(nodes[2], 1);
10546 expect_payment_claimed!(nodes[2], payment_hash_2, 1_000_000);
10548 for dest in &[1, 2] {
10549 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[*dest], nodes[0].node.get_our_node_id());
10550 nodes[0].node.handle_update_fulfill_htlc(&nodes[*dest].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
10551 commitment_signed_dance!(nodes[0], nodes[*dest], htlc_fulfill_updates.commitment_signed, false);
10552 check_added_monitors(&nodes[0], 0);
10555 let (route, payment_hash_3, _, payment_secret_3) =
10556 get_route_and_payment_hash!(nodes[1], nodes[0], 100_000);
10557 let payment_id = PaymentId(payment_hash_3.0);
10558 nodes[1].node.send_payment_with_route(&route, payment_hash_3,
10559 RecipientOnionFields::secret_only(payment_secret_3), payment_id).unwrap();
10560 check_added_monitors(&nodes[1], 1);
10562 let send_event = SendEvent::from_node(&nodes[1]);
10563 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event.msgs[0]);
10564 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_event.commitment_msg);
10565 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
10568 let nodes_0_serialized = nodes[0].node.encode();
10569 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
10570 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_2).encode();
10571 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);
10573 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10574 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10576 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
10577 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[2]));
10580 let events = nodes[0].node.get_and_clear_pending_events();
10581 assert_eq!(events.len(), 4);
10582 if let Event::PaymentSent { payment_preimage, .. } = events[0] {
10583 assert!(payment_preimage == our_payment_preimage || payment_preimage == payment_preimage_2);
10584 } else { panic!(); }
10585 if let Event::PaymentSent { payment_preimage, .. } = events[1] {
10586 assert!(payment_preimage == our_payment_preimage || payment_preimage == payment_preimage_2);
10587 } else { panic!(); }
10588 if let Event::PaymentPathSuccessful { .. } = events[2] {} else { panic!(); }
10589 if let Event::PaymentPathSuccessful { .. } = events[3] {} else { panic!(); }
10591 // After the events are processed, the ChannelMonitorUpdates will be released and, upon their
10592 // completion, we'll respond to nodes[1] with an RAA + CS.
10593 get_revoke_commit_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
10594 check_added_monitors(&nodes[0], 3);
10598 fn test_multi_post_event_actions() {
10599 do_test_multi_post_event_actions(true);
10600 do_test_multi_post_event_actions(false);
10604 fn test_batch_channel_open() {
10605 let chanmon_cfgs = create_chanmon_cfgs(3);
10606 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10607 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10608 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10610 // Initiate channel opening and create the batch channel funding transaction.
10611 let (tx, funding_created_msgs) = create_batch_channel_funding(&nodes[0], &[
10612 (&nodes[1], 100_000, 0, 42, None),
10613 (&nodes[2], 200_000, 0, 43, None),
10616 // Go through the funding_created and funding_signed flow with node 1.
10617 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[0]);
10618 check_added_monitors(&nodes[1], 1);
10619 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
10621 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10622 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
10623 check_added_monitors(&nodes[0], 1);
10625 // The transaction should not have been broadcast before all channels are ready.
10626 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
10628 // Go through the funding_created and funding_signed flow with node 2.
10629 nodes[2].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[1]);
10630 check_added_monitors(&nodes[2], 1);
10631 expect_channel_pending_event(&nodes[2], &nodes[0].node.get_our_node_id());
10633 let funding_signed_msg = get_event_msg!(nodes[2], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10634 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
10635 nodes[0].node.handle_funding_signed(&nodes[2].node.get_our_node_id(), &funding_signed_msg);
10636 check_added_monitors(&nodes[0], 1);
10638 // The transaction should not have been broadcast before persisting all monitors has been
10640 assert_eq!(nodes[0].tx_broadcaster.txn_broadcast().len(), 0);
10641 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
10643 // Complete the persistence of the monitor.
10644 nodes[0].chain_monitor.complete_sole_pending_chan_update(
10645 &ChannelId::v1_from_funding_outpoint(OutPoint { txid: tx.txid(), index: 1 })
10647 let events = nodes[0].node.get_and_clear_pending_events();
10649 // The transaction should only have been broadcast now.
10650 let broadcasted_txs = nodes[0].tx_broadcaster.txn_broadcast();
10651 assert_eq!(broadcasted_txs.len(), 1);
10652 assert_eq!(broadcasted_txs[0], tx);
10654 assert_eq!(events.len(), 2);
10655 assert!(events.iter().any(|e| matches!(
10657 crate::events::Event::ChannelPending {
10658 ref counterparty_node_id,
10660 } if counterparty_node_id == &nodes[1].node.get_our_node_id(),
10662 assert!(events.iter().any(|e| matches!(
10664 crate::events::Event::ChannelPending {
10665 ref counterparty_node_id,
10667 } if counterparty_node_id == &nodes[2].node.get_our_node_id(),
10672 fn test_close_in_funding_batch() {
10673 // This test ensures that if one of the channels
10674 // in the batch closes, the complete batch will close.
10675 let chanmon_cfgs = create_chanmon_cfgs(3);
10676 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10677 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10678 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10680 // Initiate channel opening and create the batch channel funding transaction.
10681 let (tx, funding_created_msgs) = create_batch_channel_funding(&nodes[0], &[
10682 (&nodes[1], 100_000, 0, 42, None),
10683 (&nodes[2], 200_000, 0, 43, None),
10686 // Go through the funding_created and funding_signed flow with node 1.
10687 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[0]);
10688 check_added_monitors(&nodes[1], 1);
10689 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
10691 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10692 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
10693 check_added_monitors(&nodes[0], 1);
10695 // The transaction should not have been broadcast before all channels are ready.
10696 assert_eq!(nodes[0].tx_broadcaster.txn_broadcast().len(), 0);
10698 // Force-close the channel for which we've completed the initial monitor.
10699 let funding_txo_1 = OutPoint { txid: tx.txid(), index: 0 };
10700 let funding_txo_2 = OutPoint { txid: tx.txid(), index: 1 };
10701 let channel_id_1 = ChannelId::v1_from_funding_outpoint(funding_txo_1);
10702 let channel_id_2 = ChannelId::v1_from_funding_outpoint(funding_txo_2);
10704 nodes[0].node.force_close_broadcasting_latest_txn(&channel_id_1, &nodes[1].node.get_our_node_id()).unwrap();
10706 // The monitor should become closed.
10707 check_added_monitors(&nodes[0], 1);
10709 let mut monitor_updates = nodes[0].chain_monitor.monitor_updates.lock().unwrap();
10710 let monitor_updates_1 = monitor_updates.get(&channel_id_1).unwrap();
10711 assert_eq!(monitor_updates_1.len(), 1);
10712 assert_eq!(monitor_updates_1[0].update_id, CLOSED_CHANNEL_UPDATE_ID);
10715 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
10716 match msg_events[0] {
10717 MessageSendEvent::HandleError { .. } => (),
10718 _ => panic!("Unexpected message."),
10721 // We broadcast the commitment transaction as part of the force-close.
10723 let broadcasted_txs = nodes[0].tx_broadcaster.txn_broadcast();
10724 assert_eq!(broadcasted_txs.len(), 1);
10725 assert!(broadcasted_txs[0].txid() != tx.txid());
10726 assert_eq!(broadcasted_txs[0].input.len(), 1);
10727 assert_eq!(broadcasted_txs[0].input[0].previous_output.txid, tx.txid());
10730 // All channels in the batch should close immediately.
10731 check_closed_events(&nodes[0], &[
10732 ExpectedCloseEvent {
10733 channel_id: Some(channel_id_1),
10734 discard_funding: true,
10735 channel_funding_txo: Some(funding_txo_1),
10736 user_channel_id: Some(42),
10737 ..Default::default()
10739 ExpectedCloseEvent {
10740 channel_id: Some(channel_id_2),
10741 discard_funding: true,
10742 channel_funding_txo: Some(funding_txo_2),
10743 user_channel_id: Some(43),
10744 ..Default::default()
10748 // Ensure the channels don't exist anymore.
10749 assert!(nodes[0].node.list_channels().is_empty());
10753 fn test_batch_funding_close_after_funding_signed() {
10754 let chanmon_cfgs = create_chanmon_cfgs(3);
10755 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10756 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10757 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10759 // Initiate channel opening and create the batch channel funding transaction.
10760 let (tx, funding_created_msgs) = create_batch_channel_funding(&nodes[0], &[
10761 (&nodes[1], 100_000, 0, 42, None),
10762 (&nodes[2], 200_000, 0, 43, None),
10765 // Go through the funding_created and funding_signed flow with node 1.
10766 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[0]);
10767 check_added_monitors(&nodes[1], 1);
10768 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
10770 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10771 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
10772 check_added_monitors(&nodes[0], 1);
10774 // Go through the funding_created and funding_signed flow with node 2.
10775 nodes[2].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[1]);
10776 check_added_monitors(&nodes[2], 1);
10777 expect_channel_pending_event(&nodes[2], &nodes[0].node.get_our_node_id());
10779 let funding_signed_msg = get_event_msg!(nodes[2], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10780 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
10781 nodes[0].node.handle_funding_signed(&nodes[2].node.get_our_node_id(), &funding_signed_msg);
10782 check_added_monitors(&nodes[0], 1);
10784 // The transaction should not have been broadcast before all channels are ready.
10785 assert_eq!(nodes[0].tx_broadcaster.txn_broadcast().len(), 0);
10787 // Force-close the channel for which we've completed the initial monitor.
10788 let funding_txo_1 = OutPoint { txid: tx.txid(), index: 0 };
10789 let funding_txo_2 = OutPoint { txid: tx.txid(), index: 1 };
10790 let channel_id_1 = ChannelId::v1_from_funding_outpoint(funding_txo_1);
10791 let channel_id_2 = ChannelId::v1_from_funding_outpoint(funding_txo_2);
10792 nodes[0].node.force_close_broadcasting_latest_txn(&channel_id_1, &nodes[1].node.get_our_node_id()).unwrap();
10793 check_added_monitors(&nodes[0], 2);
10795 let mut monitor_updates = nodes[0].chain_monitor.monitor_updates.lock().unwrap();
10796 let monitor_updates_1 = monitor_updates.get(&channel_id_1).unwrap();
10797 assert_eq!(monitor_updates_1.len(), 1);
10798 assert_eq!(monitor_updates_1[0].update_id, CLOSED_CHANNEL_UPDATE_ID);
10799 let monitor_updates_2 = monitor_updates.get(&channel_id_2).unwrap();
10800 assert_eq!(monitor_updates_2.len(), 1);
10801 assert_eq!(monitor_updates_2[0].update_id, CLOSED_CHANNEL_UPDATE_ID);
10803 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
10804 match msg_events[0] {
10805 MessageSendEvent::HandleError { .. } => (),
10806 _ => panic!("Unexpected message."),
10809 // We broadcast the commitment transaction as part of the force-close.
10811 let broadcasted_txs = nodes[0].tx_broadcaster.txn_broadcast();
10812 assert_eq!(broadcasted_txs.len(), 1);
10813 assert!(broadcasted_txs[0].txid() != tx.txid());
10814 assert_eq!(broadcasted_txs[0].input.len(), 1);
10815 assert_eq!(broadcasted_txs[0].input[0].previous_output.txid, tx.txid());
10818 // All channels in the batch should close immediately.
10819 check_closed_events(&nodes[0], &[
10820 ExpectedCloseEvent {
10821 channel_id: Some(channel_id_1),
10822 discard_funding: true,
10823 channel_funding_txo: Some(funding_txo_1),
10824 user_channel_id: Some(42),
10825 ..Default::default()
10827 ExpectedCloseEvent {
10828 channel_id: Some(channel_id_2),
10829 discard_funding: true,
10830 channel_funding_txo: Some(funding_txo_2),
10831 user_channel_id: Some(43),
10832 ..Default::default()
10836 // Ensure the channels don't exist anymore.
10837 assert!(nodes[0].node.list_channels().is_empty());
10840 fn do_test_funding_and_commitment_tx_confirm_same_block(confirm_remote_commitment: bool) {
10841 // Tests that a node will forget the channel (when it only requires 1 confirmation) if the
10842 // funding and commitment transaction confirm in the same block.
10843 let chanmon_cfgs = create_chanmon_cfgs(2);
10844 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10845 let mut min_depth_1_block_cfg = test_default_channel_config();
10846 min_depth_1_block_cfg.channel_handshake_config.minimum_depth = 1;
10847 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(min_depth_1_block_cfg), Some(min_depth_1_block_cfg)]);
10848 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10850 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
10851 let chan_id = ChannelId::v1_from_funding_outpoint(chain::transaction::OutPoint { txid: funding_tx.txid(), index: 0 });
10853 assert_eq!(nodes[0].node.list_channels().len(), 1);
10854 assert_eq!(nodes[1].node.list_channels().len(), 1);
10856 let (closing_node, other_node) = if confirm_remote_commitment {
10857 (&nodes[1], &nodes[0])
10859 (&nodes[0], &nodes[1])
10862 closing_node.node.force_close_broadcasting_latest_txn(&chan_id, &other_node.node.get_our_node_id()).unwrap();
10863 let mut msg_events = closing_node.node.get_and_clear_pending_msg_events();
10864 assert_eq!(msg_events.len(), 1);
10865 match msg_events.pop().unwrap() {
10866 MessageSendEvent::HandleError { action: msgs::ErrorAction::DisconnectPeer { .. }, .. } => {},
10867 _ => panic!("Unexpected event"),
10869 check_added_monitors(closing_node, 1);
10870 check_closed_event(closing_node, 1, ClosureReason::HolderForceClosed, false, &[other_node.node.get_our_node_id()], 1_000_000);
10872 let commitment_tx = {
10873 let mut txn = closing_node.tx_broadcaster.txn_broadcast();
10874 assert_eq!(txn.len(), 1);
10875 let commitment_tx = txn.pop().unwrap();
10876 check_spends!(commitment_tx, funding_tx);
10880 mine_transactions(&nodes[0], &[&funding_tx, &commitment_tx]);
10881 mine_transactions(&nodes[1], &[&funding_tx, &commitment_tx]);
10883 check_closed_broadcast(other_node, 1, true);
10884 check_added_monitors(other_node, 1);
10885 check_closed_event(other_node, 1, ClosureReason::CommitmentTxConfirmed, false, &[closing_node.node.get_our_node_id()], 1_000_000);
10887 assert!(nodes[0].node.list_channels().is_empty());
10888 assert!(nodes[1].node.list_channels().is_empty());
10892 fn test_funding_and_commitment_tx_confirm_same_block() {
10893 do_test_funding_and_commitment_tx_confirm_same_block(false);
10894 do_test_funding_and_commitment_tx_confirm_same_block(true);