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 { total_fee_earned_msat, prev_channel_id, claim_from_onchain_tx,
2893 next_channel_id, outbound_amount_forwarded_msat, ..
2895 assert_eq!(total_fee_earned_msat, Some(1000));
2896 assert_eq!(prev_channel_id, chan_id);
2897 assert_eq!(claim_from_onchain_tx, true);
2898 assert_eq!(next_channel_id, Some(chan_2.2));
2899 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2903 match forwarded_events[2] {
2904 Event::PaymentForwarded { total_fee_earned_msat, prev_channel_id, claim_from_onchain_tx,
2905 next_channel_id, outbound_amount_forwarded_msat, ..
2907 assert_eq!(total_fee_earned_msat, Some(1000));
2908 assert_eq!(prev_channel_id, chan_id);
2909 assert_eq!(claim_from_onchain_tx, true);
2910 assert_eq!(next_channel_id, Some(chan_2.2));
2911 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2915 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2917 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2918 assert_eq!(added_monitors.len(), 2);
2919 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2920 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2921 added_monitors.clear();
2923 assert_eq!(events.len(), 3);
2925 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
2926 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
2928 match nodes_2_event {
2929 MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { .. }, node_id: _ } => {},
2930 _ => panic!("Unexpected event"),
2933 match nodes_0_event {
2934 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, .. } } => {
2935 assert!(update_add_htlcs.is_empty());
2936 assert!(update_fail_htlcs.is_empty());
2937 assert_eq!(update_fulfill_htlcs.len(), 1);
2938 assert!(update_fail_malformed_htlcs.is_empty());
2939 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2941 _ => panic!("Unexpected event"),
2944 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
2946 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2947 _ => panic!("Unexpected event"),
2950 macro_rules! check_tx_local_broadcast {
2951 ($node: expr, $htlc_offered: expr, $commitment_tx: expr) => { {
2952 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2953 assert_eq!(node_txn.len(), 2);
2954 // Node[1]: 2 * HTLC-timeout tx
2955 // Node[0]: 2 * HTLC-timeout tx
2956 check_spends!(node_txn[0], $commitment_tx);
2957 check_spends!(node_txn[1], $commitment_tx);
2958 assert_ne!(node_txn[0].lock_time, LockTime::ZERO);
2959 assert_ne!(node_txn[1].lock_time, LockTime::ZERO);
2961 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2962 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2963 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2964 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2966 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2967 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2968 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2969 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2974 // nodes[1] now broadcasts its own timeout-claim of the output that nodes[2] just claimed via success.
2975 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0]);
2977 // Broadcast legit commitment tx from A on B's chain
2978 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2979 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2980 check_spends!(node_a_commitment_tx[0], chan_1.3);
2981 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2982 check_closed_broadcast!(nodes[1], true);
2983 check_added_monitors!(nodes[1], 1);
2984 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2985 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2986 assert!(node_txn.len() == 1 || node_txn.len() == 3); // HTLC-Success, 2* RBF bumps of above HTLC txn
2987 let commitment_spend =
2988 if node_txn.len() == 1 {
2991 // Certain `ConnectStyle`s will cause RBF bumps of the previous HTLC transaction to be broadcast.
2992 // FullBlockViaListen
2993 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2994 check_spends!(node_txn[1], commitment_tx[0]);
2995 check_spends!(node_txn[2], commitment_tx[0]);
2996 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2999 check_spends!(node_txn[0], commitment_tx[0]);
3000 check_spends!(node_txn[1], commitment_tx[0]);
3001 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
3006 check_spends!(commitment_spend, node_a_commitment_tx[0]);
3007 assert_eq!(commitment_spend.input.len(), 2);
3008 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3009 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3010 assert_eq!(commitment_spend.lock_time.to_consensus_u32(), nodes[1].best_block_info().1);
3011 assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
3012 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
3013 // we already checked the same situation with A.
3015 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
3016 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()]));
3017 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
3018 check_closed_broadcast!(nodes[0], true);
3019 check_added_monitors!(nodes[0], 1);
3020 let events = nodes[0].node.get_and_clear_pending_events();
3021 assert_eq!(events.len(), 5);
3022 let mut first_claimed = false;
3023 for event in events {
3025 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3026 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
3027 assert!(!first_claimed);
3028 first_claimed = true;
3030 assert_eq!(payment_preimage, our_payment_preimage_2);
3031 assert_eq!(payment_hash, payment_hash_2);
3034 Event::PaymentPathSuccessful { .. } => {},
3035 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
3036 _ => panic!("Unexpected event"),
3039 check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0]);
3042 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
3043 // Test that in case of a unilateral close onchain, we detect the state of output and
3044 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
3045 // broadcasting the right event to other nodes in payment path.
3046 // A ------------------> B ----------------------> C (timeout)
3047 // B's commitment tx C's commitment tx
3049 // B's HTLC timeout tx B's timeout tx
3051 let chanmon_cfgs = create_chanmon_cfgs(3);
3052 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3053 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3054 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3055 *nodes[0].connect_style.borrow_mut() = connect_style;
3056 *nodes[1].connect_style.borrow_mut() = connect_style;
3057 *nodes[2].connect_style.borrow_mut() = connect_style;
3059 // Create some intial channels
3060 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
3061 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3063 // Rebalance the network a bit by relaying one payment thorugh all the channels...
3064 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
3065 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
3067 let (_payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
3069 // Broadcast legit commitment tx from C on B's chain
3070 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
3071 check_spends!(commitment_tx[0], chan_2.3);
3072 nodes[2].node.fail_htlc_backwards(&payment_hash);
3073 check_added_monitors!(nodes[2], 0);
3074 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
3075 check_added_monitors!(nodes[2], 1);
3077 let events = nodes[2].node.get_and_clear_pending_msg_events();
3078 assert_eq!(events.len(), 1);
3080 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, .. } } => {
3081 assert!(update_add_htlcs.is_empty());
3082 assert!(!update_fail_htlcs.is_empty());
3083 assert!(update_fulfill_htlcs.is_empty());
3084 assert!(update_fail_malformed_htlcs.is_empty());
3085 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
3087 _ => panic!("Unexpected event"),
3089 mine_transaction(&nodes[2], &commitment_tx[0]);
3090 check_closed_broadcast!(nodes[2], true);
3091 check_added_monitors!(nodes[2], 1);
3092 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
3093 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
3094 assert_eq!(node_txn.len(), 0);
3096 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
3097 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
3098 mine_transaction(&nodes[1], &commitment_tx[0]);
3099 check_closed_event!(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false
3100 , [nodes[2].node.get_our_node_id()], 100000);
3101 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
3103 let mut txn = nodes[1].tx_broadcaster.txn_broadcast();
3104 if nodes[1].connect_style.borrow().skips_blocks() {
3105 assert_eq!(txn.len(), 1);
3107 assert_eq!(txn.len(), 3); // Two extra fee bumps for timeout transaction
3109 txn.iter().for_each(|tx| check_spends!(tx, commitment_tx[0]));
3110 assert_eq!(txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3114 mine_transaction(&nodes[1], &timeout_tx);
3115 check_added_monitors!(nodes[1], 1);
3116 check_closed_broadcast!(nodes[1], true);
3118 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3120 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 }]);
3121 check_added_monitors!(nodes[1], 1);
3122 let events = nodes[1].node.get_and_clear_pending_msg_events();
3123 assert_eq!(events.len(), 1);
3125 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, .. } } => {
3126 assert!(update_add_htlcs.is_empty());
3127 assert!(!update_fail_htlcs.is_empty());
3128 assert!(update_fulfill_htlcs.is_empty());
3129 assert!(update_fail_malformed_htlcs.is_empty());
3130 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3132 _ => panic!("Unexpected event"),
3135 // Broadcast legit commitment tx from B on A's chain
3136 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3137 check_spends!(commitment_tx[0], chan_1.3);
3139 mine_transaction(&nodes[0], &commitment_tx[0]);
3140 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
3142 check_closed_broadcast!(nodes[0], true);
3143 check_added_monitors!(nodes[0], 1);
3144 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
3145 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // 1 timeout tx
3146 assert_eq!(node_txn.len(), 1);
3147 check_spends!(node_txn[0], commitment_tx[0]);
3148 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3152 fn test_htlc_on_chain_timeout() {
3153 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3154 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3155 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3159 fn test_simple_commitment_revoked_fail_backward() {
3160 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3161 // and fail backward accordingly.
3163 let chanmon_cfgs = create_chanmon_cfgs(3);
3164 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3165 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3166 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3168 // Create some initial channels
3169 create_announced_chan_between_nodes(&nodes, 0, 1);
3170 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3172 let (payment_preimage, _payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3173 // Get the will-be-revoked local txn from nodes[2]
3174 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3175 // Revoke the old state
3176 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3178 let (_, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3180 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3181 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
3182 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3183 check_added_monitors!(nodes[1], 1);
3184 check_closed_broadcast!(nodes[1], true);
3186 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 }]);
3187 check_added_monitors!(nodes[1], 1);
3188 let events = nodes[1].node.get_and_clear_pending_msg_events();
3189 assert_eq!(events.len(), 1);
3191 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, .. } } => {
3192 assert!(update_add_htlcs.is_empty());
3193 assert_eq!(update_fail_htlcs.len(), 1);
3194 assert!(update_fulfill_htlcs.is_empty());
3195 assert!(update_fail_malformed_htlcs.is_empty());
3196 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3198 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3199 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3200 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3202 _ => panic!("Unexpected event"),
3206 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3207 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3208 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3209 // commitment transaction anymore.
3210 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3211 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3212 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3213 // technically disallowed and we should probably handle it reasonably.
3214 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3215 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3217 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3218 // commitment_signed (implying it will be in the latest remote commitment transaction).
3219 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3220 // and once they revoke the previous commitment transaction (allowing us to send a new
3221 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3222 let chanmon_cfgs = create_chanmon_cfgs(3);
3223 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3224 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3225 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3227 // Create some initial channels
3228 create_announced_chan_between_nodes(&nodes, 0, 1);
3229 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3231 let (payment_preimage, _payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3232 // Get the will-be-revoked local txn from nodes[2]
3233 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3234 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3235 // Revoke the old state
3236 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3238 let value = if use_dust {
3239 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3240 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3241 nodes[2].node.per_peer_state.read().unwrap().get(&nodes[1].node.get_our_node_id())
3242 .unwrap().lock().unwrap().channel_by_id.get(&chan_2.2).unwrap().context().holder_dust_limit_satoshis * 1000
3245 let (_, first_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3246 let (_, second_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3247 let (_, third_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3249 nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3250 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3251 check_added_monitors!(nodes[2], 1);
3252 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3253 assert!(updates.update_add_htlcs.is_empty());
3254 assert!(updates.update_fulfill_htlcs.is_empty());
3255 assert!(updates.update_fail_malformed_htlcs.is_empty());
3256 assert_eq!(updates.update_fail_htlcs.len(), 1);
3257 assert!(updates.update_fee.is_none());
3258 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3259 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3260 // Drop the last RAA from 3 -> 2
3262 nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3263 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3264 check_added_monitors!(nodes[2], 1);
3265 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3266 assert!(updates.update_add_htlcs.is_empty());
3267 assert!(updates.update_fulfill_htlcs.is_empty());
3268 assert!(updates.update_fail_malformed_htlcs.is_empty());
3269 assert_eq!(updates.update_fail_htlcs.len(), 1);
3270 assert!(updates.update_fee.is_none());
3271 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3272 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3273 check_added_monitors!(nodes[1], 1);
3274 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3275 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3276 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3277 check_added_monitors!(nodes[2], 1);
3279 nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3280 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3281 check_added_monitors!(nodes[2], 1);
3282 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3283 assert!(updates.update_add_htlcs.is_empty());
3284 assert!(updates.update_fulfill_htlcs.is_empty());
3285 assert!(updates.update_fail_malformed_htlcs.is_empty());
3286 assert_eq!(updates.update_fail_htlcs.len(), 1);
3287 assert!(updates.update_fee.is_none());
3288 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3289 // At this point first_payment_hash has dropped out of the latest two commitment
3290 // transactions that nodes[1] is tracking...
3291 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3292 check_added_monitors!(nodes[1], 1);
3293 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3294 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3295 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3296 check_added_monitors!(nodes[2], 1);
3298 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3299 // on nodes[2]'s RAA.
3300 let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3301 nodes[1].node.send_payment_with_route(&route, fourth_payment_hash,
3302 RecipientOnionFields::secret_only(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3303 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3304 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3305 check_added_monitors!(nodes[1], 0);
3308 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3309 // One monitor for the new revocation preimage, no second on as we won't generate a new
3310 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3311 check_added_monitors!(nodes[1], 1);
3312 let events = nodes[1].node.get_and_clear_pending_events();
3313 assert_eq!(events.len(), 2);
3315 Event::PendingHTLCsForwardable { .. } => { },
3316 _ => panic!("Unexpected event"),
3319 Event::HTLCHandlingFailed { .. } => { },
3320 _ => panic!("Unexpected event"),
3322 // Deliberately don't process the pending fail-back so they all fail back at once after
3323 // block connection just like the !deliver_bs_raa case
3326 let mut failed_htlcs = HashSet::new();
3327 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3329 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3330 check_added_monitors!(nodes[1], 1);
3331 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3333 let events = nodes[1].node.get_and_clear_pending_events();
3334 assert_eq!(events.len(), if deliver_bs_raa { 3 + nodes.len() - 1 } else { 4 + nodes.len() });
3335 assert!(events.iter().any(|ev| matches!(
3337 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. }
3339 assert!(events.iter().any(|ev| matches!(
3341 Event::PaymentPathFailed { ref payment_hash, .. } if *payment_hash == fourth_payment_hash
3343 assert!(events.iter().any(|ev| matches!(
3345 Event::PaymentFailed { ref payment_hash, .. } if *payment_hash == fourth_payment_hash
3348 nodes[1].node.process_pending_htlc_forwards();
3349 check_added_monitors!(nodes[1], 1);
3351 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
3352 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3355 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3356 match nodes_2_event {
3357 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, .. } } => {
3358 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3359 assert_eq!(update_add_htlcs.len(), 1);
3360 assert!(update_fulfill_htlcs.is_empty());
3361 assert!(update_fail_htlcs.is_empty());
3362 assert!(update_fail_malformed_htlcs.is_empty());
3364 _ => panic!("Unexpected event"),
3368 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3369 match nodes_2_event {
3370 MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { msg: Some(msgs::ErrorMessage { channel_id, ref data }) }, node_id: _ } => {
3371 assert_eq!(channel_id, chan_2.2);
3372 assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3374 _ => panic!("Unexpected event"),
3377 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
3378 match nodes_0_event {
3379 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, .. } } => {
3380 assert!(update_add_htlcs.is_empty());
3381 assert_eq!(update_fail_htlcs.len(), 3);
3382 assert!(update_fulfill_htlcs.is_empty());
3383 assert!(update_fail_malformed_htlcs.is_empty());
3384 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3386 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3387 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3388 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3390 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3392 let events = nodes[0].node.get_and_clear_pending_events();
3393 assert_eq!(events.len(), 6);
3395 Event::PaymentPathFailed { ref payment_hash, ref failure, .. } => {
3396 assert!(failed_htlcs.insert(payment_hash.0));
3397 // If we delivered B's RAA we got an unknown preimage error, not something
3398 // that we should update our routing table for.
3399 if !deliver_bs_raa {
3400 if let PathFailure::OnPath { network_update: Some(_) } = failure { } else { panic!("Unexpected path failure") }
3403 _ => panic!("Unexpected event"),
3406 Event::PaymentFailed { ref payment_hash, .. } => {
3407 assert_eq!(*payment_hash, first_payment_hash);
3409 _ => panic!("Unexpected event"),
3412 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3413 assert!(failed_htlcs.insert(payment_hash.0));
3415 _ => panic!("Unexpected event"),
3418 Event::PaymentFailed { ref payment_hash, .. } => {
3419 assert_eq!(*payment_hash, second_payment_hash);
3421 _ => panic!("Unexpected event"),
3424 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3425 assert!(failed_htlcs.insert(payment_hash.0));
3427 _ => panic!("Unexpected event"),
3430 Event::PaymentFailed { ref payment_hash, .. } => {
3431 assert_eq!(*payment_hash, third_payment_hash);
3433 _ => panic!("Unexpected event"),
3436 _ => panic!("Unexpected event"),
3439 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
3441 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3442 _ => panic!("Unexpected event"),
3445 assert!(failed_htlcs.contains(&first_payment_hash.0));
3446 assert!(failed_htlcs.contains(&second_payment_hash.0));
3447 assert!(failed_htlcs.contains(&third_payment_hash.0));
3451 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3452 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3453 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3454 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3455 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3459 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3460 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3461 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3462 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3463 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3467 fn fail_backward_pending_htlc_upon_channel_failure() {
3468 let chanmon_cfgs = create_chanmon_cfgs(2);
3469 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3470 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3471 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3472 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
3474 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3476 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3477 nodes[0].node.send_payment_with_route(&route, payment_hash, RecipientOnionFields::secret_only(payment_secret),
3478 PaymentId(payment_hash.0)).unwrap();
3479 check_added_monitors!(nodes[0], 1);
3481 let payment_event = {
3482 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3483 assert_eq!(events.len(), 1);
3484 SendEvent::from_event(events.remove(0))
3486 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3487 assert_eq!(payment_event.msgs.len(), 1);
3490 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3491 let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3493 nodes[0].node.send_payment_with_route(&route, failed_payment_hash,
3494 RecipientOnionFields::secret_only(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3495 check_added_monitors!(nodes[0], 0);
3497 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3500 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3502 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3504 let secp_ctx = Secp256k1::new();
3505 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3506 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3507 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(
3508 &route.paths[0], 50_000, RecipientOnionFields::secret_only(payment_secret), current_height, &None).unwrap();
3509 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3510 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
3512 // Send a 0-msat update_add_htlc to fail the channel.
3513 let update_add_htlc = msgs::UpdateAddHTLC {
3519 onion_routing_packet,
3520 skimmed_fee_msat: None,
3521 blinding_point: None,
3523 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3525 let events = nodes[0].node.get_and_clear_pending_events();
3526 assert_eq!(events.len(), 3);
3527 // Check that Alice fails backward the pending HTLC from the second payment.
3529 Event::PaymentPathFailed { payment_hash, .. } => {
3530 assert_eq!(payment_hash, failed_payment_hash);
3532 _ => panic!("Unexpected event"),
3535 Event::PaymentFailed { payment_hash, .. } => {
3536 assert_eq!(payment_hash, failed_payment_hash);
3538 _ => panic!("Unexpected event"),
3541 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3542 assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3544 _ => panic!("Unexpected event {:?}", events[1]),
3546 check_closed_broadcast!(nodes[0], true);
3547 check_added_monitors!(nodes[0], 1);
3551 fn test_htlc_ignore_latest_remote_commitment() {
3552 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3553 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3554 let chanmon_cfgs = create_chanmon_cfgs(2);
3555 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3556 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3557 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3558 if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3559 // We rely on the ability to connect a block redundantly, which isn't allowed via
3560 // `chain::Listen`, so we never run the test if we randomly get assigned that
3564 let funding_tx = create_announced_chan_between_nodes(&nodes, 0, 1).3;
3566 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3567 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3568 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3569 check_closed_broadcast!(nodes[0], true);
3570 check_added_monitors!(nodes[0], 1);
3571 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
3573 let node_txn = nodes[0].tx_broadcaster.unique_txn_broadcast();
3574 assert_eq!(node_txn.len(), 2);
3575 check_spends!(node_txn[0], funding_tx);
3576 check_spends!(node_txn[1], node_txn[0]);
3578 let block = create_dummy_block(nodes[1].best_block_hash(), 42, vec![node_txn[0].clone()]);
3579 connect_block(&nodes[1], &block);
3580 check_closed_broadcast!(nodes[1], true);
3581 check_added_monitors!(nodes[1], 1);
3582 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
3584 // Duplicate the connect_block call since this may happen due to other listeners
3585 // registering new transactions
3586 connect_block(&nodes[1], &block);
3590 fn test_force_close_fail_back() {
3591 // Check which HTLCs are failed-backwards on channel force-closure
3592 let chanmon_cfgs = create_chanmon_cfgs(3);
3593 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3594 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3595 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3596 create_announced_chan_between_nodes(&nodes, 0, 1);
3597 create_announced_chan_between_nodes(&nodes, 1, 2);
3599 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3601 let mut payment_event = {
3602 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
3603 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3604 check_added_monitors!(nodes[0], 1);
3606 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3607 assert_eq!(events.len(), 1);
3608 SendEvent::from_event(events.remove(0))
3611 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3612 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3614 expect_pending_htlcs_forwardable!(nodes[1]);
3616 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3617 assert_eq!(events_2.len(), 1);
3618 payment_event = SendEvent::from_event(events_2.remove(0));
3619 assert_eq!(payment_event.msgs.len(), 1);
3621 check_added_monitors!(nodes[1], 1);
3622 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3623 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3624 check_added_monitors!(nodes[2], 1);
3625 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3627 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3628 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3629 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3631 nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3632 check_closed_broadcast!(nodes[2], true);
3633 check_added_monitors!(nodes[2], 1);
3634 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
3635 let commitment_tx = {
3636 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3637 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3638 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3639 // back to nodes[1] upon timeout otherwise.
3640 assert_eq!(node_txn.len(), 1);
3644 mine_transaction(&nodes[1], &commitment_tx);
3646 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3647 check_closed_broadcast!(nodes[1], true);
3648 check_added_monitors!(nodes[1], 1);
3649 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
3651 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3653 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3654 .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);
3656 mine_transaction(&nodes[2], &commitment_tx);
3657 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcast();
3658 assert_eq!(node_txn.len(), if nodes[2].connect_style.borrow().updates_best_block_first() { 2 } else { 1 });
3659 let htlc_tx = node_txn.pop().unwrap();
3660 assert_eq!(htlc_tx.input.len(), 1);
3661 assert_eq!(htlc_tx.input[0].previous_output.txid, commitment_tx.txid());
3662 assert_eq!(htlc_tx.lock_time, LockTime::ZERO); // Must be an HTLC-Success
3663 assert_eq!(htlc_tx.input[0].witness.len(), 5); // Must be an HTLC-Success
3665 check_spends!(htlc_tx, commitment_tx);
3669 fn test_dup_events_on_peer_disconnect() {
3670 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3671 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3672 // as we used to generate the event immediately upon receipt of the payment preimage in the
3673 // update_fulfill_htlc message.
3675 let chanmon_cfgs = create_chanmon_cfgs(2);
3676 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3677 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3678 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3679 create_announced_chan_between_nodes(&nodes, 0, 1);
3681 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3683 nodes[1].node.claim_funds(payment_preimage);
3684 expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3685 check_added_monitors!(nodes[1], 1);
3686 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3687 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3688 expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
3690 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3691 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3693 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3694 reconnect_args.pending_htlc_claims.0 = 1;
3695 reconnect_nodes(reconnect_args);
3696 expect_payment_path_successful!(nodes[0]);
3700 fn test_peer_disconnected_before_funding_broadcasted() {
3701 // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3702 // before the funding transaction has been broadcasted.
3703 let chanmon_cfgs = create_chanmon_cfgs(2);
3704 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3705 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3706 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3708 // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3709 // broadcasted, even though it's created by `nodes[0]`.
3710 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();
3711 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3712 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
3713 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3714 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
3716 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3717 assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3719 assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3721 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3722 assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3724 // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3725 // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3728 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3731 // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3732 // disconnected before the funding transaction was broadcasted.
3733 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3734 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3736 check_closed_event!(&nodes[0], 2, ClosureReason::DisconnectedPeer, true
3737 , [nodes[1].node.get_our_node_id()], 1000000);
3738 check_closed_event!(&nodes[1], 1, ClosureReason::DisconnectedPeer, false
3739 , [nodes[0].node.get_our_node_id()], 1000000);
3743 fn test_simple_peer_disconnect() {
3744 // Test that we can reconnect when there are no lost messages
3745 let chanmon_cfgs = create_chanmon_cfgs(3);
3746 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3747 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3748 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3749 create_announced_chan_between_nodes(&nodes, 0, 1);
3750 create_announced_chan_between_nodes(&nodes, 1, 2);
3752 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3753 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3754 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3755 reconnect_args.send_channel_ready = (true, true);
3756 reconnect_nodes(reconnect_args);
3758 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3759 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3760 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3761 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3763 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3764 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3765 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3767 let (payment_preimage_3, payment_hash_3, ..) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3768 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3769 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3770 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3772 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3773 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3775 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3776 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3778 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3779 reconnect_args.pending_cell_htlc_fails.0 = 1;
3780 reconnect_args.pending_cell_htlc_claims.0 = 1;
3781 reconnect_nodes(reconnect_args);
3783 let events = nodes[0].node.get_and_clear_pending_events();
3784 assert_eq!(events.len(), 4);
3786 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3787 assert_eq!(payment_preimage, payment_preimage_3);
3788 assert_eq!(payment_hash, payment_hash_3);
3790 _ => panic!("Unexpected event"),
3793 Event::PaymentPathSuccessful { .. } => {},
3794 _ => panic!("Unexpected event"),
3797 Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3798 assert_eq!(payment_hash, payment_hash_5);
3799 assert!(payment_failed_permanently);
3801 _ => panic!("Unexpected event"),
3804 Event::PaymentFailed { payment_hash, .. } => {
3805 assert_eq!(payment_hash, payment_hash_5);
3807 _ => panic!("Unexpected event"),
3810 check_added_monitors(&nodes[0], 1);
3812 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3813 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3816 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3817 // Test that we can reconnect when in-flight HTLC updates get dropped
3818 let chanmon_cfgs = create_chanmon_cfgs(2);
3819 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3820 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3821 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3823 let mut as_channel_ready = None;
3824 let channel_id = if messages_delivered == 0 {
3825 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3826 as_channel_ready = Some(channel_ready);
3827 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3828 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3829 // it before the channel_reestablish message.
3832 create_announced_chan_between_nodes(&nodes, 0, 1).2
3835 let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3837 let payment_event = {
3838 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
3839 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3840 check_added_monitors!(nodes[0], 1);
3842 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3843 assert_eq!(events.len(), 1);
3844 SendEvent::from_event(events.remove(0))
3846 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3848 if messages_delivered < 2 {
3849 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3851 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3852 if messages_delivered >= 3 {
3853 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3854 check_added_monitors!(nodes[1], 1);
3855 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3857 if messages_delivered >= 4 {
3858 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3859 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3860 check_added_monitors!(nodes[0], 1);
3862 if messages_delivered >= 5 {
3863 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3864 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3865 // No commitment_signed so get_event_msg's assert(len == 1) passes
3866 check_added_monitors!(nodes[0], 1);
3868 if messages_delivered >= 6 {
3869 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3870 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3871 check_added_monitors!(nodes[1], 1);
3878 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3879 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3880 if messages_delivered < 3 {
3881 if simulate_broken_lnd {
3882 // lnd has a long-standing bug where they send a channel_ready prior to a
3883 // channel_reestablish if you reconnect prior to channel_ready time.
3885 // Here we simulate that behavior, delivering a channel_ready immediately on
3886 // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3887 // in `reconnect_nodes` but we currently don't fail based on that.
3889 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3890 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3892 // Even if the channel_ready messages get exchanged, as long as nothing further was
3893 // received on either side, both sides will need to resend them.
3894 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3895 reconnect_args.send_channel_ready = (true, true);
3896 reconnect_args.pending_htlc_adds.1 = 1;
3897 reconnect_nodes(reconnect_args);
3898 } else if messages_delivered == 3 {
3899 // nodes[0] still wants its RAA + commitment_signed
3900 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3901 reconnect_args.pending_responding_commitment_signed.0 = true;
3902 reconnect_args.pending_raa.0 = true;
3903 reconnect_nodes(reconnect_args);
3904 } else if messages_delivered == 4 {
3905 // nodes[0] still wants its commitment_signed
3906 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3907 reconnect_args.pending_responding_commitment_signed.0 = true;
3908 reconnect_nodes(reconnect_args);
3909 } else if messages_delivered == 5 {
3910 // nodes[1] still wants its final RAA
3911 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3912 reconnect_args.pending_raa.1 = true;
3913 reconnect_nodes(reconnect_args);
3914 } else if messages_delivered == 6 {
3915 // Everything was delivered...
3916 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3919 let events_1 = nodes[1].node.get_and_clear_pending_events();
3920 if messages_delivered == 0 {
3921 assert_eq!(events_1.len(), 2);
3923 Event::ChannelReady { .. } => { },
3924 _ => panic!("Unexpected event"),
3927 Event::PendingHTLCsForwardable { .. } => { },
3928 _ => panic!("Unexpected event"),
3931 assert_eq!(events_1.len(), 1);
3933 Event::PendingHTLCsForwardable { .. } => { },
3934 _ => panic!("Unexpected event"),
3938 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3939 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3940 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3942 nodes[1].node.process_pending_htlc_forwards();
3944 let events_2 = nodes[1].node.get_and_clear_pending_events();
3945 assert_eq!(events_2.len(), 1);
3947 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
3948 assert_eq!(payment_hash_1, *payment_hash);
3949 assert_eq!(amount_msat, 1_000_000);
3950 assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3951 assert_eq!(via_channel_id, Some(channel_id));
3953 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3954 assert!(payment_preimage.is_none());
3955 assert_eq!(payment_secret_1, *payment_secret);
3957 _ => panic!("expected PaymentPurpose::InvoicePayment")
3960 _ => panic!("Unexpected event"),
3963 nodes[1].node.claim_funds(payment_preimage_1);
3964 check_added_monitors!(nodes[1], 1);
3965 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3967 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3968 assert_eq!(events_3.len(), 1);
3969 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3970 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3971 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3972 assert!(updates.update_add_htlcs.is_empty());
3973 assert!(updates.update_fail_htlcs.is_empty());
3974 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3975 assert!(updates.update_fail_malformed_htlcs.is_empty());
3976 assert!(updates.update_fee.is_none());
3977 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3979 _ => panic!("Unexpected event"),
3982 if messages_delivered >= 1 {
3983 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3985 let events_4 = nodes[0].node.get_and_clear_pending_events();
3986 assert_eq!(events_4.len(), 1);
3988 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3989 assert_eq!(payment_preimage_1, *payment_preimage);
3990 assert_eq!(payment_hash_1, *payment_hash);
3992 _ => panic!("Unexpected event"),
3995 if messages_delivered >= 2 {
3996 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3997 check_added_monitors!(nodes[0], 1);
3998 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4000 if messages_delivered >= 3 {
4001 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4002 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4003 check_added_monitors!(nodes[1], 1);
4005 if messages_delivered >= 4 {
4006 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
4007 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4008 // No commitment_signed so get_event_msg's assert(len == 1) passes
4009 check_added_monitors!(nodes[1], 1);
4011 if messages_delivered >= 5 {
4012 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4013 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4014 check_added_monitors!(nodes[0], 1);
4021 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4022 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4023 if messages_delivered < 2 {
4024 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4025 reconnect_args.pending_htlc_claims.0 = 1;
4026 reconnect_nodes(reconnect_args);
4027 if messages_delivered < 1 {
4028 expect_payment_sent!(nodes[0], payment_preimage_1);
4030 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4032 } else if messages_delivered == 2 {
4033 // nodes[0] still wants its RAA + commitment_signed
4034 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4035 reconnect_args.pending_responding_commitment_signed.1 = true;
4036 reconnect_args.pending_raa.1 = true;
4037 reconnect_nodes(reconnect_args);
4038 } else if messages_delivered == 3 {
4039 // nodes[0] still wants its commitment_signed
4040 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4041 reconnect_args.pending_responding_commitment_signed.1 = true;
4042 reconnect_nodes(reconnect_args);
4043 } else if messages_delivered == 4 {
4044 // nodes[1] still wants its final RAA
4045 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4046 reconnect_args.pending_raa.0 = true;
4047 reconnect_nodes(reconnect_args);
4048 } else if messages_delivered == 5 {
4049 // Everything was delivered...
4050 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
4053 if messages_delivered == 1 || messages_delivered == 2 {
4054 expect_payment_path_successful!(nodes[0]);
4056 if messages_delivered <= 5 {
4057 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4058 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4060 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
4062 if messages_delivered > 2 {
4063 expect_payment_path_successful!(nodes[0]);
4066 // Channel should still work fine...
4067 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4068 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
4069 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4073 fn test_drop_messages_peer_disconnect_a() {
4074 do_test_drop_messages_peer_disconnect(0, true);
4075 do_test_drop_messages_peer_disconnect(0, false);
4076 do_test_drop_messages_peer_disconnect(1, false);
4077 do_test_drop_messages_peer_disconnect(2, false);
4081 fn test_drop_messages_peer_disconnect_b() {
4082 do_test_drop_messages_peer_disconnect(3, false);
4083 do_test_drop_messages_peer_disconnect(4, false);
4084 do_test_drop_messages_peer_disconnect(5, false);
4085 do_test_drop_messages_peer_disconnect(6, false);
4089 fn test_channel_ready_without_best_block_updated() {
4090 // Previously, if we were offline when a funding transaction was locked in, and then we came
4091 // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
4092 // generate a channel_ready until a later best_block_updated. This tests that we generate the
4093 // channel_ready immediately instead.
4094 let chanmon_cfgs = create_chanmon_cfgs(2);
4095 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4096 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4097 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4098 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
4100 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
4102 let conf_height = nodes[0].best_block_info().1 + 1;
4103 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4104 let block_txn = [funding_tx];
4105 let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
4106 let conf_block_header = nodes[0].get_block_header(conf_height);
4107 nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
4109 // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4110 let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4111 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4115 fn test_channel_monitor_skipping_block_when_channel_manager_is_leading() {
4116 let chanmon_cfgs = create_chanmon_cfgs(2);
4117 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4118 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4119 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4121 // Let channel_manager get ahead of chain_monitor by 1 block.
4122 // This is to emulate race-condition where newly added channel_monitor skips processing 1 block,
4123 // in case where client calls block_connect on channel_manager first and then on chain_monitor.
4124 let height_1 = nodes[0].best_block_info().1 + 1;
4125 let mut block_1 = create_dummy_block(nodes[0].best_block_hash(), height_1, Vec::new());
4127 nodes[0].blocks.lock().unwrap().push((block_1.clone(), height_1));
4128 nodes[0].node.block_connected(&block_1, height_1);
4130 // Create channel, and it gets added to chain_monitor in funding_created.
4131 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
4133 // Now, newly added channel_monitor in chain_monitor hasn't processed block_1,
4134 // but it's best_block is block_1, since that was populated by channel_manager, and channel_manager
4135 // was running ahead of chain_monitor at the time of funding_created.
4136 // Later on, subsequent blocks are connected to both channel_manager and chain_monitor.
4137 // Hence, this channel's channel_monitor skipped block_1, directly tries to process subsequent blocks.
4138 confirm_transaction_at(&nodes[0], &funding_tx, nodes[0].best_block_info().1 + 1);
4139 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4141 // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4142 let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4143 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4147 fn test_channel_monitor_skipping_block_when_channel_manager_is_lagging() {
4148 let chanmon_cfgs = create_chanmon_cfgs(2);
4149 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4150 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4151 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4153 // Let chain_monitor get ahead of channel_manager by 1 block.
4154 // This is to emulate race-condition where newly added channel_monitor skips processing 1 block,
4155 // in case where client calls block_connect on chain_monitor first and then on channel_manager.
4156 let height_1 = nodes[0].best_block_info().1 + 1;
4157 let mut block_1 = create_dummy_block(nodes[0].best_block_hash(), height_1, Vec::new());
4159 nodes[0].blocks.lock().unwrap().push((block_1.clone(), height_1));
4160 nodes[0].chain_monitor.chain_monitor.block_connected(&block_1, height_1);
4162 // Create channel, and it gets added to chain_monitor in funding_created.
4163 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
4165 // channel_manager can't really skip block_1, it should get it eventually.
4166 nodes[0].node.block_connected(&block_1, height_1);
4168 // Now, newly added channel_monitor in chain_monitor hasn't processed block_1, it's best_block is
4169 // the block before block_1, since that was populated by channel_manager, and channel_manager was
4170 // running behind at the time of funding_created.
4171 // Later on, subsequent blocks are connected to both channel_manager and chain_monitor.
4172 // Hence, this channel's channel_monitor skipped block_1, directly tries to process subsequent blocks.
4173 confirm_transaction_at(&nodes[0], &funding_tx, nodes[0].best_block_info().1 + 1);
4174 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4176 // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4177 let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4178 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4182 fn test_drop_messages_peer_disconnect_dual_htlc() {
4183 // Test that we can handle reconnecting when both sides of a channel have pending
4184 // commitment_updates when we disconnect.
4185 let chanmon_cfgs = create_chanmon_cfgs(2);
4186 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4187 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4188 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4189 create_announced_chan_between_nodes(&nodes, 0, 1);
4191 let (payment_preimage_1, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
4193 // Now try to send a second payment which will fail to send
4194 let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4195 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
4196 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
4197 check_added_monitors!(nodes[0], 1);
4199 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4200 assert_eq!(events_1.len(), 1);
4202 MessageSendEvent::UpdateHTLCs { .. } => {},
4203 _ => panic!("Unexpected event"),
4206 nodes[1].node.claim_funds(payment_preimage_1);
4207 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4208 check_added_monitors!(nodes[1], 1);
4210 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4211 assert_eq!(events_2.len(), 1);
4213 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 } } => {
4214 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4215 assert!(update_add_htlcs.is_empty());
4216 assert_eq!(update_fulfill_htlcs.len(), 1);
4217 assert!(update_fail_htlcs.is_empty());
4218 assert!(update_fail_malformed_htlcs.is_empty());
4219 assert!(update_fee.is_none());
4221 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4222 let events_3 = nodes[0].node.get_and_clear_pending_events();
4223 assert_eq!(events_3.len(), 1);
4225 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4226 assert_eq!(*payment_preimage, payment_preimage_1);
4227 assert_eq!(*payment_hash, payment_hash_1);
4229 _ => panic!("Unexpected event"),
4232 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4233 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4234 // No commitment_signed so get_event_msg's assert(len == 1) passes
4235 check_added_monitors!(nodes[0], 1);
4237 _ => panic!("Unexpected event"),
4240 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4241 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4243 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
4244 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
4246 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4247 assert_eq!(reestablish_1.len(), 1);
4248 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
4249 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
4251 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4252 assert_eq!(reestablish_2.len(), 1);
4254 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4255 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4256 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4257 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4259 assert!(as_resp.0.is_none());
4260 assert!(bs_resp.0.is_none());
4262 assert!(bs_resp.1.is_none());
4263 assert!(bs_resp.2.is_none());
4265 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4267 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4268 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4269 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4270 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4271 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4272 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4273 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4274 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4275 // No commitment_signed so get_event_msg's assert(len == 1) passes
4276 check_added_monitors!(nodes[1], 1);
4278 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4279 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4280 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4281 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4282 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4283 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4284 assert!(bs_second_commitment_signed.update_fee.is_none());
4285 check_added_monitors!(nodes[1], 1);
4287 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4288 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4289 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4290 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4291 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4292 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4293 assert!(as_commitment_signed.update_fee.is_none());
4294 check_added_monitors!(nodes[0], 1);
4296 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4297 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4298 // No commitment_signed so get_event_msg's assert(len == 1) passes
4299 check_added_monitors!(nodes[0], 1);
4301 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4302 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4303 // No commitment_signed so get_event_msg's assert(len == 1) passes
4304 check_added_monitors!(nodes[1], 1);
4306 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4307 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4308 check_added_monitors!(nodes[1], 1);
4310 expect_pending_htlcs_forwardable!(nodes[1]);
4312 let events_5 = nodes[1].node.get_and_clear_pending_events();
4313 assert_eq!(events_5.len(), 1);
4315 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4316 assert_eq!(payment_hash_2, *payment_hash);
4318 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4319 assert!(payment_preimage.is_none());
4320 assert_eq!(payment_secret_2, *payment_secret);
4322 _ => panic!("expected PaymentPurpose::InvoicePayment")
4325 _ => panic!("Unexpected event"),
4328 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4329 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4330 check_added_monitors!(nodes[0], 1);
4332 expect_payment_path_successful!(nodes[0]);
4333 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4336 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4337 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4338 // to avoid our counterparty failing the channel.
4339 let chanmon_cfgs = create_chanmon_cfgs(2);
4340 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4341 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4342 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4344 create_announced_chan_between_nodes(&nodes, 0, 1);
4346 let our_payment_hash = if send_partial_mpp {
4347 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4348 // Use the utility function send_payment_along_path to send the payment with MPP data which
4349 // indicates there are more HTLCs coming.
4350 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.
4351 let payment_id = PaymentId([42; 32]);
4352 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
4353 RecipientOnionFields::secret_only(payment_secret), payment_id, &route).unwrap();
4354 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
4355 RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id,
4356 &None, session_privs[0]).unwrap();
4357 check_added_monitors!(nodes[0], 1);
4358 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4359 assert_eq!(events.len(), 1);
4360 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4361 // hop should *not* yet generate any PaymentClaimable event(s).
4362 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4365 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4368 let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
4369 connect_block(&nodes[0], &block);
4370 connect_block(&nodes[1], &block);
4371 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4372 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4373 block.header.prev_blockhash = block.block_hash();
4374 connect_block(&nodes[0], &block);
4375 connect_block(&nodes[1], &block);
4378 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4380 check_added_monitors!(nodes[1], 1);
4381 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4382 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4383 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4384 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4385 assert!(htlc_timeout_updates.update_fee.is_none());
4387 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4388 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4389 // 100_000 msat as u64, followed by the height at which we failed back above
4390 let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4391 expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4392 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4396 fn test_htlc_timeout() {
4397 do_test_htlc_timeout(true);
4398 do_test_htlc_timeout(false);
4401 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4402 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4403 let chanmon_cfgs = create_chanmon_cfgs(3);
4404 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4405 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4406 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4407 create_announced_chan_between_nodes(&nodes, 0, 1);
4408 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4410 // Make sure all nodes are at the same starting height
4411 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4412 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4413 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4415 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4416 let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4417 nodes[1].node.send_payment_with_route(&route, first_payment_hash,
4418 RecipientOnionFields::secret_only(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4419 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4420 check_added_monitors!(nodes[1], 1);
4422 // Now attempt to route a second payment, which should be placed in the holding cell
4423 let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4424 let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4425 sending_node.node.send_payment_with_route(&route, second_payment_hash,
4426 RecipientOnionFields::secret_only(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4428 check_added_monitors!(nodes[0], 1);
4429 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4430 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4431 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4432 expect_pending_htlcs_forwardable!(nodes[1]);
4434 check_added_monitors!(nodes[1], 0);
4436 connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4437 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4438 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4439 connect_blocks(&nodes[1], 1);
4442 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 }]);
4443 check_added_monitors!(nodes[1], 1);
4444 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4445 assert_eq!(fail_commit.len(), 1);
4446 match fail_commit[0] {
4447 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4448 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4449 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4451 _ => unreachable!(),
4453 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4455 expect_payment_failed!(nodes[1], second_payment_hash, false);
4460 fn test_holding_cell_htlc_add_timeouts() {
4461 do_test_holding_cell_htlc_add_timeouts(false);
4462 do_test_holding_cell_htlc_add_timeouts(true);
4465 macro_rules! check_spendable_outputs {
4466 ($node: expr, $keysinterface: expr) => {
4468 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4469 let mut txn = Vec::new();
4470 let mut all_outputs = Vec::new();
4471 let secp_ctx = Secp256k1::new();
4472 for event in events.drain(..) {
4474 Event::SpendableOutputs { mut outputs, channel_id: _ } => {
4475 for outp in outputs.drain(..) {
4476 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());
4477 all_outputs.push(outp);
4480 _ => panic!("Unexpected event"),
4483 if all_outputs.len() > 1 {
4484 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) {
4494 fn test_claim_sizeable_push_msat() {
4495 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4496 let chanmon_cfgs = create_chanmon_cfgs(2);
4497 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4498 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4499 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4501 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4502 nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4503 check_closed_broadcast!(nodes[1], true);
4504 check_added_monitors!(nodes[1], 1);
4505 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[0].node.get_our_node_id()], 100000);
4506 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4507 assert_eq!(node_txn.len(), 1);
4508 check_spends!(node_txn[0], chan.3);
4509 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
4511 mine_transaction(&nodes[1], &node_txn[0]);
4512 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4514 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4515 assert_eq!(spend_txn.len(), 1);
4516 assert_eq!(spend_txn[0].input.len(), 1);
4517 check_spends!(spend_txn[0], node_txn[0]);
4518 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4522 fn test_claim_on_remote_sizeable_push_msat() {
4523 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4524 // to_remote output is encumbered by a P2WPKH
4525 let chanmon_cfgs = create_chanmon_cfgs(2);
4526 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4527 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4528 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4530 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4531 nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4532 check_closed_broadcast!(nodes[0], true);
4533 check_added_monitors!(nodes[0], 1);
4534 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
4536 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4537 assert_eq!(node_txn.len(), 1);
4538 check_spends!(node_txn[0], chan.3);
4539 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
4541 mine_transaction(&nodes[1], &node_txn[0]);
4542 check_closed_broadcast!(nodes[1], true);
4543 check_added_monitors!(nodes[1], 1);
4544 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4545 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4547 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4548 assert_eq!(spend_txn.len(), 1);
4549 check_spends!(spend_txn[0], node_txn[0]);
4553 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4554 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4555 // to_remote output is encumbered by a P2WPKH
4557 let chanmon_cfgs = create_chanmon_cfgs(2);
4558 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4559 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4560 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4562 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4563 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4564 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4565 assert_eq!(revoked_local_txn[0].input.len(), 1);
4566 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4568 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4569 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4570 check_closed_broadcast!(nodes[1], true);
4571 check_added_monitors!(nodes[1], 1);
4572 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4574 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4575 mine_transaction(&nodes[1], &node_txn[0]);
4576 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4578 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4579 assert_eq!(spend_txn.len(), 3);
4580 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4581 check_spends!(spend_txn[1], node_txn[0]);
4582 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4586 fn test_static_spendable_outputs_preimage_tx() {
4587 let chanmon_cfgs = create_chanmon_cfgs(2);
4588 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4589 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4590 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4592 // Create some initial channels
4593 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4595 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4597 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4598 assert_eq!(commitment_tx[0].input.len(), 1);
4599 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4601 // Settle A's commitment tx on B's chain
4602 nodes[1].node.claim_funds(payment_preimage);
4603 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4604 check_added_monitors!(nodes[1], 1);
4605 mine_transaction(&nodes[1], &commitment_tx[0]);
4606 check_added_monitors!(nodes[1], 1);
4607 let events = nodes[1].node.get_and_clear_pending_msg_events();
4609 MessageSendEvent::UpdateHTLCs { .. } => {},
4610 _ => panic!("Unexpected event"),
4613 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4614 _ => panic!("Unexepected event"),
4617 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4618 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4619 assert_eq!(node_txn.len(), 1);
4620 check_spends!(node_txn[0], commitment_tx[0]);
4621 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4623 mine_transaction(&nodes[1], &node_txn[0]);
4624 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4625 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4627 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4628 assert_eq!(spend_txn.len(), 1);
4629 check_spends!(spend_txn[0], node_txn[0]);
4633 fn test_static_spendable_outputs_timeout_tx() {
4634 let chanmon_cfgs = create_chanmon_cfgs(2);
4635 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4636 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4637 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4639 // Create some initial channels
4640 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4642 // Rebalance the network a bit by relaying one payment through all the channels ...
4643 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4645 let (_, our_payment_hash, ..) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4647 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4648 assert_eq!(commitment_tx[0].input.len(), 1);
4649 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4651 // Settle A's commitment tx on B' chain
4652 mine_transaction(&nodes[1], &commitment_tx[0]);
4653 check_added_monitors!(nodes[1], 1);
4654 let events = nodes[1].node.get_and_clear_pending_msg_events();
4656 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4657 _ => panic!("Unexpected event"),
4659 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4661 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4662 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4663 assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4664 check_spends!(node_txn[0], commitment_tx[0].clone());
4665 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4667 mine_transaction(&nodes[1], &node_txn[0]);
4668 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4669 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4670 expect_payment_failed!(nodes[1], our_payment_hash, false);
4672 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4673 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4674 check_spends!(spend_txn[0], commitment_tx[0]);
4675 check_spends!(spend_txn[1], node_txn[0]);
4676 check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4680 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4681 let chanmon_cfgs = create_chanmon_cfgs(2);
4682 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4683 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4684 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4686 // Create some initial channels
4687 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4689 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4690 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4691 assert_eq!(revoked_local_txn[0].input.len(), 1);
4692 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4694 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4696 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4697 check_closed_broadcast!(nodes[1], true);
4698 check_added_monitors!(nodes[1], 1);
4699 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4701 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4702 assert_eq!(node_txn.len(), 1);
4703 assert_eq!(node_txn[0].input.len(), 2);
4704 check_spends!(node_txn[0], revoked_local_txn[0]);
4706 mine_transaction(&nodes[1], &node_txn[0]);
4707 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4709 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4710 assert_eq!(spend_txn.len(), 1);
4711 check_spends!(spend_txn[0], node_txn[0]);
4715 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4716 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4717 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4718 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4719 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4720 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4722 // Create some initial channels
4723 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4725 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4726 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4727 assert_eq!(revoked_local_txn[0].input.len(), 1);
4728 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4730 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4732 // A will generate HTLC-Timeout from revoked commitment tx
4733 mine_transaction(&nodes[0], &revoked_local_txn[0]);
4734 check_closed_broadcast!(nodes[0], true);
4735 check_added_monitors!(nodes[0], 1);
4736 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4737 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4739 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4740 assert_eq!(revoked_htlc_txn.len(), 1);
4741 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4742 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4743 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4744 assert_ne!(revoked_htlc_txn[0].lock_time, LockTime::ZERO); // HTLC-Timeout
4746 // B will generate justice tx from A's revoked commitment/HTLC tx
4747 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4748 check_closed_broadcast!(nodes[1], true);
4749 check_added_monitors!(nodes[1], 1);
4750 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4752 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4753 assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4754 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4755 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4756 // transactions next...
4757 assert_eq!(node_txn[0].input.len(), 3);
4758 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4760 assert_eq!(node_txn[1].input.len(), 2);
4761 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4762 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4763 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4765 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4766 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4769 mine_transaction(&nodes[1], &node_txn[1]);
4770 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4772 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4773 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4774 assert_eq!(spend_txn.len(), 1);
4775 assert_eq!(spend_txn[0].input.len(), 1);
4776 check_spends!(spend_txn[0], node_txn[1]);
4780 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4781 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4782 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4783 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4784 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4785 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4787 // Create some initial channels
4788 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4790 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4791 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4792 assert_eq!(revoked_local_txn[0].input.len(), 1);
4793 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4795 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4796 assert_eq!(revoked_local_txn[0].output.len(), 2);
4798 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4800 // B will generate HTLC-Success from revoked commitment tx
4801 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4802 check_closed_broadcast!(nodes[1], true);
4803 check_added_monitors!(nodes[1], 1);
4804 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4805 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4807 assert_eq!(revoked_htlc_txn.len(), 1);
4808 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4809 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4810 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4812 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4813 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4814 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4816 // A will generate justice tx from B's revoked commitment/HTLC tx
4817 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4818 check_closed_broadcast!(nodes[0], true);
4819 check_added_monitors!(nodes[0], 1);
4820 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4822 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4823 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4825 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4826 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4827 // transactions next...
4828 assert_eq!(node_txn[0].input.len(), 2);
4829 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4830 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4831 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4833 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4834 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4837 assert_eq!(node_txn[1].input.len(), 1);
4838 check_spends!(node_txn[1], revoked_htlc_txn[0]);
4840 mine_transaction(&nodes[0], &node_txn[1]);
4841 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4843 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4844 // didn't try to generate any new transactions.
4846 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4847 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4848 assert_eq!(spend_txn.len(), 3);
4849 assert_eq!(spend_txn[0].input.len(), 1);
4850 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4851 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4852 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4853 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4857 fn test_onchain_to_onchain_claim() {
4858 // Test that in case of channel closure, we detect the state of output and claim HTLC
4859 // on downstream peer's remote commitment tx.
4860 // First, have C claim an HTLC against its own latest commitment transaction.
4861 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4863 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4866 let chanmon_cfgs = create_chanmon_cfgs(3);
4867 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4868 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4869 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4871 // Create some initial channels
4872 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4873 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4875 // Ensure all nodes are at the same height
4876 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4877 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4878 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4879 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4881 // Rebalance the network a bit by relaying one payment through all the channels ...
4882 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4883 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4885 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4886 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4887 check_spends!(commitment_tx[0], chan_2.3);
4888 nodes[2].node.claim_funds(payment_preimage);
4889 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4890 check_added_monitors!(nodes[2], 1);
4891 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4892 assert!(updates.update_add_htlcs.is_empty());
4893 assert!(updates.update_fail_htlcs.is_empty());
4894 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4895 assert!(updates.update_fail_malformed_htlcs.is_empty());
4897 mine_transaction(&nodes[2], &commitment_tx[0]);
4898 check_closed_broadcast!(nodes[2], true);
4899 check_added_monitors!(nodes[2], 1);
4900 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4902 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4903 assert_eq!(c_txn.len(), 1);
4904 check_spends!(c_txn[0], commitment_tx[0]);
4905 assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4906 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4907 assert_eq!(c_txn[0].lock_time, LockTime::ZERO); // Success tx
4909 // 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
4910 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![commitment_tx[0].clone(), c_txn[0].clone()]));
4911 check_added_monitors!(nodes[1], 1);
4912 let events = nodes[1].node.get_and_clear_pending_events();
4913 assert_eq!(events.len(), 2);
4915 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4916 _ => panic!("Unexpected event"),
4919 Event::PaymentForwarded { total_fee_earned_msat, prev_channel_id, claim_from_onchain_tx,
4920 next_channel_id, outbound_amount_forwarded_msat, ..
4922 assert_eq!(total_fee_earned_msat, Some(1000));
4923 assert_eq!(prev_channel_id, Some(chan_1.2));
4924 assert_eq!(claim_from_onchain_tx, true);
4925 assert_eq!(next_channel_id, Some(chan_2.2));
4926 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
4928 _ => panic!("Unexpected event"),
4930 check_added_monitors!(nodes[1], 1);
4931 let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4932 assert_eq!(msg_events.len(), 3);
4933 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut msg_events);
4934 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut msg_events);
4936 match nodes_2_event {
4937 MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { .. }, node_id: _ } => {},
4938 _ => panic!("Unexpected event"),
4941 match nodes_0_event {
4942 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, .. } } => {
4943 assert!(update_add_htlcs.is_empty());
4944 assert!(update_fail_htlcs.is_empty());
4945 assert_eq!(update_fulfill_htlcs.len(), 1);
4946 assert!(update_fail_malformed_htlcs.is_empty());
4947 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4949 _ => panic!("Unexpected event"),
4952 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
4953 match msg_events[0] {
4954 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4955 _ => panic!("Unexpected event"),
4958 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4959 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4960 mine_transaction(&nodes[1], &commitment_tx[0]);
4961 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4962 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4963 // ChannelMonitor: HTLC-Success tx
4964 assert_eq!(b_txn.len(), 1);
4965 check_spends!(b_txn[0], commitment_tx[0]);
4966 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4967 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4968 assert_eq!(b_txn[0].lock_time.to_consensus_u32(), nodes[1].best_block_info().1); // Success tx
4970 check_closed_broadcast!(nodes[1], true);
4971 check_added_monitors!(nodes[1], 1);
4975 fn test_duplicate_payment_hash_one_failure_one_success() {
4976 // Topology : A --> B --> C --> D
4977 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4978 // Note that because C will refuse to generate two payment secrets for the same payment hash,
4979 // we forward one of the payments onwards to D.
4980 let chanmon_cfgs = create_chanmon_cfgs(4);
4981 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4982 // When this test was written, the default base fee floated based on the HTLC count.
4983 // It is now fixed, so we simply set the fee to the expected value here.
4984 let mut config = test_default_channel_config();
4985 config.channel_config.forwarding_fee_base_msat = 196;
4986 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4987 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4988 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4990 create_announced_chan_between_nodes(&nodes, 0, 1);
4991 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4992 create_announced_chan_between_nodes(&nodes, 2, 3);
4994 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4995 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4996 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4997 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4998 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5000 let (our_payment_preimage, duplicate_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
5002 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
5003 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5004 // script push size limit so that the below script length checks match
5005 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5006 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV - 40)
5007 .with_bolt11_features(nodes[3].node.bolt11_invoice_features()).unwrap();
5008 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000);
5009 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
5011 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5012 assert_eq!(commitment_txn[0].input.len(), 1);
5013 check_spends!(commitment_txn[0], chan_2.3);
5015 mine_transaction(&nodes[1], &commitment_txn[0]);
5016 check_closed_broadcast!(nodes[1], true);
5017 check_added_monitors!(nodes[1], 1);
5018 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
5019 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
5021 let htlc_timeout_tx;
5022 { // Extract one of the two HTLC-Timeout transaction
5023 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5024 // ChannelMonitor: timeout tx * 2-or-3
5025 assert!(node_txn.len() == 2 || node_txn.len() == 3);
5027 check_spends!(node_txn[0], commitment_txn[0]);
5028 assert_eq!(node_txn[0].input.len(), 1);
5029 assert_eq!(node_txn[0].output.len(), 1);
5031 if node_txn.len() > 2 {
5032 check_spends!(node_txn[1], commitment_txn[0]);
5033 assert_eq!(node_txn[1].input.len(), 1);
5034 assert_eq!(node_txn[1].output.len(), 1);
5035 assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
5037 check_spends!(node_txn[2], commitment_txn[0]);
5038 assert_eq!(node_txn[2].input.len(), 1);
5039 assert_eq!(node_txn[2].output.len(), 1);
5040 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
5042 check_spends!(node_txn[1], commitment_txn[0]);
5043 assert_eq!(node_txn[1].input.len(), 1);
5044 assert_eq!(node_txn[1].output.len(), 1);
5045 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
5048 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5049 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5050 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
5051 // (with value 900 sats) will be claimed in the below `claim_funds` call.
5052 if node_txn.len() > 2 {
5053 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5054 htlc_timeout_tx = if node_txn[2].output[0].value < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
5056 htlc_timeout_tx = if node_txn[0].output[0].value < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
5060 nodes[2].node.claim_funds(our_payment_preimage);
5061 expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
5063 mine_transaction(&nodes[2], &commitment_txn[0]);
5064 check_added_monitors!(nodes[2], 2);
5065 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5066 let events = nodes[2].node.get_and_clear_pending_msg_events();
5068 MessageSendEvent::UpdateHTLCs { .. } => {},
5069 _ => panic!("Unexpected event"),
5072 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5073 _ => panic!("Unexepected event"),
5075 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5076 assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
5077 check_spends!(htlc_success_txn[0], commitment_txn[0]);
5078 check_spends!(htlc_success_txn[1], commitment_txn[0]);
5079 assert_eq!(htlc_success_txn[0].input.len(), 1);
5080 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5081 assert_eq!(htlc_success_txn[1].input.len(), 1);
5082 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5083 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5084 assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5086 mine_transaction(&nodes[1], &htlc_timeout_tx);
5087 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5088 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 }]);
5089 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5090 assert!(htlc_updates.update_add_htlcs.is_empty());
5091 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5092 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5093 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5094 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5095 check_added_monitors!(nodes[1], 1);
5097 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5098 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5100 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5102 expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5104 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5105 mine_transaction(&nodes[1], &htlc_success_txn[1]);
5106 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
5107 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5108 assert!(updates.update_add_htlcs.is_empty());
5109 assert!(updates.update_fail_htlcs.is_empty());
5110 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5111 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5112 assert!(updates.update_fail_malformed_htlcs.is_empty());
5113 check_added_monitors!(nodes[1], 1);
5115 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5116 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5117 expect_payment_sent(&nodes[0], our_payment_preimage, None, true, true);
5121 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5122 let chanmon_cfgs = create_chanmon_cfgs(2);
5123 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5124 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5125 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5127 // Create some initial channels
5128 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5130 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
5131 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5132 assert_eq!(local_txn.len(), 1);
5133 assert_eq!(local_txn[0].input.len(), 1);
5134 check_spends!(local_txn[0], chan_1.3);
5136 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5137 nodes[1].node.claim_funds(payment_preimage);
5138 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
5139 check_added_monitors!(nodes[1], 1);
5141 mine_transaction(&nodes[1], &local_txn[0]);
5142 check_added_monitors!(nodes[1], 1);
5143 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
5144 let events = nodes[1].node.get_and_clear_pending_msg_events();
5146 MessageSendEvent::UpdateHTLCs { .. } => {},
5147 _ => panic!("Unexpected event"),
5150 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5151 _ => panic!("Unexepected event"),
5154 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5155 assert_eq!(node_txn.len(), 1);
5156 assert_eq!(node_txn[0].input.len(), 1);
5157 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5158 check_spends!(node_txn[0], local_txn[0]);
5162 mine_transaction(&nodes[1], &node_tx);
5163 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5165 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5166 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5167 assert_eq!(spend_txn.len(), 1);
5168 assert_eq!(spend_txn[0].input.len(), 1);
5169 check_spends!(spend_txn[0], node_tx);
5170 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5173 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5174 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5175 // unrevoked commitment transaction.
5176 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5177 // a remote RAA before they could be failed backwards (and combinations thereof).
5178 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5179 // use the same payment hashes.
5180 // Thus, we use a six-node network:
5185 // And test where C fails back to A/B when D announces its latest commitment transaction
5186 let chanmon_cfgs = create_chanmon_cfgs(6);
5187 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5188 // When this test was written, the default base fee floated based on the HTLC count.
5189 // It is now fixed, so we simply set the fee to the expected value here.
5190 let mut config = test_default_channel_config();
5191 config.channel_config.forwarding_fee_base_msat = 196;
5192 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5193 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5194 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5196 let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2);
5197 let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5198 let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5199 let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
5200 let chan_3_5 = create_announced_chan_between_nodes(&nodes, 3, 5);
5202 // Rebalance and check output sanity...
5203 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5204 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5205 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
5207 let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
5208 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().context().holder_dust_limit_satoshis;
5210 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
5212 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
5213 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5215 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
5217 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
5219 let (_, payment_hash_3, ..) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5221 let (_, payment_hash_4, ..) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5222 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5224 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());
5226 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());
5229 let (_, payment_hash_5, ..) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5231 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5232 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
5235 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
5237 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5238 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());
5240 // Double-check that six of the new HTLC were added
5241 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5242 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5243 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5244 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5246 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5247 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5248 nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5249 nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5250 nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5251 nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5252 check_added_monitors!(nodes[4], 0);
5254 let failed_destinations = vec![
5255 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5256 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5257 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5258 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5260 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5261 check_added_monitors!(nodes[4], 1);
5263 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5264 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5265 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5266 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5267 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5268 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5270 // Fail 3rd below-dust and 7th above-dust HTLCs
5271 nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5272 nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5273 check_added_monitors!(nodes[5], 0);
5275 let failed_destinations_2 = vec![
5276 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5277 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5279 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5280 check_added_monitors!(nodes[5], 1);
5282 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5283 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5284 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5285 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5287 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5289 // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5290 let failed_destinations_3 = vec![
5291 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
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[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5296 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5298 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5299 check_added_monitors!(nodes[3], 1);
5300 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5301 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5302 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5303 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5304 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5305 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5306 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5307 if deliver_last_raa {
5308 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5310 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5313 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5314 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5315 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5316 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5318 // We now broadcast the latest commitment transaction, which *should* result in failures for
5319 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5320 // the non-broadcast above-dust HTLCs.
5322 // Alternatively, we may broadcast the previous commitment transaction, which should only
5323 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5324 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5326 if announce_latest {
5327 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5329 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5331 let events = nodes[2].node.get_and_clear_pending_events();
5332 let close_event = if deliver_last_raa {
5333 assert_eq!(events.len(), 2 + 6);
5334 events.last().clone().unwrap()
5336 assert_eq!(events.len(), 1);
5337 events.last().clone().unwrap()
5340 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5341 _ => panic!("Unexpected event"),
5344 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5345 check_closed_broadcast!(nodes[2], true);
5346 if deliver_last_raa {
5347 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5349 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();
5350 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5352 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5353 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5355 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5358 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5360 check_added_monitors!(nodes[2], 3);
5362 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5363 assert_eq!(cs_msgs.len(), 2);
5364 let mut a_done = false;
5365 for msg in cs_msgs {
5367 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5368 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5369 // should be failed-backwards here.
5370 let target = if *node_id == nodes[0].node.get_our_node_id() {
5371 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5372 for htlc in &updates.update_fail_htlcs {
5373 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 });
5375 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5380 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5381 for htlc in &updates.update_fail_htlcs {
5382 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5384 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5385 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5388 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5389 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5390 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5391 if announce_latest {
5392 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5393 if *node_id == nodes[0].node.get_our_node_id() {
5394 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5397 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5399 _ => panic!("Unexpected event"),
5403 let as_events = nodes[0].node.get_and_clear_pending_events();
5404 assert_eq!(as_events.len(), if announce_latest { 10 } else { 6 });
5405 let mut as_failds = HashSet::new();
5406 let mut as_updates = 0;
5407 for event in as_events.iter() {
5408 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5409 assert!(as_failds.insert(*payment_hash));
5410 if *payment_hash != payment_hash_2 {
5411 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5413 assert!(!payment_failed_permanently);
5415 if let PathFailure::OnPath { network_update: Some(_) } = failure {
5418 } else if let &Event::PaymentFailed { .. } = event {
5419 } else { panic!("Unexpected event"); }
5421 assert!(as_failds.contains(&payment_hash_1));
5422 assert!(as_failds.contains(&payment_hash_2));
5423 if announce_latest {
5424 assert!(as_failds.contains(&payment_hash_3));
5425 assert!(as_failds.contains(&payment_hash_5));
5427 assert!(as_failds.contains(&payment_hash_6));
5429 let bs_events = nodes[1].node.get_and_clear_pending_events();
5430 assert_eq!(bs_events.len(), if announce_latest { 8 } else { 6 });
5431 let mut bs_failds = HashSet::new();
5432 let mut bs_updates = 0;
5433 for event in bs_events.iter() {
5434 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5435 assert!(bs_failds.insert(*payment_hash));
5436 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5437 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5439 assert!(!payment_failed_permanently);
5441 if let PathFailure::OnPath { network_update: Some(_) } = failure {
5444 } else if let &Event::PaymentFailed { .. } = event {
5445 } else { panic!("Unexpected event"); }
5447 assert!(bs_failds.contains(&payment_hash_1));
5448 assert!(bs_failds.contains(&payment_hash_2));
5449 if announce_latest {
5450 assert!(bs_failds.contains(&payment_hash_4));
5452 assert!(bs_failds.contains(&payment_hash_5));
5454 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5455 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5456 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5457 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5458 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5459 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5463 fn test_fail_backwards_latest_remote_announce_a() {
5464 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5468 fn test_fail_backwards_latest_remote_announce_b() {
5469 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5473 fn test_fail_backwards_previous_remote_announce() {
5474 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5475 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5476 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5480 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5481 let chanmon_cfgs = create_chanmon_cfgs(2);
5482 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5483 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5484 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5486 // Create some initial channels
5487 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5489 let (_, our_payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5490 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5491 assert_eq!(local_txn[0].input.len(), 1);
5492 check_spends!(local_txn[0], chan_1.3);
5494 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5495 mine_transaction(&nodes[0], &local_txn[0]);
5496 check_closed_broadcast!(nodes[0], true);
5497 check_added_monitors!(nodes[0], 1);
5498 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5499 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5501 let htlc_timeout = {
5502 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5503 assert_eq!(node_txn.len(), 1);
5504 assert_eq!(node_txn[0].input.len(), 1);
5505 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5506 check_spends!(node_txn[0], local_txn[0]);
5510 mine_transaction(&nodes[0], &htlc_timeout);
5511 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5512 expect_payment_failed!(nodes[0], our_payment_hash, false);
5514 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5515 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5516 assert_eq!(spend_txn.len(), 3);
5517 check_spends!(spend_txn[0], local_txn[0]);
5518 assert_eq!(spend_txn[1].input.len(), 1);
5519 check_spends!(spend_txn[1], htlc_timeout);
5520 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5521 assert_eq!(spend_txn[2].input.len(), 2);
5522 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5523 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5524 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5528 fn test_key_derivation_params() {
5529 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5530 // manager rotation to test that `channel_keys_id` returned in
5531 // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5532 // then derive a `delayed_payment_key`.
5534 let chanmon_cfgs = create_chanmon_cfgs(3);
5536 // We manually create the node configuration to backup the seed.
5537 let seed = [42; 32];
5538 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5539 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);
5540 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[0].logger));
5541 let scorer = RwLock::new(test_utils::TestScorer::new());
5542 let router = test_utils::TestRouter::new(network_graph.clone(), &chanmon_cfgs[0].logger, &scorer);
5543 let message_router = test_utils::TestMessageRouter::new(network_graph.clone());
5544 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)) };
5545 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5546 node_cfgs.remove(0);
5547 node_cfgs.insert(0, node);
5549 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5550 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5552 // Create some initial channels
5553 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5555 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2);
5556 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5557 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5559 // Ensure all nodes are at the same height
5560 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5561 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5562 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5563 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5565 let (_, our_payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5566 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5567 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5568 assert_eq!(local_txn_1[0].input.len(), 1);
5569 check_spends!(local_txn_1[0], chan_1.3);
5571 // We check funding pubkey are unique
5572 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]));
5573 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]));
5574 if from_0_funding_key_0 == from_1_funding_key_0
5575 || from_0_funding_key_0 == from_1_funding_key_1
5576 || from_0_funding_key_1 == from_1_funding_key_0
5577 || from_0_funding_key_1 == from_1_funding_key_1 {
5578 panic!("Funding pubkeys aren't unique");
5581 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5582 mine_transaction(&nodes[0], &local_txn_1[0]);
5583 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5584 check_closed_broadcast!(nodes[0], true);
5585 check_added_monitors!(nodes[0], 1);
5586 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5588 let htlc_timeout = {
5589 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5590 assert_eq!(node_txn.len(), 1);
5591 assert_eq!(node_txn[0].input.len(), 1);
5592 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5593 check_spends!(node_txn[0], local_txn_1[0]);
5597 mine_transaction(&nodes[0], &htlc_timeout);
5598 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5599 expect_payment_failed!(nodes[0], our_payment_hash, false);
5601 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5602 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5603 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5604 assert_eq!(spend_txn.len(), 3);
5605 check_spends!(spend_txn[0], local_txn_1[0]);
5606 assert_eq!(spend_txn[1].input.len(), 1);
5607 check_spends!(spend_txn[1], htlc_timeout);
5608 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5609 assert_eq!(spend_txn[2].input.len(), 2);
5610 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5611 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5612 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5616 fn test_static_output_closing_tx() {
5617 let chanmon_cfgs = create_chanmon_cfgs(2);
5618 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5619 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5620 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5622 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5624 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5625 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5627 mine_transaction(&nodes[0], &closing_tx);
5628 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
5629 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5631 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5632 assert_eq!(spend_txn.len(), 1);
5633 check_spends!(spend_txn[0], closing_tx);
5635 mine_transaction(&nodes[1], &closing_tx);
5636 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
5637 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5639 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5640 assert_eq!(spend_txn.len(), 1);
5641 check_spends!(spend_txn[0], closing_tx);
5644 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5645 let chanmon_cfgs = create_chanmon_cfgs(2);
5646 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5647 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5648 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5649 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5651 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5653 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5654 // present in B's local commitment transaction, but none of A's commitment transactions.
5655 nodes[1].node.claim_funds(payment_preimage);
5656 check_added_monitors!(nodes[1], 1);
5657 expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5659 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5660 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5661 expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
5663 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5664 check_added_monitors!(nodes[0], 1);
5665 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5666 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5667 check_added_monitors!(nodes[1], 1);
5669 let starting_block = nodes[1].best_block_info();
5670 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5671 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5672 connect_block(&nodes[1], &block);
5673 block.header.prev_blockhash = block.block_hash();
5675 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5676 check_closed_broadcast!(nodes[1], true);
5677 check_added_monitors!(nodes[1], 1);
5678 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[0].node.get_our_node_id()], 100000);
5681 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5682 let chanmon_cfgs = create_chanmon_cfgs(2);
5683 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5684 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5685 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5686 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5688 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5689 nodes[0].node.send_payment_with_route(&route, payment_hash,
5690 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
5691 check_added_monitors!(nodes[0], 1);
5693 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5695 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5696 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5697 // to "time out" the HTLC.
5699 let starting_block = nodes[1].best_block_info();
5700 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5702 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5703 connect_block(&nodes[0], &block);
5704 block.header.prev_blockhash = block.block_hash();
5706 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5707 check_closed_broadcast!(nodes[0], true);
5708 check_added_monitors!(nodes[0], 1);
5709 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
5712 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5713 let chanmon_cfgs = create_chanmon_cfgs(3);
5714 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5715 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5716 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5717 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5719 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5720 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5721 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5722 // actually revoked.
5723 let htlc_value = if use_dust { 50000 } else { 3000000 };
5724 let (_, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5725 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5726 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5727 check_added_monitors!(nodes[1], 1);
5729 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5730 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5731 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5732 check_added_monitors!(nodes[0], 1);
5733 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5734 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5735 check_added_monitors!(nodes[1], 1);
5736 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5737 check_added_monitors!(nodes[1], 1);
5738 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5740 if check_revoke_no_close {
5741 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5742 check_added_monitors!(nodes[0], 1);
5745 let starting_block = nodes[1].best_block_info();
5746 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5747 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5748 connect_block(&nodes[0], &block);
5749 block.header.prev_blockhash = block.block_hash();
5751 if !check_revoke_no_close {
5752 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5753 check_closed_broadcast!(nodes[0], true);
5754 check_added_monitors!(nodes[0], 1);
5755 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
5757 expect_payment_failed!(nodes[0], our_payment_hash, true);
5761 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5762 // There are only a few cases to test here:
5763 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5764 // broadcastable commitment transactions result in channel closure,
5765 // * its included in an unrevoked-but-previous remote commitment transaction,
5766 // * its included in the latest remote or local commitment transactions.
5767 // We test each of the three possible commitment transactions individually and use both dust and
5769 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5770 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5771 // tested for at least one of the cases in other tests.
5773 fn htlc_claim_single_commitment_only_a() {
5774 do_htlc_claim_local_commitment_only(true);
5775 do_htlc_claim_local_commitment_only(false);
5777 do_htlc_claim_current_remote_commitment_only(true);
5778 do_htlc_claim_current_remote_commitment_only(false);
5782 fn htlc_claim_single_commitment_only_b() {
5783 do_htlc_claim_previous_remote_commitment_only(true, false);
5784 do_htlc_claim_previous_remote_commitment_only(false, false);
5785 do_htlc_claim_previous_remote_commitment_only(true, true);
5786 do_htlc_claim_previous_remote_commitment_only(false, true);
5791 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5792 let chanmon_cfgs = create_chanmon_cfgs(2);
5793 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5794 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5795 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5796 // Force duplicate randomness for every get-random call
5797 for node in nodes.iter() {
5798 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5801 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5802 let channel_value_satoshis=10000;
5803 let push_msat=10001;
5804 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).unwrap();
5805 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5806 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5807 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5809 // Create a second channel with the same random values. This used to panic due to a colliding
5810 // channel_id, but now panics due to a colliding outbound SCID alias.
5811 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).is_err());
5815 fn bolt2_open_channel_sending_node_checks_part2() {
5816 let chanmon_cfgs = create_chanmon_cfgs(2);
5817 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5818 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5819 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5821 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5822 let channel_value_satoshis=2^24;
5823 let push_msat=10001;
5824 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).is_err());
5826 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5827 let channel_value_satoshis=10000;
5828 // Test when push_msat is equal to 1000 * funding_satoshis.
5829 let push_msat=1000*channel_value_satoshis+1;
5830 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).is_err());
5832 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5833 let channel_value_satoshis=10000;
5834 let push_msat=10001;
5835 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
5836 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5837 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5839 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5840 // 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
5841 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5843 // 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.
5844 assert!(BREAKDOWN_TIMEOUT>0);
5845 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5847 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5848 let chain_hash = ChainHash::using_genesis_block(Network::Testnet);
5849 assert_eq!(node0_to_1_send_open_channel.chain_hash, chain_hash);
5851 // 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.
5852 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5853 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5854 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5855 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5856 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5860 fn bolt2_open_channel_sane_dust_limit() {
5861 let chanmon_cfgs = create_chanmon_cfgs(2);
5862 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5863 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5864 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5866 let channel_value_satoshis=1000000;
5867 let push_msat=10001;
5868 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).unwrap();
5869 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5870 node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5871 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5873 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5874 let events = nodes[1].node.get_and_clear_pending_msg_events();
5875 let err_msg = match events[0] {
5876 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5879 _ => panic!("Unexpected event"),
5881 assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5884 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5885 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5886 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5887 // is no longer affordable once it's freed.
5889 fn test_fail_holding_cell_htlc_upon_free() {
5890 let chanmon_cfgs = create_chanmon_cfgs(2);
5891 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5892 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5893 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5894 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5896 // First nodes[0] generates an update_fee, setting the channel's
5897 // pending_update_fee.
5899 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5900 *feerate_lock += 20;
5902 nodes[0].node.timer_tick_occurred();
5903 check_added_monitors!(nodes[0], 1);
5905 let events = nodes[0].node.get_and_clear_pending_msg_events();
5906 assert_eq!(events.len(), 1);
5907 let (update_msg, commitment_signed) = match events[0] {
5908 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5909 (update_fee.as_ref(), commitment_signed)
5911 _ => panic!("Unexpected event"),
5914 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5916 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5917 let channel_reserve = chan_stat.channel_reserve_msat;
5918 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5919 let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
5921 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5922 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
5923 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5925 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5926 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5927 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5928 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5929 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5931 // Flush the pending fee update.
5932 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5933 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5934 check_added_monitors!(nodes[1], 1);
5935 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5936 check_added_monitors!(nodes[0], 1);
5938 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5939 // HTLC, but now that the fee has been raised the payment will now fail, causing
5940 // us to surface its failure to the user.
5941 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5942 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5943 nodes[0].logger.assert_log("lightning::ln::channel", format!("Freeing holding cell with 1 HTLC updates in channel {}", chan.2), 1);
5945 // Check that the payment failed to be sent out.
5946 let events = nodes[0].node.get_and_clear_pending_events();
5947 assert_eq!(events.len(), 2);
5949 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5950 assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5951 assert_eq!(our_payment_hash.clone(), *payment_hash);
5952 assert_eq!(*payment_failed_permanently, false);
5953 assert_eq!(*short_channel_id, Some(route.paths[0].hops[0].short_channel_id));
5955 _ => panic!("Unexpected event"),
5958 &Event::PaymentFailed { ref payment_hash, .. } => {
5959 assert_eq!(our_payment_hash.clone(), *payment_hash);
5961 _ => panic!("Unexpected event"),
5965 // Test that if multiple HTLCs are released from the holding cell and one is
5966 // valid but the other is no longer valid upon release, the valid HTLC can be
5967 // successfully completed while the other one fails as expected.
5969 fn test_free_and_fail_holding_cell_htlcs() {
5970 let chanmon_cfgs = create_chanmon_cfgs(2);
5971 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5972 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5973 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5974 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5976 // First nodes[0] generates an update_fee, setting the channel's
5977 // pending_update_fee.
5979 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5980 *feerate_lock += 200;
5982 nodes[0].node.timer_tick_occurred();
5983 check_added_monitors!(nodes[0], 1);
5985 let events = nodes[0].node.get_and_clear_pending_msg_events();
5986 assert_eq!(events.len(), 1);
5987 let (update_msg, commitment_signed) = match events[0] {
5988 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5989 (update_fee.as_ref(), commitment_signed)
5991 _ => panic!("Unexpected event"),
5994 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5996 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5997 let channel_reserve = chan_stat.channel_reserve_msat;
5998 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5999 let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
6001 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6003 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features) - amt_1;
6004 let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
6005 let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
6007 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6008 nodes[0].node.send_payment_with_route(&route_1, payment_hash_1,
6009 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
6010 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6011 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6012 let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
6013 nodes[0].node.send_payment_with_route(&route_2, payment_hash_2,
6014 RecipientOnionFields::secret_only(payment_secret_2), payment_id_2).unwrap();
6015 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6016 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6018 // Flush the pending fee update.
6019 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6020 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6021 check_added_monitors!(nodes[1], 1);
6022 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6023 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6024 check_added_monitors!(nodes[0], 2);
6026 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6027 // but now that the fee has been raised the second payment will now fail, causing us
6028 // to surface its failure to the user. The first payment should succeed.
6029 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6030 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6031 nodes[0].logger.assert_log("lightning::ln::channel", format!("Freeing holding cell with 2 HTLC updates in channel {}", chan.2), 1);
6033 // Check that the second payment failed to be sent out.
6034 let events = nodes[0].node.get_and_clear_pending_events();
6035 assert_eq!(events.len(), 2);
6037 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
6038 assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6039 assert_eq!(payment_hash_2.clone(), *payment_hash);
6040 assert_eq!(*payment_failed_permanently, false);
6041 assert_eq!(*short_channel_id, Some(route_2.paths[0].hops[0].short_channel_id));
6043 _ => panic!("Unexpected event"),
6046 &Event::PaymentFailed { ref payment_hash, .. } => {
6047 assert_eq!(payment_hash_2.clone(), *payment_hash);
6049 _ => panic!("Unexpected event"),
6052 // Complete the first payment and the RAA from the fee update.
6053 let (payment_event, send_raa_event) = {
6054 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6055 assert_eq!(msgs.len(), 2);
6056 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6058 let raa = match send_raa_event {
6059 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6060 _ => panic!("Unexpected event"),
6062 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6063 check_added_monitors!(nodes[1], 1);
6064 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6065 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6066 let events = nodes[1].node.get_and_clear_pending_events();
6067 assert_eq!(events.len(), 1);
6069 Event::PendingHTLCsForwardable { .. } => {},
6070 _ => panic!("Unexpected event"),
6072 nodes[1].node.process_pending_htlc_forwards();
6073 let events = nodes[1].node.get_and_clear_pending_events();
6074 assert_eq!(events.len(), 1);
6076 Event::PaymentClaimable { .. } => {},
6077 _ => panic!("Unexpected event"),
6079 nodes[1].node.claim_funds(payment_preimage_1);
6080 check_added_monitors!(nodes[1], 1);
6081 expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
6083 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6084 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6085 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6086 expect_payment_sent!(nodes[0], payment_preimage_1);
6089 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6090 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6091 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6094 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6095 let chanmon_cfgs = create_chanmon_cfgs(3);
6096 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6097 // Avoid having to include routing fees in calculations
6098 let mut config = test_default_channel_config();
6099 config.channel_config.forwarding_fee_base_msat = 0;
6100 config.channel_config.forwarding_fee_proportional_millionths = 0;
6101 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6102 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6103 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6104 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
6106 // First nodes[1] generates an update_fee, setting the channel's
6107 // pending_update_fee.
6109 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6110 *feerate_lock += 20;
6112 nodes[1].node.timer_tick_occurred();
6113 check_added_monitors!(nodes[1], 1);
6115 let events = nodes[1].node.get_and_clear_pending_msg_events();
6116 assert_eq!(events.len(), 1);
6117 let (update_msg, commitment_signed) = match events[0] {
6118 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6119 (update_fee.as_ref(), commitment_signed)
6121 _ => panic!("Unexpected event"),
6124 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6126 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan_0_1.2);
6127 let channel_reserve = chan_stat.channel_reserve_msat;
6128 let feerate = get_feerate!(nodes[0], nodes[1], chan_0_1.2);
6129 let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_0_1.2);
6131 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6132 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
6133 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6134 let payment_event = {
6135 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6136 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6137 check_added_monitors!(nodes[0], 1);
6139 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6140 assert_eq!(events.len(), 1);
6142 SendEvent::from_event(events.remove(0))
6144 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6145 check_added_monitors!(nodes[1], 0);
6146 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6147 expect_pending_htlcs_forwardable!(nodes[1]);
6149 chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
6150 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6152 // Flush the pending fee update.
6153 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6154 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6155 check_added_monitors!(nodes[2], 1);
6156 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6157 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6158 check_added_monitors!(nodes[1], 2);
6160 // A final RAA message is generated to finalize the fee update.
6161 let events = nodes[1].node.get_and_clear_pending_msg_events();
6162 assert_eq!(events.len(), 1);
6164 let raa_msg = match &events[0] {
6165 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6168 _ => panic!("Unexpected event"),
6171 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6172 check_added_monitors!(nodes[2], 1);
6173 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6175 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6176 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6177 assert_eq!(process_htlc_forwards_event.len(), 2);
6178 match &process_htlc_forwards_event[0] {
6179 &Event::PendingHTLCsForwardable { .. } => {},
6180 _ => panic!("Unexpected event"),
6183 // In response, we call ChannelManager's process_pending_htlc_forwards
6184 nodes[1].node.process_pending_htlc_forwards();
6185 check_added_monitors!(nodes[1], 1);
6187 // This causes the HTLC to be failed backwards.
6188 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6189 assert_eq!(fail_event.len(), 1);
6190 let (fail_msg, commitment_signed) = match &fail_event[0] {
6191 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6192 assert_eq!(updates.update_add_htlcs.len(), 0);
6193 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6194 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6195 assert_eq!(updates.update_fail_htlcs.len(), 1);
6196 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6198 _ => panic!("Unexpected event"),
6201 // Pass the failure messages back to nodes[0].
6202 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6203 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6205 // Complete the HTLC failure+removal process.
6206 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6207 check_added_monitors!(nodes[0], 1);
6208 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6209 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6210 check_added_monitors!(nodes[1], 2);
6211 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6212 assert_eq!(final_raa_event.len(), 1);
6213 let raa = match &final_raa_event[0] {
6214 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6215 _ => panic!("Unexpected event"),
6217 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6218 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6219 check_added_monitors!(nodes[0], 1);
6223 fn test_payment_route_reaching_same_channel_twice() {
6224 //A route should not go through the same channel twice
6225 //It is enforced when constructing a route.
6226 let chanmon_cfgs = create_chanmon_cfgs(2);
6227 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6228 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6229 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6230 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6232 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6233 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
6234 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);
6236 // Extend the path by itself, essentially simulating route going through same channel twice
6237 let cloned_hops = route.paths[0].hops.clone();
6238 route.paths[0].hops.extend_from_slice(&cloned_hops);
6240 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6241 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6242 ), false, APIError::InvalidRoute { ref err },
6243 assert_eq!(err, &"Path went through the same channel twice"));
6246 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6247 // 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.
6248 //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.
6251 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6252 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6253 let chanmon_cfgs = create_chanmon_cfgs(2);
6254 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6255 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6256 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6257 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6259 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6260 route.paths[0].hops[0].fee_msat = 100;
6262 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6263 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6264 ), true, APIError::ChannelUnavailable { .. }, {});
6265 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6269 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6270 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6271 let chanmon_cfgs = create_chanmon_cfgs(2);
6272 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6273 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6274 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6275 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6277 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6278 route.paths[0].hops[0].fee_msat = 0;
6279 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6280 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)),
6281 true, APIError::ChannelUnavailable { ref err },
6282 assert_eq!(err, "Cannot send 0-msat HTLC"));
6284 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6285 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send 0-msat HTLC", 1);
6289 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6290 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6291 let chanmon_cfgs = create_chanmon_cfgs(2);
6292 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6293 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6294 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6295 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6297 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6298 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6299 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6300 check_added_monitors!(nodes[0], 1);
6301 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6302 updates.update_add_htlcs[0].amount_msat = 0;
6304 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6305 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Remote side tried to send a 0-msat HTLC", 3);
6306 check_closed_broadcast!(nodes[1], true).unwrap();
6307 check_added_monitors!(nodes[1], 1);
6308 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() },
6309 [nodes[0].node.get_our_node_id()], 100000);
6313 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6314 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6315 //It is enforced when constructing a route.
6316 let chanmon_cfgs = create_chanmon_cfgs(2);
6317 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6318 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6319 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6320 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6322 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6323 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
6324 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);
6325 route.paths[0].hops.last_mut().unwrap().cltv_expiry_delta = 500000001;
6326 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6327 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6328 ), true, APIError::InvalidRoute { ref err },
6329 assert_eq!(err, &"Channel CLTV overflowed?"));
6333 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6334 //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.
6335 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6336 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6337 let chanmon_cfgs = create_chanmon_cfgs(2);
6338 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6339 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6340 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6341 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6342 let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6343 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context().counterparty_max_accepted_htlcs as u64;
6345 // Fetch a route in advance as we will be unable to once we're unable to send.
6346 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6347 for i in 0..max_accepted_htlcs {
6348 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6349 let payment_event = {
6350 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6351 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6352 check_added_monitors!(nodes[0], 1);
6354 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6355 assert_eq!(events.len(), 1);
6356 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6357 assert_eq!(htlcs[0].htlc_id, i);
6361 SendEvent::from_event(events.remove(0))
6363 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6364 check_added_monitors!(nodes[1], 0);
6365 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6367 expect_pending_htlcs_forwardable!(nodes[1]);
6368 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6370 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6371 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6372 ), true, APIError::ChannelUnavailable { .. }, {});
6374 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6378 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6379 //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.
6380 let chanmon_cfgs = create_chanmon_cfgs(2);
6381 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6382 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6383 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6384 let channel_value = 100000;
6385 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6386 let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6388 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6390 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6391 // Manually create a route over our max in flight (which our router normally automatically
6393 route.paths[0].hops[0].fee_msat = max_in_flight + 1;
6394 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6395 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6396 ), true, APIError::ChannelUnavailable { .. }, {});
6397 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6399 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6402 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6404 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6405 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6406 let chanmon_cfgs = create_chanmon_cfgs(2);
6407 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6408 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6409 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6410 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6411 let htlc_minimum_msat: u64;
6413 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6414 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6415 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6416 htlc_minimum_msat = channel.context().get_holder_htlc_minimum_msat();
6419 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6420 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6421 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6422 check_added_monitors!(nodes[0], 1);
6423 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6424 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6425 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6426 assert!(nodes[1].node.list_channels().is_empty());
6427 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6428 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()));
6429 check_added_monitors!(nodes[1], 1);
6430 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6434 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6435 //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
6436 let chanmon_cfgs = create_chanmon_cfgs(2);
6437 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6438 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6439 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6440 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6442 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6443 let channel_reserve = chan_stat.channel_reserve_msat;
6444 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6445 let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
6446 // The 2* and +1 are for the fee spike reserve.
6447 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
6449 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6450 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6451 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6452 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6453 check_added_monitors!(nodes[0], 1);
6454 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6456 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6457 // at this time channel-initiatee receivers are not required to enforce that senders
6458 // respect the fee_spike_reserve.
6459 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6460 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6462 assert!(nodes[1].node.list_channels().is_empty());
6463 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6464 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6465 check_added_monitors!(nodes[1], 1);
6466 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6470 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6471 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6472 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6473 let chanmon_cfgs = create_chanmon_cfgs(2);
6474 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6475 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6476 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6477 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6479 let send_amt = 3999999;
6480 let (mut route, our_payment_hash, _, our_payment_secret) =
6481 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
6482 route.paths[0].hops[0].fee_msat = send_amt;
6483 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6484 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6485 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6486 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
6487 &route.paths[0], send_amt, RecipientOnionFields::secret_only(our_payment_secret), cur_height, &None).unwrap();
6488 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
6490 let mut msg = msgs::UpdateAddHTLC {
6494 payment_hash: our_payment_hash,
6495 cltv_expiry: htlc_cltv,
6496 onion_routing_packet: onion_packet.clone(),
6497 skimmed_fee_msat: None,
6498 blinding_point: None,
6502 msg.htlc_id = i as u64;
6503 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6505 msg.htlc_id = (50) as u64;
6506 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6508 assert!(nodes[1].node.list_channels().is_empty());
6509 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6510 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6511 check_added_monitors!(nodes[1], 1);
6512 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6516 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6517 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6518 let chanmon_cfgs = create_chanmon_cfgs(2);
6519 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6520 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6521 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6522 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6524 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6525 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6526 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6527 check_added_monitors!(nodes[0], 1);
6528 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6529 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;
6530 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6532 assert!(nodes[1].node.list_channels().is_empty());
6533 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6534 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6535 check_added_monitors!(nodes[1], 1);
6536 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 1000000);
6540 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6541 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6542 let chanmon_cfgs = create_chanmon_cfgs(2);
6543 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6544 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6545 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6547 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6548 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6549 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6550 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6551 check_added_monitors!(nodes[0], 1);
6552 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6553 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6554 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6556 assert!(nodes[1].node.list_channels().is_empty());
6557 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6558 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6559 check_added_monitors!(nodes[1], 1);
6560 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6564 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6565 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6566 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6567 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6568 let chanmon_cfgs = create_chanmon_cfgs(2);
6569 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6570 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6571 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6573 create_announced_chan_between_nodes(&nodes, 0, 1);
6574 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6575 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6576 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6577 check_added_monitors!(nodes[0], 1);
6578 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6579 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6581 //Disconnect and Reconnect
6582 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
6583 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
6584 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
6585 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
6587 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6588 assert_eq!(reestablish_1.len(), 1);
6589 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
6590 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
6592 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6593 assert_eq!(reestablish_2.len(), 1);
6594 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6595 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6596 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6597 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6600 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6601 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6602 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6603 check_added_monitors!(nodes[1], 1);
6604 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6606 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6608 assert!(nodes[1].node.list_channels().is_empty());
6609 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6610 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6611 check_added_monitors!(nodes[1], 1);
6612 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6616 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6617 //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.
6619 let chanmon_cfgs = create_chanmon_cfgs(2);
6620 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6621 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6622 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6623 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6624 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6625 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6626 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6628 check_added_monitors!(nodes[0], 1);
6629 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6630 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6632 let update_msg = msgs::UpdateFulfillHTLC{
6635 payment_preimage: our_payment_preimage,
6638 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6640 assert!(nodes[0].node.list_channels().is_empty());
6641 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6642 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()));
6643 check_added_monitors!(nodes[0], 1);
6644 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6648 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6649 //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.
6651 let chanmon_cfgs = create_chanmon_cfgs(2);
6652 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6653 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6654 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6655 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6657 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6658 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6659 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6660 check_added_monitors!(nodes[0], 1);
6661 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6662 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6664 let update_msg = msgs::UpdateFailHTLC{
6667 reason: msgs::OnionErrorPacket { data: Vec::new()},
6670 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6672 assert!(nodes[0].node.list_channels().is_empty());
6673 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6674 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()));
6675 check_added_monitors!(nodes[0], 1);
6676 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6680 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6681 //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.
6683 let chanmon_cfgs = create_chanmon_cfgs(2);
6684 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6685 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6686 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6687 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6689 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6690 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6691 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6692 check_added_monitors!(nodes[0], 1);
6693 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6694 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6695 let update_msg = msgs::UpdateFailMalformedHTLC{
6698 sha256_of_onion: [1; 32],
6699 failure_code: 0x8000,
6702 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6704 assert!(nodes[0].node.list_channels().is_empty());
6705 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6706 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()));
6707 check_added_monitors!(nodes[0], 1);
6708 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6712 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6713 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6715 let chanmon_cfgs = create_chanmon_cfgs(2);
6716 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6717 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6718 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6719 create_announced_chan_between_nodes(&nodes, 0, 1);
6721 let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6723 nodes[1].node.claim_funds(our_payment_preimage);
6724 check_added_monitors!(nodes[1], 1);
6725 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6727 let events = nodes[1].node.get_and_clear_pending_msg_events();
6728 assert_eq!(events.len(), 1);
6729 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6731 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, .. } } => {
6732 assert!(update_add_htlcs.is_empty());
6733 assert_eq!(update_fulfill_htlcs.len(), 1);
6734 assert!(update_fail_htlcs.is_empty());
6735 assert!(update_fail_malformed_htlcs.is_empty());
6736 assert!(update_fee.is_none());
6737 update_fulfill_htlcs[0].clone()
6739 _ => panic!("Unexpected event"),
6743 update_fulfill_msg.htlc_id = 1;
6745 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6747 assert!(nodes[0].node.list_channels().is_empty());
6748 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6749 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6750 check_added_monitors!(nodes[0], 1);
6751 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6755 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6756 //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.
6758 let chanmon_cfgs = create_chanmon_cfgs(2);
6759 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6760 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6761 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6762 create_announced_chan_between_nodes(&nodes, 0, 1);
6764 let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6766 nodes[1].node.claim_funds(our_payment_preimage);
6767 check_added_monitors!(nodes[1], 1);
6768 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6770 let events = nodes[1].node.get_and_clear_pending_msg_events();
6771 assert_eq!(events.len(), 1);
6772 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6774 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, .. } } => {
6775 assert!(update_add_htlcs.is_empty());
6776 assert_eq!(update_fulfill_htlcs.len(), 1);
6777 assert!(update_fail_htlcs.is_empty());
6778 assert!(update_fail_malformed_htlcs.is_empty());
6779 assert!(update_fee.is_none());
6780 update_fulfill_htlcs[0].clone()
6782 _ => panic!("Unexpected event"),
6786 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6788 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6790 assert!(nodes[0].node.list_channels().is_empty());
6791 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6792 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6793 check_added_monitors!(nodes[0], 1);
6794 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6798 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6799 //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.
6801 let chanmon_cfgs = create_chanmon_cfgs(2);
6802 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6803 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6804 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6805 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6807 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6808 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6809 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6810 check_added_monitors!(nodes[0], 1);
6812 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6813 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6815 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6816 check_added_monitors!(nodes[1], 0);
6817 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6819 let events = nodes[1].node.get_and_clear_pending_msg_events();
6821 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6823 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, .. } } => {
6824 assert!(update_add_htlcs.is_empty());
6825 assert!(update_fulfill_htlcs.is_empty());
6826 assert!(update_fail_htlcs.is_empty());
6827 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6828 assert!(update_fee.is_none());
6829 update_fail_malformed_htlcs[0].clone()
6831 _ => panic!("Unexpected event"),
6834 update_msg.failure_code &= !0x8000;
6835 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6837 assert!(nodes[0].node.list_channels().is_empty());
6838 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6839 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6840 check_added_monitors!(nodes[0], 1);
6841 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 1000000);
6845 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6846 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6847 // * 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.
6849 let chanmon_cfgs = create_chanmon_cfgs(3);
6850 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6851 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6852 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6853 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6854 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000);
6856 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6859 let mut payment_event = {
6860 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6861 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6862 check_added_monitors!(nodes[0], 1);
6863 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6864 assert_eq!(events.len(), 1);
6865 SendEvent::from_event(events.remove(0))
6867 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6868 check_added_monitors!(nodes[1], 0);
6869 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6870 expect_pending_htlcs_forwardable!(nodes[1]);
6871 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6872 assert_eq!(events_2.len(), 1);
6873 check_added_monitors!(nodes[1], 1);
6874 payment_event = SendEvent::from_event(events_2.remove(0));
6875 assert_eq!(payment_event.msgs.len(), 1);
6878 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6879 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6880 check_added_monitors!(nodes[2], 0);
6881 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6883 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6884 assert_eq!(events_3.len(), 1);
6885 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6887 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 } } => {
6888 assert!(update_add_htlcs.is_empty());
6889 assert!(update_fulfill_htlcs.is_empty());
6890 assert!(update_fail_htlcs.is_empty());
6891 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6892 assert!(update_fee.is_none());
6893 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6895 _ => panic!("Unexpected event"),
6899 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6901 check_added_monitors!(nodes[1], 0);
6902 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6903 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 }]);
6904 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6905 assert_eq!(events_4.len(), 1);
6907 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6909 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, .. } } => {
6910 assert!(update_add_htlcs.is_empty());
6911 assert!(update_fulfill_htlcs.is_empty());
6912 assert_eq!(update_fail_htlcs.len(), 1);
6913 assert!(update_fail_malformed_htlcs.is_empty());
6914 assert!(update_fee.is_none());
6916 _ => panic!("Unexpected event"),
6919 check_added_monitors!(nodes[1], 1);
6923 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6924 let chanmon_cfgs = create_chanmon_cfgs(3);
6925 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6926 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6927 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6928 create_announced_chan_between_nodes(&nodes, 0, 1);
6929 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6931 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6934 let mut payment_event = {
6935 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6936 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6937 check_added_monitors!(nodes[0], 1);
6938 SendEvent::from_node(&nodes[0])
6941 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6942 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6943 expect_pending_htlcs_forwardable!(nodes[1]);
6944 check_added_monitors!(nodes[1], 1);
6945 payment_event = SendEvent::from_node(&nodes[1]);
6946 assert_eq!(payment_event.msgs.len(), 1);
6949 payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6950 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6951 check_added_monitors!(nodes[2], 0);
6952 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6954 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6955 assert_eq!(events_3.len(), 1);
6957 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6958 let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6959 // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6960 update_msg.failure_code |= 0x2000;
6962 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6963 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6965 _ => panic!("Unexpected event"),
6968 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6969 vec![HTLCDestination::NextHopChannel {
6970 node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6971 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6972 assert_eq!(events_4.len(), 1);
6973 check_added_monitors!(nodes[1], 1);
6976 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6977 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6978 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6980 _ => panic!("Unexpected event"),
6983 let events_5 = nodes[0].node.get_and_clear_pending_events();
6984 assert_eq!(events_5.len(), 2);
6986 // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6987 // the node originating the error to its next hop.
6989 Event::PaymentPathFailed { error_code, failure: PathFailure::OnPath { network_update: Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }) }, ..
6991 assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6992 assert!(is_permanent);
6993 assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
6995 _ => panic!("Unexpected event"),
6998 Event::PaymentFailed { payment_hash, .. } => {
6999 assert_eq!(payment_hash, our_payment_hash);
7001 _ => panic!("Unexpected event"),
7004 // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
7007 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7008 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7009 // 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
7010 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7012 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7013 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7014 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7015 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7016 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7017 let chan =create_announced_chan_between_nodes(&nodes, 0, 1);
7019 let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
7020 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context().holder_dust_limit_satoshis;
7022 // We route 2 dust-HTLCs between A and B
7023 let (_, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7024 let (_, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7025 route_payment(&nodes[0], &[&nodes[1]], 1000000);
7027 // Cache one local commitment tx as previous
7028 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7030 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7031 nodes[1].node.fail_htlc_backwards(&payment_hash_2);
7032 check_added_monitors!(nodes[1], 0);
7033 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7034 check_added_monitors!(nodes[1], 1);
7036 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7037 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7038 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7039 check_added_monitors!(nodes[0], 1);
7041 // Cache one local commitment tx as lastest
7042 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7044 let events = nodes[0].node.get_and_clear_pending_msg_events();
7046 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7047 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7049 _ => panic!("Unexpected event"),
7052 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7053 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7055 _ => panic!("Unexpected event"),
7058 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7059 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7060 if announce_latest {
7061 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7063 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7066 check_closed_broadcast!(nodes[0], true);
7067 check_added_monitors!(nodes[0], 1);
7068 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7070 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7071 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7072 let events = nodes[0].node.get_and_clear_pending_events();
7073 // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7074 assert_eq!(events.len(), 4);
7075 let mut first_failed = false;
7076 for event in events {
7078 Event::PaymentPathFailed { payment_hash, .. } => {
7079 if payment_hash == payment_hash_1 {
7080 assert!(!first_failed);
7081 first_failed = true;
7083 assert_eq!(payment_hash, payment_hash_2);
7086 Event::PaymentFailed { .. } => {}
7087 _ => panic!("Unexpected event"),
7093 fn test_failure_delay_dust_htlc_local_commitment() {
7094 do_test_failure_delay_dust_htlc_local_commitment(true);
7095 do_test_failure_delay_dust_htlc_local_commitment(false);
7098 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7099 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7100 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7101 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7102 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7103 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7104 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7106 let chanmon_cfgs = create_chanmon_cfgs(3);
7107 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7108 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7109 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7110 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
7112 let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
7113 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context().holder_dust_limit_satoshis;
7115 let (_payment_preimage_1, dust_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7116 let (_payment_preimage_2, non_dust_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7118 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7119 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7121 // We revoked bs_commitment_tx
7123 let (payment_preimage_3, ..) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7124 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7127 let mut timeout_tx = Vec::new();
7129 // We fail dust-HTLC 1 by broadcast of local commitment tx
7130 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7131 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7132 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7133 expect_payment_failed!(nodes[0], dust_hash, false);
7135 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7136 check_closed_broadcast!(nodes[0], true);
7137 check_added_monitors!(nodes[0], 1);
7138 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7139 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7140 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7141 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7142 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7143 mine_transaction(&nodes[0], &timeout_tx[0]);
7144 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7145 expect_payment_failed!(nodes[0], non_dust_hash, false);
7147 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7148 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7149 check_closed_broadcast!(nodes[0], true);
7150 check_added_monitors!(nodes[0], 1);
7151 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7152 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7154 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7155 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
7156 .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
7157 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
7158 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
7159 // dust HTLC should have been failed.
7160 expect_payment_failed!(nodes[0], dust_hash, false);
7163 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7165 assert_eq!(timeout_tx[0].lock_time.to_consensus_u32(), 11);
7167 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
7168 mine_transaction(&nodes[0], &timeout_tx[0]);
7169 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7170 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7171 expect_payment_failed!(nodes[0], non_dust_hash, false);
7176 fn test_sweep_outbound_htlc_failure_update() {
7177 do_test_sweep_outbound_htlc_failure_update(false, true);
7178 do_test_sweep_outbound_htlc_failure_update(false, false);
7179 do_test_sweep_outbound_htlc_failure_update(true, false);
7183 fn test_user_configurable_csv_delay() {
7184 // We test our channel constructors yield errors when we pass them absurd csv delay
7186 let mut low_our_to_self_config = UserConfig::default();
7187 low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
7188 let mut high_their_to_self_config = UserConfig::default();
7189 high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
7190 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7191 let chanmon_cfgs = create_chanmon_cfgs(2);
7192 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7193 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7194 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7196 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in OutboundV1Channel::new()
7197 if let Err(error) = OutboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7198 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[1].node.init_features(), 1000000, 1000000, 0,
7199 &low_our_to_self_config, 0, 42, None)
7202 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())); },
7203 _ => panic!("Unexpected event"),
7205 } else { assert!(false) }
7207 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in InboundV1Channel::new()
7208 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None, None).unwrap();
7209 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7210 open_channel.to_self_delay = 200;
7211 if let Err(error) = InboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7212 &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,
7213 &low_our_to_self_config, 0, &nodes[0].logger, /*is_0conf=*/false)
7216 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())); },
7217 _ => panic!("Unexpected event"),
7219 } else { assert!(false); }
7221 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7222 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None, None).unwrap();
7223 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()));
7224 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7225 accept_channel.to_self_delay = 200;
7226 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
7228 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7230 &ErrorAction::SendErrorMessage { ref msg } => {
7231 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()));
7232 reason_msg = msg.data.clone();
7236 } else { panic!(); }
7237 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg }, [nodes[1].node.get_our_node_id()], 1000000);
7239 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in InboundV1Channel::new()
7240 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None, None).unwrap();
7241 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7242 open_channel.to_self_delay = 200;
7243 if let Err(error) = InboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7244 &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,
7245 &high_their_to_self_config, 0, &nodes[0].logger, /*is_0conf=*/false)
7248 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())); },
7249 _ => panic!("Unexpected event"),
7251 } else { assert!(false); }
7255 fn test_check_htlc_underpaying() {
7256 // Send payment through A -> B but A is maliciously
7257 // sending a probe payment (i.e less than expected value0
7258 // to B, B should refuse payment.
7260 let chanmon_cfgs = create_chanmon_cfgs(2);
7261 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7262 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7263 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7265 // Create some initial channels
7266 create_announced_chan_between_nodes(&nodes, 0, 1);
7268 let scorer = test_utils::TestScorer::new();
7269 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7270 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
7271 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
7272 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 10_000);
7273 let route = get_route(&nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph.read_only(),
7274 None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes).unwrap();
7275 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7276 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, None).unwrap();
7277 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
7278 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
7279 check_added_monitors!(nodes[0], 1);
7281 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7282 assert_eq!(events.len(), 1);
7283 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7284 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7285 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7287 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7288 // and then will wait a second random delay before failing the HTLC back:
7289 expect_pending_htlcs_forwardable!(nodes[1]);
7290 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7292 // Node 3 is expecting payment of 100_000 but received 10_000,
7293 // it should fail htlc like we didn't know the preimage.
7294 nodes[1].node.process_pending_htlc_forwards();
7296 let events = nodes[1].node.get_and_clear_pending_msg_events();
7297 assert_eq!(events.len(), 1);
7298 let (update_fail_htlc, commitment_signed) = match events[0] {
7299 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 } } => {
7300 assert!(update_add_htlcs.is_empty());
7301 assert!(update_fulfill_htlcs.is_empty());
7302 assert_eq!(update_fail_htlcs.len(), 1);
7303 assert!(update_fail_malformed_htlcs.is_empty());
7304 assert!(update_fee.is_none());
7305 (update_fail_htlcs[0].clone(), commitment_signed)
7307 _ => panic!("Unexpected event"),
7309 check_added_monitors!(nodes[1], 1);
7311 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7312 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7314 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7315 let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
7316 expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
7317 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7321 fn test_announce_disable_channels() {
7322 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7323 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7325 let chanmon_cfgs = create_chanmon_cfgs(2);
7326 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7327 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7328 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7330 create_announced_chan_between_nodes(&nodes, 0, 1);
7331 create_announced_chan_between_nodes(&nodes, 1, 0);
7332 create_announced_chan_between_nodes(&nodes, 0, 1);
7335 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
7336 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
7338 for _ in 0..DISABLE_GOSSIP_TICKS + 1 {
7339 nodes[0].node.timer_tick_occurred();
7341 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7342 assert_eq!(msg_events.len(), 3);
7343 let mut chans_disabled = HashMap::new();
7344 for e in msg_events {
7346 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7347 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7348 // Check that each channel gets updated exactly once
7349 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7350 panic!("Generated ChannelUpdate for wrong chan!");
7353 _ => panic!("Unexpected event"),
7357 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
7358 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
7360 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7361 assert_eq!(reestablish_1.len(), 3);
7362 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
7363 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
7365 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7366 assert_eq!(reestablish_2.len(), 3);
7368 // Reestablish chan_1
7369 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7370 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7371 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7372 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7373 // Reestablish chan_2
7374 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7375 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7376 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7377 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7378 // Reestablish chan_3
7379 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7380 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7381 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7382 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7384 for _ in 0..ENABLE_GOSSIP_TICKS {
7385 nodes[0].node.timer_tick_occurred();
7387 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7388 nodes[0].node.timer_tick_occurred();
7389 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7390 assert_eq!(msg_events.len(), 3);
7391 for e in msg_events {
7393 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7394 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7395 match chans_disabled.remove(&msg.contents.short_channel_id) {
7396 // Each update should have a higher timestamp than the previous one, replacing
7398 Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7399 None => panic!("Generated ChannelUpdate for wrong chan!"),
7402 _ => panic!("Unexpected event"),
7405 // Check that each channel gets updated exactly once
7406 assert!(chans_disabled.is_empty());
7410 fn test_bump_penalty_txn_on_revoked_commitment() {
7411 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7412 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7414 let chanmon_cfgs = create_chanmon_cfgs(2);
7415 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7416 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7417 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7419 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7421 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7422 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7423 .with_bolt11_features(nodes[0].node.bolt11_invoice_features()).unwrap();
7424 let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000);
7425 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7427 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7428 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7429 assert_eq!(revoked_txn[0].output.len(), 4);
7430 assert_eq!(revoked_txn[0].input.len(), 1);
7431 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7432 let revoked_txid = revoked_txn[0].txid();
7434 let mut penalty_sum = 0;
7435 for outp in revoked_txn[0].output.iter() {
7436 if outp.script_pubkey.is_v0_p2wsh() {
7437 penalty_sum += outp.value;
7441 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7442 let header_114 = connect_blocks(&nodes[1], 14);
7444 // Actually revoke tx by claiming a HTLC
7445 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7446 connect_block(&nodes[1], &create_dummy_block(header_114, 42, vec![revoked_txn[0].clone()]));
7447 check_added_monitors!(nodes[1], 1);
7449 // One or more justice tx should have been broadcast, check it
7453 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7454 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7455 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7456 assert_eq!(node_txn[0].output.len(), 1);
7457 check_spends!(node_txn[0], revoked_txn[0]);
7458 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7459 feerate_1 = fee_1 * 1000 / node_txn[0].weight().to_wu();
7460 penalty_1 = node_txn[0].txid();
7464 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7465 connect_blocks(&nodes[1], 15);
7466 let mut penalty_2 = penalty_1;
7467 let mut feerate_2 = 0;
7469 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7470 assert_eq!(node_txn.len(), 1);
7471 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7472 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7473 assert_eq!(node_txn[0].output.len(), 1);
7474 check_spends!(node_txn[0], revoked_txn[0]);
7475 penalty_2 = node_txn[0].txid();
7476 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7477 assert_ne!(penalty_2, penalty_1);
7478 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7479 feerate_2 = fee_2 * 1000 / node_txn[0].weight().to_wu();
7480 // Verify 25% bump heuristic
7481 assert!(feerate_2 * 100 >= feerate_1 * 125);
7485 assert_ne!(feerate_2, 0);
7487 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7488 connect_blocks(&nodes[1], 1);
7490 let mut feerate_3 = 0;
7492 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7493 assert_eq!(node_txn.len(), 1);
7494 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7495 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7496 assert_eq!(node_txn[0].output.len(), 1);
7497 check_spends!(node_txn[0], revoked_txn[0]);
7498 penalty_3 = node_txn[0].txid();
7499 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7500 assert_ne!(penalty_3, penalty_2);
7501 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7502 feerate_3 = fee_3 * 1000 / node_txn[0].weight().to_wu();
7503 // Verify 25% bump heuristic
7504 assert!(feerate_3 * 100 >= feerate_2 * 125);
7508 assert_ne!(feerate_3, 0);
7510 nodes[1].node.get_and_clear_pending_events();
7511 nodes[1].node.get_and_clear_pending_msg_events();
7515 fn test_bump_penalty_txn_on_revoked_htlcs() {
7516 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7517 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7519 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7520 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7521 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7522 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7523 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7525 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7526 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7527 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();
7528 let scorer = test_utils::TestScorer::new();
7529 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7530 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 3_000_000);
7531 let route = get_route(&nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph.read_only(), None,
7532 nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes).unwrap();
7533 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7534 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50)
7535 .with_bolt11_features(nodes[0].node.bolt11_invoice_features()).unwrap();
7536 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 3_000_000);
7537 let route = get_route(&nodes[1].node.get_our_node_id(), &route_params, &nodes[1].network_graph.read_only(), None,
7538 nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes).unwrap();
7539 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7541 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7542 assert_eq!(revoked_local_txn[0].input.len(), 1);
7543 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7545 // Revoke local commitment tx
7546 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7548 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7549 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone()]));
7550 check_closed_broadcast!(nodes[1], true);
7551 check_added_monitors!(nodes[1], 1);
7552 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 1000000);
7553 connect_blocks(&nodes[1], 50); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7555 let revoked_htlc_txn = {
7556 let txn = nodes[1].tx_broadcaster.unique_txn_broadcast();
7557 assert_eq!(txn.len(), 2);
7559 assert_eq!(txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7560 assert_eq!(txn[0].input.len(), 1);
7561 check_spends!(txn[0], revoked_local_txn[0]);
7563 assert_eq!(txn[1].input.len(), 1);
7564 assert_eq!(txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7565 assert_eq!(txn[1].output.len(), 1);
7566 check_spends!(txn[1], revoked_local_txn[0]);
7571 // Broadcast set of revoked txn on A
7572 let hash_128 = connect_blocks(&nodes[0], 40);
7573 let block_11 = create_dummy_block(hash_128, 42, vec![revoked_local_txn[0].clone()]);
7574 connect_block(&nodes[0], &block_11);
7575 let block_129 = create_dummy_block(block_11.block_hash(), 42, vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()]);
7576 connect_block(&nodes[0], &block_129);
7577 let events = nodes[0].node.get_and_clear_pending_events();
7578 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7579 match events.last().unwrap() {
7580 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7581 _ => panic!("Unexpected event"),
7587 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7588 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7589 // Verify claim tx are spending revoked HTLC txn
7591 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7592 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7593 // which are included in the same block (they are broadcasted because we scan the
7594 // transactions linearly and generate claims as we go, they likely should be removed in the
7596 assert_eq!(node_txn[0].input.len(), 1);
7597 check_spends!(node_txn[0], revoked_local_txn[0]);
7598 assert_eq!(node_txn[1].input.len(), 1);
7599 check_spends!(node_txn[1], revoked_local_txn[0]);
7600 assert_eq!(node_txn[2].input.len(), 1);
7601 check_spends!(node_txn[2], revoked_local_txn[0]);
7603 // Each of the three justice transactions claim a separate (single) output of the three
7604 // available, which we check here:
7605 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7606 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7607 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7609 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7610 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7612 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7613 // output, checked above).
7614 assert_eq!(node_txn[3].input.len(), 2);
7615 assert_eq!(node_txn[3].output.len(), 1);
7616 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7618 first = node_txn[3].txid();
7619 // Store both feerates for later comparison
7620 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7621 feerate_1 = fee_1 * 1000 / node_txn[3].weight().to_wu();
7622 penalty_txn = vec![node_txn[2].clone()];
7626 // Connect one more block to see if bumped penalty are issued for HTLC txn
7627 let block_130 = create_dummy_block(block_129.block_hash(), 42, penalty_txn);
7628 connect_block(&nodes[0], &block_130);
7629 let block_131 = create_dummy_block(block_130.block_hash(), 42, Vec::new());
7630 connect_block(&nodes[0], &block_131);
7632 // Few more blocks to confirm penalty txn
7633 connect_blocks(&nodes[0], 4);
7634 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7635 let header_144 = connect_blocks(&nodes[0], 9);
7637 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7638 assert_eq!(node_txn.len(), 1);
7640 assert_eq!(node_txn[0].input.len(), 2);
7641 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7642 // Verify bumped tx is different and 25% bump heuristic
7643 assert_ne!(first, node_txn[0].txid());
7644 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7645 let feerate_2 = fee_2 * 1000 / node_txn[0].weight().to_wu();
7646 assert!(feerate_2 * 100 > feerate_1 * 125);
7647 let txn = vec![node_txn[0].clone()];
7651 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7652 connect_block(&nodes[0], &create_dummy_block(header_144, 42, node_txn));
7653 connect_blocks(&nodes[0], 20);
7655 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7656 // We verify than no new transaction has been broadcast because previously
7657 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7658 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7659 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7660 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7661 // up bumped justice generation.
7662 assert_eq!(node_txn.len(), 0);
7665 check_closed_broadcast!(nodes[0], true);
7666 check_added_monitors!(nodes[0], 1);
7670 fn test_bump_penalty_txn_on_remote_commitment() {
7671 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7672 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7675 // Provide preimage for one
7676 // Check aggregation
7678 let chanmon_cfgs = create_chanmon_cfgs(2);
7679 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7680 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7681 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7683 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7684 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7685 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7687 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7688 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7689 assert_eq!(remote_txn[0].output.len(), 4);
7690 assert_eq!(remote_txn[0].input.len(), 1);
7691 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7693 // Claim a HTLC without revocation (provide B monitor with preimage)
7694 nodes[1].node.claim_funds(payment_preimage);
7695 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7696 mine_transaction(&nodes[1], &remote_txn[0]);
7697 check_added_monitors!(nodes[1], 2);
7698 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7700 // One or more claim tx should have been broadcast, check it
7704 let feerate_timeout;
7705 let feerate_preimage;
7707 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7708 // 3 transactions including:
7709 // preimage and timeout sweeps from remote commitment + preimage sweep bump
7710 assert_eq!(node_txn.len(), 3);
7711 assert_eq!(node_txn[0].input.len(), 1);
7712 assert_eq!(node_txn[1].input.len(), 1);
7713 assert_eq!(node_txn[2].input.len(), 1);
7714 check_spends!(node_txn[0], remote_txn[0]);
7715 check_spends!(node_txn[1], remote_txn[0]);
7716 check_spends!(node_txn[2], remote_txn[0]);
7718 preimage = node_txn[0].txid();
7719 let index = node_txn[0].input[0].previous_output.vout;
7720 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7721 feerate_preimage = fee * 1000 / node_txn[0].weight().to_wu();
7723 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7724 (node_txn[2].clone(), node_txn[1].clone())
7726 (node_txn[1].clone(), node_txn[2].clone())
7729 preimage_bump = preimage_bump_tx;
7730 check_spends!(preimage_bump, remote_txn[0]);
7731 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7733 timeout = timeout_tx.txid();
7734 let index = timeout_tx.input[0].previous_output.vout;
7735 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7736 feerate_timeout = fee * 1000 / timeout_tx.weight().to_wu();
7740 assert_ne!(feerate_timeout, 0);
7741 assert_ne!(feerate_preimage, 0);
7743 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7744 connect_blocks(&nodes[1], 1);
7746 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7747 assert_eq!(node_txn.len(), 1);
7748 assert_eq!(node_txn[0].input.len(), 1);
7749 assert_eq!(preimage_bump.input.len(), 1);
7750 check_spends!(node_txn[0], remote_txn[0]);
7751 check_spends!(preimage_bump, remote_txn[0]);
7753 let index = preimage_bump.input[0].previous_output.vout;
7754 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7755 let new_feerate = fee * 1000 / preimage_bump.weight().to_wu();
7756 assert!(new_feerate * 100 > feerate_timeout * 125);
7757 assert_ne!(timeout, preimage_bump.txid());
7759 let index = node_txn[0].input[0].previous_output.vout;
7760 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7761 let new_feerate = fee * 1000 / node_txn[0].weight().to_wu();
7762 assert!(new_feerate * 100 > feerate_preimage * 125);
7763 assert_ne!(preimage, node_txn[0].txid());
7768 nodes[1].node.get_and_clear_pending_events();
7769 nodes[1].node.get_and_clear_pending_msg_events();
7773 fn test_counterparty_raa_skip_no_crash() {
7774 // Previously, if our counterparty sent two RAAs in a row without us having provided a
7775 // commitment transaction, we would have happily carried on and provided them the next
7776 // commitment transaction based on one RAA forward. This would probably eventually have led to
7777 // channel closure, but it would not have resulted in funds loss. Still, our
7778 // TestChannelSigner would have panicked as it doesn't like jumps into the future. Here, we
7779 // check simply that the channel is closed in response to such an RAA, but don't check whether
7780 // we decide to punish our counterparty for revoking their funds (as we don't currently
7782 let chanmon_cfgs = create_chanmon_cfgs(2);
7783 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7784 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7785 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7786 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7788 let per_commitment_secret;
7789 let next_per_commitment_point;
7791 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7792 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7793 let keys = guard.channel_by_id.get_mut(&channel_id).map(
7794 |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
7795 ).flatten().unwrap().get_signer();
7797 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7799 // Make signer believe we got a counterparty signature, so that it allows the revocation
7800 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7801 per_commitment_secret = keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7803 // Must revoke without gaps
7804 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7805 keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7807 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7808 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7809 &SecretKey::from_slice(&keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7812 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7813 &msgs::RevokeAndACK {
7815 per_commitment_secret,
7816 next_per_commitment_point,
7818 next_local_nonce: None,
7820 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7821 check_added_monitors!(nodes[1], 1);
7822 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() }
7823 , [nodes[0].node.get_our_node_id()], 100000);
7827 fn test_bump_txn_sanitize_tracking_maps() {
7828 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7829 // verify we clean then right after expiration of ANTI_REORG_DELAY.
7831 let chanmon_cfgs = create_chanmon_cfgs(2);
7832 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7833 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7834 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7836 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7837 // Lock HTLC in both directions
7838 let (payment_preimage_1, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7839 let (_, payment_hash_2, ..) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7841 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7842 assert_eq!(revoked_local_txn[0].input.len(), 1);
7843 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7845 // Revoke local commitment tx
7846 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7848 // Broadcast set of revoked txn on A
7849 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7850 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7851 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7853 mine_transaction(&nodes[0], &revoked_local_txn[0]);
7854 check_closed_broadcast!(nodes[0], true);
7855 check_added_monitors!(nodes[0], 1);
7856 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 1000000);
7858 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7859 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7860 check_spends!(node_txn[0], revoked_local_txn[0]);
7861 check_spends!(node_txn[1], revoked_local_txn[0]);
7862 check_spends!(node_txn[2], revoked_local_txn[0]);
7863 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7867 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, penalty_txn));
7868 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7870 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7871 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7872 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7877 fn test_channel_conf_timeout() {
7878 // Tests that, for inbound channels, we give up on them if the funding transaction does not
7879 // confirm within 2016 blocks, as recommended by BOLT 2.
7880 let chanmon_cfgs = create_chanmon_cfgs(2);
7881 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7882 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7883 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7885 let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7887 // The outbound node should wait forever for confirmation:
7888 // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7889 // copied here instead of directly referencing the constant.
7890 connect_blocks(&nodes[0], 2016);
7891 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7893 // The inbound node should fail the channel after exactly 2016 blocks
7894 connect_blocks(&nodes[1], 2015);
7895 check_added_monitors!(nodes[1], 0);
7896 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7898 connect_blocks(&nodes[1], 1);
7899 check_added_monitors!(nodes[1], 1);
7900 check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut, [nodes[0].node.get_our_node_id()], 1000000);
7901 let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7902 assert_eq!(close_ev.len(), 1);
7904 MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { ref msg }, ref node_id } => {
7905 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7906 assert_eq!(msg.as_ref().unwrap().data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7908 _ => panic!("Unexpected event"),
7913 fn test_override_channel_config() {
7914 let chanmon_cfgs = create_chanmon_cfgs(2);
7915 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7916 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7917 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7919 // Node0 initiates a channel to node1 using the override config.
7920 let mut override_config = UserConfig::default();
7921 override_config.channel_handshake_config.our_to_self_delay = 200;
7923 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, None, Some(override_config)).unwrap();
7925 // Assert the channel created by node0 is using the override config.
7926 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7927 assert_eq!(res.channel_flags, 0);
7928 assert_eq!(res.to_self_delay, 200);
7932 fn test_override_0msat_htlc_minimum() {
7933 let mut zero_config = UserConfig::default();
7934 zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7935 let chanmon_cfgs = create_chanmon_cfgs(2);
7936 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7937 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7938 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7940 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, None, Some(zero_config)).unwrap();
7941 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7942 assert_eq!(res.htlc_minimum_msat, 1);
7944 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7945 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7946 assert_eq!(res.htlc_minimum_msat, 1);
7950 fn test_channel_update_has_correct_htlc_maximum_msat() {
7951 // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7952 // Bolt 7 specifies that if present `htlc_maximum_msat`:
7953 // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7954 // 90% of the `channel_value`.
7955 // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7957 let mut config_30_percent = UserConfig::default();
7958 config_30_percent.channel_handshake_config.announced_channel = true;
7959 config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7960 let mut config_50_percent = UserConfig::default();
7961 config_50_percent.channel_handshake_config.announced_channel = true;
7962 config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7963 let mut config_95_percent = UserConfig::default();
7964 config_95_percent.channel_handshake_config.announced_channel = true;
7965 config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7966 let mut config_100_percent = UserConfig::default();
7967 config_100_percent.channel_handshake_config.announced_channel = true;
7968 config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7970 let chanmon_cfgs = create_chanmon_cfgs(4);
7971 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7972 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)]);
7973 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7975 let channel_value_satoshis = 100000;
7976 let channel_value_msat = channel_value_satoshis * 1000;
7977 let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7978 let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7979 let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7981 let (node_0_chan_update, node_1_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
7982 let (node_2_chan_update, node_3_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
7984 // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7985 // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7986 assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7987 // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7988 // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7989 assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7991 // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7992 // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7994 assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7995 // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7996 // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7998 assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
8002 fn test_manually_accept_inbound_channel_request() {
8003 let mut manually_accept_conf = UserConfig::default();
8004 manually_accept_conf.manually_accept_inbound_channels = true;
8005 let chanmon_cfgs = create_chanmon_cfgs(2);
8006 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8007 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8008 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8010 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();
8011 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8013 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
8015 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8016 // accepting the inbound channel request.
8017 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8019 let events = nodes[1].node.get_and_clear_pending_events();
8021 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8022 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
8024 _ => panic!("Unexpected event"),
8027 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8028 assert_eq!(accept_msg_ev.len(), 1);
8030 match accept_msg_ev[0] {
8031 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8032 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8034 _ => panic!("Unexpected event"),
8037 nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8039 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8040 assert_eq!(close_msg_ev.len(), 1);
8042 let events = nodes[1].node.get_and_clear_pending_events();
8044 Event::ChannelClosed { user_channel_id, .. } => {
8045 assert_eq!(user_channel_id, 23);
8047 _ => panic!("Unexpected event"),
8052 fn test_manually_reject_inbound_channel_request() {
8053 let mut manually_accept_conf = UserConfig::default();
8054 manually_accept_conf.manually_accept_inbound_channels = true;
8055 let chanmon_cfgs = create_chanmon_cfgs(2);
8056 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8057 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8058 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8060 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, Some(manually_accept_conf)).unwrap();
8061 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8063 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
8065 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8066 // rejecting the inbound channel request.
8067 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8069 let events = nodes[1].node.get_and_clear_pending_events();
8071 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8072 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8074 _ => panic!("Unexpected event"),
8077 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8078 assert_eq!(close_msg_ev.len(), 1);
8080 match close_msg_ev[0] {
8081 MessageSendEvent::HandleError { ref node_id, .. } => {
8082 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8084 _ => panic!("Unexpected event"),
8087 // There should be no more events to process, as the channel was never opened.
8088 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
8092 fn test_can_not_accept_inbound_channel_twice() {
8093 let mut manually_accept_conf = UserConfig::default();
8094 manually_accept_conf.manually_accept_inbound_channels = true;
8095 let chanmon_cfgs = create_chanmon_cfgs(2);
8096 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8097 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8098 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8100 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, Some(manually_accept_conf)).unwrap();
8101 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8103 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
8105 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8106 // accepting the inbound channel request.
8107 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8109 let events = nodes[1].node.get_and_clear_pending_events();
8111 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8112 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
8113 let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
8115 Err(APIError::APIMisuseError { err }) => {
8116 assert_eq!(err, "No such channel awaiting to be accepted.");
8118 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8119 Err(e) => panic!("Unexpected Error {:?}", e),
8122 _ => panic!("Unexpected event"),
8125 // Ensure that the channel wasn't closed after attempting to accept it twice.
8126 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8127 assert_eq!(accept_msg_ev.len(), 1);
8129 match accept_msg_ev[0] {
8130 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8131 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8133 _ => panic!("Unexpected event"),
8138 fn test_can_not_accept_unknown_inbound_channel() {
8139 let chanmon_cfg = create_chanmon_cfgs(2);
8140 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8141 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8142 let nodes = create_network(2, &node_cfg, &node_chanmgr);
8144 let unknown_channel_id = ChannelId::new_zero();
8145 let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
8147 Err(APIError::APIMisuseError { err }) => {
8148 assert_eq!(err, "No such channel awaiting to be accepted.");
8150 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8151 Err(e) => panic!("Unexpected Error: {:?}", e),
8156 fn test_onion_value_mpp_set_calculation() {
8157 // Test that we use the onion value `amt_to_forward` when
8158 // calculating whether we've reached the `total_msat` of an MPP
8159 // by having a routing node forward more than `amt_to_forward`
8160 // and checking that the receiving node doesn't generate
8161 // a PaymentClaimable event too early
8163 let chanmon_cfgs = create_chanmon_cfgs(node_count);
8164 let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8165 let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8166 let mut nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8168 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8169 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8170 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8171 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8173 let total_msat = 100_000;
8174 let expected_paths: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
8175 let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], total_msat);
8176 let sample_path = route.paths.pop().unwrap();
8178 let mut path_1 = sample_path.clone();
8179 path_1.hops[0].pubkey = nodes[1].node.get_our_node_id();
8180 path_1.hops[0].short_channel_id = chan_1_id;
8181 path_1.hops[1].pubkey = nodes[3].node.get_our_node_id();
8182 path_1.hops[1].short_channel_id = chan_3_id;
8183 path_1.hops[1].fee_msat = 100_000;
8184 route.paths.push(path_1);
8186 let mut path_2 = sample_path.clone();
8187 path_2.hops[0].pubkey = nodes[2].node.get_our_node_id();
8188 path_2.hops[0].short_channel_id = chan_2_id;
8189 path_2.hops[1].pubkey = nodes[3].node.get_our_node_id();
8190 path_2.hops[1].short_channel_id = chan_4_id;
8191 path_2.hops[1].fee_msat = 1_000;
8192 route.paths.push(path_2);
8195 let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
8196 let onion_session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
8197 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8198 nodes[0].node.test_send_payment_internal(&route, our_payment_hash,
8199 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8200 check_added_monitors!(nodes[0], expected_paths.len());
8202 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8203 assert_eq!(events.len(), expected_paths.len());
8206 let ev = remove_first_msg_event_to_node(&expected_paths[0][0].node.get_our_node_id(), &mut events);
8207 let mut payment_event = SendEvent::from_event(ev);
8208 let mut prev_node = &nodes[0];
8210 for (idx, &node) in expected_paths[0].iter().enumerate() {
8211 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
8213 if idx == 0 { // routing node
8214 let session_priv = [3; 32];
8215 let height = nodes[0].best_block_info().1;
8216 let session_priv = SecretKey::from_slice(&session_priv).unwrap();
8217 let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
8218 let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], 100_000,
8219 RecipientOnionFields::secret_only(our_payment_secret), height + 1, &None).unwrap();
8220 // Edit amt_to_forward to simulate the sender having set
8221 // the final amount and the routing node taking less fee
8222 if let msgs::OutboundOnionPayload::Receive {
8223 ref mut sender_intended_htlc_amt_msat, ..
8224 } = onion_payloads[1] {
8225 *sender_intended_htlc_amt_msat = 99_000;
8227 let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
8228 payment_event.msgs[0].onion_routing_packet = new_onion_packet;
8231 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
8232 check_added_monitors!(node, 0);
8233 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
8234 expect_pending_htlcs_forwardable!(node);
8237 let mut events_2 = node.node.get_and_clear_pending_msg_events();
8238 assert_eq!(events_2.len(), 1);
8239 check_added_monitors!(node, 1);
8240 payment_event = SendEvent::from_event(events_2.remove(0));
8241 assert_eq!(payment_event.msgs.len(), 1);
8243 let events_2 = node.node.get_and_clear_pending_events();
8244 assert!(events_2.is_empty());
8251 let ev = remove_first_msg_event_to_node(&expected_paths[1][0].node.get_our_node_id(), &mut events);
8252 pass_along_path(&nodes[0], expected_paths[1], 101_000, our_payment_hash.clone(), Some(our_payment_secret), ev, true, None);
8254 claim_payment_along_route(&nodes[0], expected_paths, false, our_payment_preimage);
8257 fn do_test_overshoot_mpp(msat_amounts: &[u64], total_msat: u64) {
8259 let routing_node_count = msat_amounts.len();
8260 let node_count = routing_node_count + 2;
8262 let chanmon_cfgs = create_chanmon_cfgs(node_count);
8263 let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8264 let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8265 let nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8270 // Create channels for each amount
8271 let mut expected_paths = Vec::with_capacity(routing_node_count);
8272 let mut src_chan_ids = Vec::with_capacity(routing_node_count);
8273 let mut dst_chan_ids = Vec::with_capacity(routing_node_count);
8274 for i in 0..routing_node_count {
8275 let routing_node = 2 + i;
8276 let src_chan_id = create_announced_chan_between_nodes(&nodes, src_idx, routing_node).0.contents.short_channel_id;
8277 src_chan_ids.push(src_chan_id);
8278 let dst_chan_id = create_announced_chan_between_nodes(&nodes, routing_node, dst_idx).0.contents.short_channel_id;
8279 dst_chan_ids.push(dst_chan_id);
8280 let path = vec![&nodes[routing_node], &nodes[dst_idx]];
8281 expected_paths.push(path);
8283 let expected_paths: Vec<&[&Node]> = expected_paths.iter().map(|route| route.as_slice()).collect();
8285 // Create a route for each amount
8286 let example_amount = 100000;
8287 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);
8288 let sample_path = route.paths.pop().unwrap();
8289 for i in 0..routing_node_count {
8290 let routing_node = 2 + i;
8291 let mut path = sample_path.clone();
8292 path.hops[0].pubkey = nodes[routing_node].node.get_our_node_id();
8293 path.hops[0].short_channel_id = src_chan_ids[i];
8294 path.hops[1].pubkey = nodes[dst_idx].node.get_our_node_id();
8295 path.hops[1].short_channel_id = dst_chan_ids[i];
8296 path.hops[1].fee_msat = msat_amounts[i];
8297 route.paths.push(path);
8300 // Send payment with manually set total_msat
8301 let payment_id = PaymentId(nodes[src_idx].keys_manager.backing.get_secure_random_bytes());
8302 let onion_session_privs = nodes[src_idx].node.test_add_new_pending_payment(our_payment_hash,
8303 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8304 nodes[src_idx].node.test_send_payment_internal(&route, our_payment_hash,
8305 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8306 check_added_monitors!(nodes[src_idx], expected_paths.len());
8308 let mut events = nodes[src_idx].node.get_and_clear_pending_msg_events();
8309 assert_eq!(events.len(), expected_paths.len());
8310 let mut amount_received = 0;
8311 for (path_idx, expected_path) in expected_paths.iter().enumerate() {
8312 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
8314 let current_path_amount = msat_amounts[path_idx];
8315 amount_received += current_path_amount;
8316 let became_claimable_now = amount_received >= total_msat && amount_received - current_path_amount < total_msat;
8317 pass_along_path(&nodes[src_idx], expected_path, amount_received, our_payment_hash.clone(), Some(our_payment_secret), ev, became_claimable_now, None);
8320 claim_payment_along_route(&nodes[src_idx], &expected_paths, false, our_payment_preimage);
8324 fn test_overshoot_mpp() {
8325 do_test_overshoot_mpp(&[100_000, 101_000], 200_000);
8326 do_test_overshoot_mpp(&[100_000, 10_000, 100_000], 200_000);
8330 fn test_simple_mpp() {
8331 // Simple test of sending a multi-path payment.
8332 let chanmon_cfgs = create_chanmon_cfgs(4);
8333 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8334 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8335 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8337 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8338 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8339 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8340 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8342 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8343 let path = route.paths[0].clone();
8344 route.paths.push(path);
8345 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
8346 route.paths[0].hops[0].short_channel_id = chan_1_id;
8347 route.paths[0].hops[1].short_channel_id = chan_3_id;
8348 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
8349 route.paths[1].hops[0].short_channel_id = chan_2_id;
8350 route.paths[1].hops[1].short_channel_id = chan_4_id;
8351 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8352 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8356 fn test_preimage_storage() {
8357 // Simple test of payment preimage storage allowing no client-side storage to claim payments
8358 let chanmon_cfgs = create_chanmon_cfgs(2);
8359 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8360 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8361 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8363 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8366 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
8367 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8368 nodes[0].node.send_payment_with_route(&route, payment_hash,
8369 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8370 check_added_monitors!(nodes[0], 1);
8371 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8372 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8373 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8374 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8376 // Note that after leaving the above scope we have no knowledge of any arguments or return
8377 // values from previous calls.
8378 expect_pending_htlcs_forwardable!(nodes[1]);
8379 let events = nodes[1].node.get_and_clear_pending_events();
8380 assert_eq!(events.len(), 1);
8382 Event::PaymentClaimable { ref purpose, .. } => {
8384 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8385 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8387 _ => panic!("expected PaymentPurpose::InvoicePayment")
8390 _ => panic!("Unexpected event"),
8395 fn test_bad_secret_hash() {
8396 // Simple test of unregistered payment hash/invalid payment secret handling
8397 let chanmon_cfgs = create_chanmon_cfgs(2);
8398 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8399 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8400 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8402 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8404 let random_payment_hash = PaymentHash([42; 32]);
8405 let random_payment_secret = PaymentSecret([43; 32]);
8406 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8407 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8409 // All the below cases should end up being handled exactly identically, so we macro the
8410 // resulting events.
8411 macro_rules! handle_unknown_invalid_payment_data {
8412 ($payment_hash: expr) => {
8413 check_added_monitors!(nodes[0], 1);
8414 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8415 let payment_event = SendEvent::from_event(events.pop().unwrap());
8416 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8417 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8419 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8420 // again to process the pending backwards-failure of the HTLC
8421 expect_pending_htlcs_forwardable!(nodes[1]);
8422 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8423 check_added_monitors!(nodes[1], 1);
8425 // We should fail the payment back
8426 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8427 match events.pop().unwrap() {
8428 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8429 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8430 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8432 _ => panic!("Unexpected event"),
8437 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8438 // Error data is the HTLC value (100,000) and current block height
8439 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8441 // Send a payment with the right payment hash but the wrong payment secret
8442 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
8443 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8444 handle_unknown_invalid_payment_data!(our_payment_hash);
8445 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8447 // Send a payment with a random payment hash, but the right payment secret
8448 nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8449 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8450 handle_unknown_invalid_payment_data!(random_payment_hash);
8451 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8453 // Send a payment with a random payment hash and random payment secret
8454 nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8455 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8456 handle_unknown_invalid_payment_data!(random_payment_hash);
8457 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8461 fn test_update_err_monitor_lockdown() {
8462 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8463 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8464 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8467 // This scenario may happen in a watchtower setup, where watchtower process a block height
8468 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8469 // commitment at same time.
8471 let chanmon_cfgs = create_chanmon_cfgs(2);
8472 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8473 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8474 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8476 // Create some initial channel
8477 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8478 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8480 // Rebalance the network to generate htlc in the two directions
8481 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8483 // Route a HTLC from node 0 to node 1 (but don't settle)
8484 let (preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8486 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8487 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8488 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8489 let persister = test_utils::TestPersister::new();
8492 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8493 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8494 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8495 assert!(new_monitor == *monitor);
8498 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);
8499 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), Ok(ChannelMonitorUpdateStatus::Completed));
8502 let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8503 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8504 // transaction lock time requirements here.
8505 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 200));
8506 watchtower.chain_monitor.block_connected(&block, 200);
8508 // Try to update ChannelMonitor
8509 nodes[1].node.claim_funds(preimage);
8510 check_added_monitors!(nodes[1], 1);
8511 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8513 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8514 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8515 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8517 let mut node_0_per_peer_lock;
8518 let mut node_0_peer_state_lock;
8519 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) {
8520 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8521 assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::InProgress);
8522 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8523 } else { assert!(false); }
8528 // Our local monitor is in-sync and hasn't processed yet timeout
8529 check_added_monitors!(nodes[0], 1);
8530 let events = nodes[0].node.get_and_clear_pending_events();
8531 assert_eq!(events.len(), 1);
8535 fn test_concurrent_monitor_claim() {
8536 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8537 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8538 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8539 // state N+1 confirms. Alice claims output from state N+1.
8541 let chanmon_cfgs = create_chanmon_cfgs(2);
8542 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8543 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8544 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8546 // Create some initial channel
8547 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8548 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8550 // Rebalance the network to generate htlc in the two directions
8551 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8553 // Route a HTLC from node 0 to node 1 (but don't settle)
8554 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8556 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8557 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8558 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8559 let persister = test_utils::TestPersister::new();
8560 let alice_broadcaster = test_utils::TestBroadcaster::with_blocks(
8561 Arc::new(Mutex::new(nodes[0].blocks.lock().unwrap().clone())),
8563 let watchtower_alice = {
8565 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8566 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8567 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8568 assert!(new_monitor == *monitor);
8571 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &alice_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8572 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), Ok(ChannelMonitorUpdateStatus::Completed));
8575 let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8576 // Make Alice aware of enough blocks that it doesn't think we're violating transaction lock time
8577 // requirements here.
8578 const HTLC_TIMEOUT_BROADCAST: u32 = CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS;
8579 alice_broadcaster.blocks.lock().unwrap().resize((HTLC_TIMEOUT_BROADCAST) as usize, (block.clone(), HTLC_TIMEOUT_BROADCAST));
8580 watchtower_alice.chain_monitor.block_connected(&block, HTLC_TIMEOUT_BROADCAST);
8582 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8584 let mut txn = alice_broadcaster.txn_broadcast();
8585 assert_eq!(txn.len(), 2);
8586 check_spends!(txn[0], chan_1.3);
8587 check_spends!(txn[1], txn[0]);
8590 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8591 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8592 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8593 let persister = test_utils::TestPersister::new();
8594 let bob_broadcaster = test_utils::TestBroadcaster::with_blocks(Arc::clone(&alice_broadcaster.blocks));
8595 let watchtower_bob = {
8597 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8598 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8599 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8600 assert!(new_monitor == *monitor);
8603 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &bob_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8604 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), Ok(ChannelMonitorUpdateStatus::Completed));
8607 watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST - 1);
8609 // Route another payment to generate another update with still previous HTLC pending
8610 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8611 nodes[1].node.send_payment_with_route(&route, payment_hash,
8612 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8613 check_added_monitors!(nodes[1], 1);
8615 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8616 assert_eq!(updates.update_add_htlcs.len(), 1);
8617 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8619 let mut node_0_per_peer_lock;
8620 let mut node_0_peer_state_lock;
8621 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) {
8622 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8623 // Watchtower Alice should already have seen the block and reject the update
8624 assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::InProgress);
8625 assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8626 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8627 } else { assert!(false); }
8632 // Our local monitor is in-sync and hasn't processed yet timeout
8633 check_added_monitors!(nodes[0], 1);
8635 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8636 watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST);
8638 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8641 let mut txn = bob_broadcaster.txn_broadcast();
8642 assert_eq!(txn.len(), 2);
8643 bob_state_y = txn.remove(0);
8646 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8647 let height = HTLC_TIMEOUT_BROADCAST + 1;
8648 connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
8649 check_closed_broadcast(&nodes[0], 1, true);
8650 check_closed_event!(&nodes[0], 1, ClosureReason::HolderForceClosed, false,
8651 [nodes[1].node.get_our_node_id()], 100000);
8652 watchtower_alice.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, vec![bob_state_y.clone()]), height);
8653 check_added_monitors(&nodes[0], 1);
8655 let htlc_txn = alice_broadcaster.txn_broadcast();
8656 assert_eq!(htlc_txn.len(), 1);
8657 check_spends!(htlc_txn[0], bob_state_y);
8662 fn test_pre_lockin_no_chan_closed_update() {
8663 // Test that if a peer closes a channel in response to a funding_created message we don't
8664 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8667 // Doing so would imply a channel monitor update before the initial channel monitor
8668 // registration, violating our API guarantees.
8670 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8671 // then opening a second channel with the same funding output as the first (which is not
8672 // rejected because the first channel does not exist in the ChannelManager) and closing it
8673 // before receiving funding_signed.
8674 let chanmon_cfgs = create_chanmon_cfgs(2);
8675 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8676 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8677 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8679 // Create an initial channel
8680 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
8681 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8682 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8683 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8684 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8686 // Move the first channel through the funding flow...
8687 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8689 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8690 check_added_monitors!(nodes[0], 0);
8692 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8693 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 });
8694 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8695 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8696 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("Hi".to_string()) }, true,
8697 [nodes[1].node.get_our_node_id()], 100000);
8701 fn test_htlc_no_detection() {
8702 // This test is a mutation to underscore the detection logic bug we had
8703 // before #653. HTLC value routed is above the remaining balance, thus
8704 // inverting HTLC and `to_remote` output. HTLC will come second and
8705 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8706 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8707 // outputs order detection for correct spending children filtring.
8709 let chanmon_cfgs = create_chanmon_cfgs(2);
8710 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8711 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8712 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8714 // Create some initial channels
8715 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8717 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8718 let (_, our_payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8719 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8720 assert_eq!(local_txn[0].input.len(), 1);
8721 assert_eq!(local_txn[0].output.len(), 3);
8722 check_spends!(local_txn[0], chan_1.3);
8724 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8725 let block = create_dummy_block(nodes[0].best_block_hash(), 42, vec![local_txn[0].clone()]);
8726 connect_block(&nodes[0], &block);
8727 // We deliberately connect the local tx twice as this should provoke a failure calling
8728 // this test before #653 fix.
8729 chain::Listen::block_connected(&nodes[0].chain_monitor.chain_monitor, &block, nodes[0].best_block_info().1 + 1);
8730 check_closed_broadcast!(nodes[0], true);
8731 check_added_monitors!(nodes[0], 1);
8732 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
8733 connect_blocks(&nodes[0], TEST_FINAL_CLTV);
8735 let htlc_timeout = {
8736 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8737 assert_eq!(node_txn.len(), 1);
8738 assert_eq!(node_txn[0].input.len(), 1);
8739 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8740 check_spends!(node_txn[0], local_txn[0]);
8744 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![htlc_timeout.clone()]));
8745 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8746 expect_payment_failed!(nodes[0], our_payment_hash, false);
8749 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8750 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8751 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8752 // Carol, Alice would be the upstream node, and Carol the downstream.)
8754 // Steps of the test:
8755 // 1) Alice sends a HTLC to Carol through Bob.
8756 // 2) Carol doesn't settle the HTLC.
8757 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8758 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8759 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8760 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8761 // 5) Carol release the preimage to Bob off-chain.
8762 // 6) Bob claims the offered output on the broadcasted commitment.
8763 let chanmon_cfgs = create_chanmon_cfgs(3);
8764 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8765 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8766 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8768 // Create some initial channels
8769 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8770 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8772 // Steps (1) and (2):
8773 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8774 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8776 // Check that Alice's commitment transaction now contains an output for this HTLC.
8777 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8778 check_spends!(alice_txn[0], chan_ab.3);
8779 assert_eq!(alice_txn[0].output.len(), 2);
8780 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8781 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8782 assert_eq!(alice_txn.len(), 2);
8784 // Steps (3) and (4):
8785 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8786 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8787 let mut force_closing_node = 0; // Alice force-closes
8788 let mut counterparty_node = 1; // Bob if Alice force-closes
8791 if !broadcast_alice {
8792 force_closing_node = 1;
8793 counterparty_node = 0;
8795 nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8796 check_closed_broadcast!(nodes[force_closing_node], true);
8797 check_added_monitors!(nodes[force_closing_node], 1);
8798 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed, [nodes[counterparty_node].node.get_our_node_id()], 100000);
8799 if go_onchain_before_fulfill {
8800 let txn_to_broadcast = match broadcast_alice {
8801 true => alice_txn.clone(),
8802 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8804 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8805 if broadcast_alice {
8806 check_closed_broadcast!(nodes[1], true);
8807 check_added_monitors!(nodes[1], 1);
8808 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
8813 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8814 // process of removing the HTLC from their commitment transactions.
8815 nodes[2].node.claim_funds(payment_preimage);
8816 check_added_monitors!(nodes[2], 1);
8817 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8819 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8820 assert!(carol_updates.update_add_htlcs.is_empty());
8821 assert!(carol_updates.update_fail_htlcs.is_empty());
8822 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8823 assert!(carol_updates.update_fee.is_none());
8824 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8826 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8827 let went_onchain = go_onchain_before_fulfill || force_closing_node == 1;
8828 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if went_onchain { None } else { Some(1000) }, went_onchain, false);
8829 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8830 if !go_onchain_before_fulfill && broadcast_alice {
8831 let events = nodes[1].node.get_and_clear_pending_msg_events();
8832 assert_eq!(events.len(), 1);
8834 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8835 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8837 _ => panic!("Unexpected event"),
8840 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8841 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8842 // Carol<->Bob's updated commitment transaction info.
8843 check_added_monitors!(nodes[1], 2);
8845 let events = nodes[1].node.get_and_clear_pending_msg_events();
8846 assert_eq!(events.len(), 2);
8847 let bob_revocation = match events[0] {
8848 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8849 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8852 _ => panic!("Unexpected event"),
8854 let bob_updates = match events[1] {
8855 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8856 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8859 _ => panic!("Unexpected event"),
8862 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8863 check_added_monitors!(nodes[2], 1);
8864 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8865 check_added_monitors!(nodes[2], 1);
8867 let events = nodes[2].node.get_and_clear_pending_msg_events();
8868 assert_eq!(events.len(), 1);
8869 let carol_revocation = match events[0] {
8870 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8871 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8874 _ => panic!("Unexpected event"),
8876 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8877 check_added_monitors!(nodes[1], 1);
8879 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8880 // here's where we put said channel's commitment tx on-chain.
8881 let mut txn_to_broadcast = alice_txn.clone();
8882 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8883 if !go_onchain_before_fulfill {
8884 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8885 // If Bob was the one to force-close, he will have already passed these checks earlier.
8886 if broadcast_alice {
8887 check_closed_broadcast!(nodes[1], true);
8888 check_added_monitors!(nodes[1], 1);
8889 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
8891 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8892 if broadcast_alice {
8893 assert_eq!(bob_txn.len(), 1);
8894 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8896 if nodes[1].connect_style.borrow().updates_best_block_first() {
8897 assert_eq!(bob_txn.len(), 3);
8898 assert_eq!(bob_txn[0].txid(), bob_txn[1].txid());
8900 assert_eq!(bob_txn.len(), 2);
8902 check_spends!(bob_txn[0], chan_ab.3);
8907 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8908 // broadcasted commitment transaction.
8910 let script_weight = match broadcast_alice {
8911 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8912 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8914 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8915 // Bob force-closed and broadcasts the commitment transaction along with a
8916 // HTLC-output-claiming transaction.
8917 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8918 if broadcast_alice {
8919 assert_eq!(bob_txn.len(), 1);
8920 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8921 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8923 assert_eq!(bob_txn.len(), if nodes[1].connect_style.borrow().updates_best_block_first() { 3 } else { 2 });
8924 let htlc_tx = bob_txn.pop().unwrap();
8925 check_spends!(htlc_tx, txn_to_broadcast[0]);
8926 assert_eq!(htlc_tx.input[0].witness.last().unwrap().len(), script_weight);
8932 fn test_onchain_htlc_settlement_after_close() {
8933 do_test_onchain_htlc_settlement_after_close(true, true);
8934 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8935 do_test_onchain_htlc_settlement_after_close(true, false);
8936 do_test_onchain_htlc_settlement_after_close(false, false);
8940 fn test_duplicate_temporary_channel_id_from_different_peers() {
8941 // Tests that we can accept two different `OpenChannel` requests with the same
8942 // `temporary_channel_id`, as long as they are from different peers.
8943 let chanmon_cfgs = create_chanmon_cfgs(3);
8944 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8945 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8946 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8948 // Create an first channel channel
8949 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
8950 let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8952 // Create an second channel
8953 nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None, None).unwrap();
8954 let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8956 // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8957 // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8958 open_chan_msg_chan_2_0.temporary_channel_id = open_chan_msg_chan_1_0.temporary_channel_id;
8960 // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8961 // `temporary_channel_id` as they are from different peers.
8962 nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
8964 let events = nodes[0].node.get_and_clear_pending_msg_events();
8965 assert_eq!(events.len(), 1);
8967 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8968 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8969 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8971 _ => panic!("Unexpected event"),
8975 nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
8977 let events = nodes[0].node.get_and_clear_pending_msg_events();
8978 assert_eq!(events.len(), 1);
8980 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8981 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
8982 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8984 _ => panic!("Unexpected event"),
8990 fn test_peer_funding_sidechannel() {
8991 // Test that if a peer somehow learns which txid we'll use for our channel funding before we
8992 // receive `funding_transaction_generated` the peer cannot cause us to crash. We'd previously
8993 // assumed that LDK would receive `funding_transaction_generated` prior to our peer learning
8994 // the txid and panicked if the peer tried to open a redundant channel to us with the same
8995 // funding outpoint.
8997 // While this assumption is generally safe, some users may have out-of-band protocols where
8998 // they notify their LSP about a funding outpoint first, or this may be violated in the future
8999 // with collaborative transaction construction protocols, i.e. dual-funding.
9000 let chanmon_cfgs = create_chanmon_cfgs(3);
9001 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9002 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9003 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9005 let temp_chan_id_ab = exchange_open_accept_chan(&nodes[0], &nodes[1], 1_000_000, 0);
9006 let temp_chan_id_ca = exchange_open_accept_chan(&nodes[2], &nodes[0], 1_000_000, 0);
9008 let (_, tx, funding_output) =
9009 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9011 let cs_funding_events = nodes[2].node.get_and_clear_pending_events();
9012 assert_eq!(cs_funding_events.len(), 1);
9013 match cs_funding_events[0] {
9014 Event::FundingGenerationReady { .. } => {}
9015 _ => panic!("Unexpected event {:?}", cs_funding_events),
9018 nodes[2].node.funding_transaction_generated_unchecked(&temp_chan_id_ca, &nodes[0].node.get_our_node_id(), tx.clone(), funding_output.index).unwrap();
9019 let funding_created_msg = get_event_msg!(nodes[2], MessageSendEvent::SendFundingCreated, nodes[0].node.get_our_node_id());
9020 nodes[0].node.handle_funding_created(&nodes[2].node.get_our_node_id(), &funding_created_msg);
9021 get_event_msg!(nodes[0], MessageSendEvent::SendFundingSigned, nodes[2].node.get_our_node_id());
9022 expect_channel_pending_event(&nodes[0], &nodes[2].node.get_our_node_id());
9023 check_added_monitors!(nodes[0], 1);
9025 let res = nodes[0].node.funding_transaction_generated(&temp_chan_id_ab, &nodes[1].node.get_our_node_id(), tx.clone());
9026 let err_msg = format!("{:?}", res.unwrap_err());
9027 assert!(err_msg.contains("An existing channel using outpoint "));
9028 assert!(err_msg.contains(" is open with peer"));
9029 // Even though the last funding_transaction_generated errored, it still generated a
9030 // SendFundingCreated. However, when the peer responds with a funding_signed it will send the
9031 // appropriate error message.
9032 let as_funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9033 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &as_funding_created);
9034 check_added_monitors!(nodes[1], 1);
9035 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9036 let reason = ClosureReason::ProcessingError { err: format!("An existing channel using outpoint {} is open with peer {}", funding_output, nodes[2].node.get_our_node_id()), };
9037 check_closed_events(&nodes[0], &[ExpectedCloseEvent::from_id_reason(ChannelId::v1_from_funding_outpoint(funding_output), true, reason)]);
9039 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9040 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
9041 get_err_msg(&nodes[0], &nodes[1].node.get_our_node_id());
9045 fn test_duplicate_conflicting_funding_from_second_peer() {
9046 // Test that if a user tries to fund a channel with a funding outpoint they'd previously used
9047 // we don't try to remove the previous ChannelMonitor. This is largely a test to ensure we
9048 // don't regress in the fuzzer, as such funding getting passed our outpoint-matches checks
9049 // implies the user (and our counterparty) has reused cryptographic keys across channels, which
9050 // we require the user not do.
9051 let chanmon_cfgs = create_chanmon_cfgs(4);
9052 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9053 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9054 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9056 let temp_chan_id = exchange_open_accept_chan(&nodes[0], &nodes[1], 1_000_000, 0);
9058 let (_, tx, funding_output) =
9059 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9061 // Now that we have a funding outpoint, create a dummy `ChannelMonitor` and insert it into
9062 // nodes[0]'s ChainMonitor so that the initial `ChannelMonitor` write fails.
9063 let dummy_chan_id = create_chan_between_nodes(&nodes[2], &nodes[3]).3;
9064 let dummy_monitor = get_monitor!(nodes[2], dummy_chan_id).clone();
9065 nodes[0].chain_monitor.chain_monitor.watch_channel(funding_output, dummy_monitor).unwrap();
9067 nodes[0].node.funding_transaction_generated(&temp_chan_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9069 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9070 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9071 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9072 check_added_monitors!(nodes[1], 1);
9073 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9075 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9076 // At this point, the channel should be closed, after having generated one monitor write (the
9077 // watch_channel call which failed), but zero monitor updates.
9078 check_added_monitors!(nodes[0], 1);
9079 get_err_msg(&nodes[0], &nodes[1].node.get_our_node_id());
9080 let err_reason = ClosureReason::ProcessingError { err: "Channel funding outpoint was a duplicate".to_owned() };
9081 check_closed_events(&nodes[0], &[ExpectedCloseEvent::from_id_reason(funding_signed_msg.channel_id, true, err_reason)]);
9085 fn test_duplicate_funding_err_in_funding() {
9086 // Test that if we have a live channel with one peer, then another peer comes along and tries
9087 // to create a second channel with the same txid we'll fail and not overwrite the
9088 // outpoint_to_peer map in `ChannelManager`.
9090 // This was previously broken.
9091 let chanmon_cfgs = create_chanmon_cfgs(3);
9092 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9093 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9094 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9096 let (_, _, _, real_channel_id, funding_tx) = create_chan_between_nodes(&nodes[0], &nodes[1]);
9097 let real_chan_funding_txo = chain::transaction::OutPoint { txid: funding_tx.txid(), index: 0 };
9098 assert_eq!(ChannelId::v1_from_funding_outpoint(real_chan_funding_txo), real_channel_id);
9100 nodes[2].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
9101 let mut open_chan_msg = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9102 let node_c_temp_chan_id = open_chan_msg.temporary_channel_id;
9103 open_chan_msg.temporary_channel_id = real_channel_id;
9104 nodes[1].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg);
9105 let mut accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[2].node.get_our_node_id());
9106 accept_chan_msg.temporary_channel_id = node_c_temp_chan_id;
9107 nodes[2].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
9109 // Now that we have a second channel with the same funding txo, send a bogus funding message
9110 // and let nodes[1] remove the inbound channel.
9111 let (_, funding_tx, _) = create_funding_transaction(&nodes[2], &nodes[1].node.get_our_node_id(), 100_000, 42);
9113 nodes[2].node.funding_transaction_generated(&node_c_temp_chan_id, &nodes[1].node.get_our_node_id(), funding_tx).unwrap();
9115 let mut funding_created_msg = get_event_msg!(nodes[2], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9116 funding_created_msg.temporary_channel_id = real_channel_id;
9117 // Make the signature invalid by changing the funding output
9118 funding_created_msg.funding_output_index += 10;
9119 nodes[1].node.handle_funding_created(&nodes[2].node.get_our_node_id(), &funding_created_msg);
9120 get_err_msg(&nodes[1], &nodes[2].node.get_our_node_id());
9121 let err = "Invalid funding_created signature from peer".to_owned();
9122 let reason = ClosureReason::ProcessingError { err };
9123 let expected_closing = ExpectedCloseEvent::from_id_reason(real_channel_id, false, reason);
9124 check_closed_events(&nodes[1], &[expected_closing]);
9127 *nodes[1].node.outpoint_to_peer.lock().unwrap().get(&real_chan_funding_txo).unwrap(),
9128 nodes[0].node.get_our_node_id()
9133 fn test_duplicate_chan_id() {
9134 // Test that if a given peer tries to open a channel with the same channel_id as one that is
9135 // already open we reject it and keep the old channel.
9137 // Previously, full_stack_target managed to figure out that if you tried to open two channels
9138 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
9139 // the existing channel when we detect the duplicate new channel, screwing up our monitor
9140 // updating logic for the existing channel.
9141 let chanmon_cfgs = create_chanmon_cfgs(2);
9142 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9143 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9144 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9146 // Create an initial channel
9147 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
9148 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9149 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
9150 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()));
9152 // Try to create a second channel with the same temporary_channel_id as the first and check
9153 // that it is rejected.
9154 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
9156 let events = nodes[1].node.get_and_clear_pending_msg_events();
9157 assert_eq!(events.len(), 1);
9159 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9160 // Technically, at this point, nodes[1] would be justified in thinking both the
9161 // first (valid) and second (invalid) channels are closed, given they both have
9162 // the same non-temporary channel_id. However, currently we do not, so we just
9163 // move forward with it.
9164 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9165 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9167 _ => panic!("Unexpected event"),
9171 // Move the first channel through the funding flow...
9172 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9174 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9175 check_added_monitors!(nodes[0], 0);
9177 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9178 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9180 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9181 assert_eq!(added_monitors.len(), 1);
9182 assert_eq!(added_monitors[0].0, funding_output);
9183 added_monitors.clear();
9185 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9187 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9189 let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
9190 let channel_id = ChannelId::v1_from_funding_outpoint(funding_outpoint);
9192 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
9195 // First try to open a second channel with a temporary channel id equal to the txid-based one.
9196 // Technically this is allowed by the spec, but we don't support it and there's little reason
9197 // to. Still, it shouldn't cause any other issues.
9198 open_chan_msg.temporary_channel_id = channel_id;
9199 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
9201 let events = nodes[1].node.get_and_clear_pending_msg_events();
9202 assert_eq!(events.len(), 1);
9204 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9205 // Technically, at this point, nodes[1] would be justified in thinking both
9206 // channels are closed, but currently we do not, so we just move forward with it.
9207 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9208 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9210 _ => panic!("Unexpected event"),
9214 // Now try to create a second channel which has a duplicate funding output.
9215 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
9216 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9217 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
9218 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()));
9219 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
9221 let funding_created = {
9222 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9223 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9224 // Once we call `get_funding_created` the channel has a duplicate channel_id as
9225 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
9226 // try to create another channel. Instead, we drop the channel entirely here (leaving the
9227 // channelmanager in a possibly nonsense state instead).
9228 match a_peer_state.channel_by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap() {
9229 ChannelPhase::UnfundedOutboundV1(mut chan) => {
9230 let logger = test_utils::TestLogger::new();
9231 chan.get_funding_created(tx.clone(), funding_outpoint, false, &&logger).map_err(|_| ()).unwrap()
9233 _ => panic!("Unexpected ChannelPhase variant"),
9236 check_added_monitors!(nodes[0], 0);
9237 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9238 // At this point we'll look up if the channel_id is present and immediately fail the channel
9239 // without trying to persist the `ChannelMonitor`.
9240 check_added_monitors!(nodes[1], 0);
9242 check_closed_events(&nodes[1], &[
9243 ExpectedCloseEvent::from_id_reason(funding_created.temporary_channel_id, false, ClosureReason::ProcessingError {
9244 err: "Already had channel with the new channel_id".to_owned()
9248 // ...still, nodes[1] will reject the duplicate channel.
9250 let events = nodes[1].node.get_and_clear_pending_msg_events();
9251 assert_eq!(events.len(), 1);
9253 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9254 // Technically, at this point, nodes[1] would be justified in thinking both
9255 // channels are closed, but currently we do not, so we just move forward with it.
9256 assert_eq!(msg.channel_id, channel_id);
9257 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9259 _ => panic!("Unexpected event"),
9263 // finally, finish creating the original channel and send a payment over it to make sure
9264 // everything is functional.
9265 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9267 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9268 assert_eq!(added_monitors.len(), 1);
9269 assert_eq!(added_monitors[0].0, funding_output);
9270 added_monitors.clear();
9272 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9274 let events_4 = nodes[0].node.get_and_clear_pending_events();
9275 assert_eq!(events_4.len(), 0);
9276 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9277 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9279 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9280 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9281 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9283 send_payment(&nodes[0], &[&nodes[1]], 8000000);
9287 fn test_error_chans_closed() {
9288 // Test that we properly handle error messages, closing appropriate channels.
9290 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9291 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9292 // we can test various edge cases around it to ensure we don't regress.
9293 let chanmon_cfgs = create_chanmon_cfgs(3);
9294 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9295 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9296 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9298 // Create some initial channels
9299 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9300 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9301 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
9303 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9304 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9305 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9307 // Closing a channel from a different peer has no effect
9308 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9309 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9311 // Closing one channel doesn't impact others
9312 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9313 check_added_monitors!(nodes[0], 1);
9314 check_closed_broadcast!(nodes[0], false);
9315 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) },
9316 [nodes[1].node.get_our_node_id()], 100000);
9317 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9318 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9319 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);
9320 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);
9322 // A null channel ID should close all channels
9323 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9324 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: ChannelId::new_zero(), data: "ERR".to_owned() });
9325 check_added_monitors!(nodes[0], 2);
9326 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) },
9327 [nodes[1].node.get_our_node_id(); 2], 100000);
9328 let events = nodes[0].node.get_and_clear_pending_msg_events();
9329 assert_eq!(events.len(), 2);
9331 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9332 assert_eq!(msg.contents.flags & 2, 2);
9334 _ => panic!("Unexpected event"),
9337 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9338 assert_eq!(msg.contents.flags & 2, 2);
9340 _ => panic!("Unexpected event"),
9342 // Note that at this point users of a standard PeerHandler will end up calling
9343 // peer_disconnected.
9344 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9345 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9347 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9348 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9349 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9353 fn test_invalid_funding_tx() {
9354 // Test that we properly handle invalid funding transactions sent to us from a peer.
9356 // Previously, all other major lightning implementations had failed to properly sanitize
9357 // funding transactions from their counterparties, leading to a multi-implementation critical
9358 // security vulnerability (though we always sanitized properly, we've previously had
9359 // un-released crashes in the sanitization process).
9361 // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9362 // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9363 // gave up on it. We test this here by generating such a transaction.
9364 let chanmon_cfgs = create_chanmon_cfgs(2);
9365 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9366 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9367 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9369 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None, None).unwrap();
9370 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()));
9371 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()));
9373 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9375 // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9376 // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9377 // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9379 let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9380 let wit_program_script: ScriptBuf = wit_program.into();
9381 for output in tx.output.iter_mut() {
9382 // Make the confirmed funding transaction have a bogus script_pubkey
9383 output.script_pubkey = ScriptBuf::new_v0_p2wsh(&wit_program_script.wscript_hash());
9386 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9387 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()));
9388 check_added_monitors!(nodes[1], 1);
9389 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9391 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()));
9392 check_added_monitors!(nodes[0], 1);
9393 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9395 let events_1 = nodes[0].node.get_and_clear_pending_events();
9396 assert_eq!(events_1.len(), 0);
9398 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9399 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9400 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9402 let expected_err = "funding tx had wrong script/value or output index";
9403 confirm_transaction_at(&nodes[1], &tx, 1);
9404 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() },
9405 [nodes[0].node.get_our_node_id()], 100000);
9406 check_added_monitors!(nodes[1], 1);
9407 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9408 assert_eq!(events_2.len(), 1);
9409 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9410 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9411 if let msgs::ErrorAction::DisconnectPeer { msg } = action {
9412 assert_eq!(msg.as_ref().unwrap().data, "Channel closed because of an exception: ".to_owned() + expected_err);
9413 } else { panic!(); }
9414 } else { panic!(); }
9415 assert_eq!(nodes[1].node.list_channels().len(), 0);
9417 // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9418 // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9419 // as its not 32 bytes long.
9420 let mut spend_tx = Transaction {
9421 version: 2i32, lock_time: LockTime::ZERO,
9422 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9423 previous_output: BitcoinOutPoint {
9427 script_sig: ScriptBuf::new(),
9428 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9429 witness: Witness::from_slice(&channelmonitor::deliberately_bogus_accepted_htlc_witness())
9431 output: vec![TxOut {
9433 script_pubkey: ScriptBuf::new(),
9436 check_spends!(spend_tx, tx);
9437 mine_transaction(&nodes[1], &spend_tx);
9441 fn test_coinbase_funding_tx() {
9442 // Miners are able to fund channels directly from coinbase transactions, however
9443 // by consensus rules, outputs of a coinbase transaction are encumbered by a 100
9444 // block maturity timelock. To ensure that a (non-0conf) channel like this is enforceable
9445 // on-chain, the minimum depth is updated to 100 blocks for coinbase funding transactions.
9447 // Note that 0conf channels with coinbase funding transactions are unaffected and are
9448 // immediately operational after opening.
9449 let chanmon_cfgs = create_chanmon_cfgs(2);
9450 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9451 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9452 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9454 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
9455 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9457 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9458 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9460 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9462 // Create the coinbase funding transaction.
9463 let (temporary_channel_id, tx, _) = create_coinbase_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9465 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9466 check_added_monitors!(nodes[0], 0);
9467 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9469 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9470 check_added_monitors!(nodes[1], 1);
9471 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9473 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9475 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
9476 check_added_monitors!(nodes[0], 1);
9478 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9479 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
9481 // Starting at height 0, we "confirm" the coinbase at height 1.
9482 confirm_transaction_at(&nodes[0], &tx, 1);
9483 // We connect 98 more blocks to have 99 confirmations for the coinbase transaction.
9484 connect_blocks(&nodes[0], COINBASE_MATURITY - 2);
9485 // Check that we have no pending message events (we have not queued a `channel_ready` yet).
9486 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
9487 // Now connect one more block which results in 100 confirmations of the coinbase transaction.
9488 connect_blocks(&nodes[0], 1);
9489 // There should now be a `channel_ready` which can be handled.
9490 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()));
9492 confirm_transaction_at(&nodes[1], &tx, 1);
9493 connect_blocks(&nodes[1], COINBASE_MATURITY - 2);
9494 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9495 connect_blocks(&nodes[1], 1);
9496 expect_channel_ready_event(&nodes[1], &nodes[0].node.get_our_node_id());
9497 create_chan_between_nodes_with_value_confirm_second(&nodes[0], &nodes[1]);
9500 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9501 // In the first version of the chain::Confirm interface, after a refactor was made to not
9502 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9503 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9504 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9505 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9506 // spending transaction until height N+1 (or greater). This was due to the way
9507 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9508 // spending transaction at the height the input transaction was confirmed at, not whether we
9509 // should broadcast a spending transaction at the current height.
9510 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9511 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9512 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9513 // until we learned about an additional block.
9515 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9516 // aren't broadcasting transactions too early (ie not broadcasting them at all).
9517 let chanmon_cfgs = create_chanmon_cfgs(3);
9518 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9519 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9520 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9521 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9523 create_announced_chan_between_nodes(&nodes, 0, 1);
9524 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
9525 let (_, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9526 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
9527 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9529 nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9530 check_closed_broadcast!(nodes[1], true);
9531 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[2].node.get_our_node_id()], 100000);
9532 check_added_monitors!(nodes[1], 1);
9533 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9534 assert_eq!(node_txn.len(), 1);
9536 let conf_height = nodes[1].best_block_info().1;
9537 if !test_height_before_timelock {
9538 connect_blocks(&nodes[1], 24 * 6);
9540 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9541 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9542 if test_height_before_timelock {
9543 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9544 // generate any events or broadcast any transactions
9545 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9546 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9548 // We should broadcast an HTLC transaction spending our funding transaction first
9549 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9550 assert_eq!(spending_txn.len(), 2);
9551 let htlc_tx = if spending_txn[0].txid() == node_txn[0].txid() {
9556 check_spends!(htlc_tx, node_txn[0]);
9557 // We should also generate a SpendableOutputs event with the to_self output (as its
9559 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9560 assert_eq!(descriptor_spend_txn.len(), 1);
9562 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9563 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9564 // additional block built on top of the current chain.
9565 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9566 &nodes[1].get_block_header(conf_height + 1), &[(0, htlc_tx)], conf_height + 1);
9567 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 }]);
9568 check_added_monitors!(nodes[1], 1);
9570 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9571 assert!(updates.update_add_htlcs.is_empty());
9572 assert!(updates.update_fulfill_htlcs.is_empty());
9573 assert_eq!(updates.update_fail_htlcs.len(), 1);
9574 assert!(updates.update_fail_malformed_htlcs.is_empty());
9575 assert!(updates.update_fee.is_none());
9576 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9577 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9578 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9583 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9584 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9585 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9588 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9589 let chanmon_cfgs = create_chanmon_cfgs(2);
9590 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9591 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9592 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9594 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9596 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9597 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
9598 let route = get_route!(nodes[0], payment_params, 10_000).unwrap();
9600 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9603 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9604 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9605 check_added_monitors!(nodes[0], 1);
9606 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9607 assert_eq!(events.len(), 1);
9608 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9609 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9610 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9612 expect_pending_htlcs_forwardable!(nodes[1]);
9613 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9616 // Note that we use a different PaymentId here to allow us to duplicativly pay
9617 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9618 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9619 check_added_monitors!(nodes[0], 1);
9620 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9621 assert_eq!(events.len(), 1);
9622 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9623 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9624 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9625 // At this point, nodes[1] would notice it has too much value for the payment. It will
9626 // assume the second is a privacy attack (no longer particularly relevant
9627 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9628 // the first HTLC delivered above.
9631 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9632 nodes[1].node.process_pending_htlc_forwards();
9634 if test_for_second_fail_panic {
9635 // Now we go fail back the first HTLC from the user end.
9636 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9638 let expected_destinations = vec![
9639 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9640 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9642 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], expected_destinations);
9643 nodes[1].node.process_pending_htlc_forwards();
9645 check_added_monitors!(nodes[1], 1);
9646 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9647 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9649 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9650 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9651 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9653 let failure_events = nodes[0].node.get_and_clear_pending_events();
9654 assert_eq!(failure_events.len(), 4);
9655 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9656 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9657 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9658 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9660 // Let the second HTLC fail and claim the first
9661 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9662 nodes[1].node.process_pending_htlc_forwards();
9664 check_added_monitors!(nodes[1], 1);
9665 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9666 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9667 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9669 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9671 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9676 fn test_dup_htlc_second_fail_panic() {
9677 // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9678 // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9679 // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9680 // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9681 do_test_dup_htlc_second_rejected(true);
9685 fn test_dup_htlc_second_rejected() {
9686 // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9687 // simply reject the second HTLC but are still able to claim the first HTLC.
9688 do_test_dup_htlc_second_rejected(false);
9692 fn test_inconsistent_mpp_params() {
9693 // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9694 // such HTLC and allow the second to stay.
9695 let chanmon_cfgs = create_chanmon_cfgs(4);
9696 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9697 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9698 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9700 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9701 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9702 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9703 let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9705 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9706 .with_bolt11_features(nodes[3].node.bolt11_invoice_features()).unwrap();
9707 let mut route = get_route!(nodes[0], payment_params, 15_000_000).unwrap();
9708 assert_eq!(route.paths.len(), 2);
9709 route.paths.sort_by(|path_a, _| {
9710 // Sort the path so that the path through nodes[1] comes first
9711 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9712 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9715 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9717 let cur_height = nodes[0].best_block_info().1;
9718 let payment_id = PaymentId([42; 32]);
9720 let session_privs = {
9721 // We create a fake route here so that we start with three pending HTLCs, which we'll
9722 // ultimately have, just not right away.
9723 let mut dup_route = route.clone();
9724 dup_route.paths.push(route.paths[1].clone());
9725 nodes[0].node.test_add_new_pending_payment(our_payment_hash,
9726 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &dup_route).unwrap()
9728 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
9729 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9730 &None, session_privs[0]).unwrap();
9731 check_added_monitors!(nodes[0], 1);
9734 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9735 assert_eq!(events.len(), 1);
9736 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9738 assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9740 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9741 RecipientOnionFields::secret_only(our_payment_secret), 14_000_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9742 check_added_monitors!(nodes[0], 1);
9745 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9746 assert_eq!(events.len(), 1);
9747 let payment_event = SendEvent::from_event(events.pop().unwrap());
9749 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9750 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9752 expect_pending_htlcs_forwardable!(nodes[2]);
9753 check_added_monitors!(nodes[2], 1);
9755 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9756 assert_eq!(events.len(), 1);
9757 let payment_event = SendEvent::from_event(events.pop().unwrap());
9759 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9760 check_added_monitors!(nodes[3], 0);
9761 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9763 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9764 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9765 // post-payment_secrets) and fail back the new HTLC.
9767 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9768 nodes[3].node.process_pending_htlc_forwards();
9769 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9770 nodes[3].node.process_pending_htlc_forwards();
9772 check_added_monitors!(nodes[3], 1);
9774 let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9775 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9776 commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9778 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 }]);
9779 check_added_monitors!(nodes[2], 1);
9781 let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9782 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9783 commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9785 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9787 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9788 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9789 &None, session_privs[2]).unwrap();
9790 check_added_monitors!(nodes[0], 1);
9792 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9793 assert_eq!(events.len(), 1);
9794 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9796 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9797 expect_payment_sent(&nodes[0], our_payment_preimage, Some(None), true, true);
9801 fn test_double_partial_claim() {
9802 // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9803 // time out, the sender resends only some of the MPP parts, then the user processes the
9804 // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9806 let chanmon_cfgs = create_chanmon_cfgs(4);
9807 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9808 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9809 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9811 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9812 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9813 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9814 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9816 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9817 assert_eq!(route.paths.len(), 2);
9818 route.paths.sort_by(|path_a, _| {
9819 // Sort the path so that the path through nodes[1] comes first
9820 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9821 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9824 send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9825 // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9826 // amount of time to respond to.
9828 // Connect some blocks to time out the payment
9829 connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9830 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9832 let failed_destinations = vec![
9833 HTLCDestination::FailedPayment { payment_hash },
9834 HTLCDestination::FailedPayment { payment_hash },
9836 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9838 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
9840 // nodes[1] now retries one of the two paths...
9841 nodes[0].node.send_payment_with_route(&route, payment_hash,
9842 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9843 check_added_monitors!(nodes[0], 2);
9845 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9846 assert_eq!(events.len(), 2);
9847 let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
9848 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9850 // At this point nodes[3] has received one half of the payment, and the user goes to handle
9851 // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9852 nodes[3].node.claim_funds(payment_preimage);
9853 check_added_monitors!(nodes[3], 0);
9854 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9857 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9858 #[derive(Clone, Copy, PartialEq)]
9859 enum ExposureEvent {
9860 /// Breach occurs at HTLC forwarding (see `send_htlc`)
9862 /// Breach occurs at HTLC reception (see `update_add_htlc`)
9864 /// Breach occurs at outbound update_fee (see `send_update_fee`)
9865 AtUpdateFeeOutbound,
9868 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool, multiplier_dust_limit: bool) {
9869 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9872 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9873 // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9874 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9875 // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9876 // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9877 // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9878 // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9879 // might be available again for HTLC processing once the dust bandwidth has cleared up.
9881 let chanmon_cfgs = create_chanmon_cfgs(2);
9882 let mut config = test_default_channel_config();
9883 config.channel_config.max_dust_htlc_exposure = if multiplier_dust_limit {
9884 // Default test fee estimator rate is 253 sat/kw, so we set the multiplier to 5_000_000 / 253
9885 // to get roughly the same initial value as the default setting when this test was
9886 // originally written.
9887 MaxDustHTLCExposure::FeeRateMultiplier(5_000_000 / 253)
9888 } else { MaxDustHTLCExposure::FixedLimitMsat(5_000_000) }; // initial default setting value
9889 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9890 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9891 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9893 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None, None).unwrap();
9894 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9895 open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9896 open_channel.max_accepted_htlcs = 60;
9898 open_channel.dust_limit_satoshis = 546;
9900 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9901 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9902 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9904 let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
9906 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9909 let mut node_0_per_peer_lock;
9910 let mut node_0_peer_state_lock;
9911 match get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, temporary_channel_id) {
9912 ChannelPhase::UnfundedOutboundV1(chan) => {
9913 chan.context.holder_dust_limit_satoshis = 546;
9915 _ => panic!("Unexpected ChannelPhase variant"),
9919 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9920 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()));
9921 check_added_monitors!(nodes[1], 1);
9922 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9924 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()));
9925 check_added_monitors!(nodes[0], 1);
9926 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9928 let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9929 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9930 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9932 // Fetch a route in advance as we will be unable to once we're unable to send.
9933 let (mut route, payment_hash, _, payment_secret) =
9934 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
9936 let (dust_buffer_feerate, max_dust_htlc_exposure_msat) = {
9937 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9938 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9939 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
9940 (chan.context().get_dust_buffer_feerate(None) as u64,
9941 chan.context().get_max_dust_htlc_exposure_msat(&LowerBoundedFeeEstimator(nodes[0].fee_estimator)))
9943 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;
9944 let dust_outbound_htlc_on_holder_tx: u64 = max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9946 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;
9947 let dust_inbound_htlc_on_holder_tx: u64 = max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9949 let dust_htlc_on_counterparty_tx: u64 = 4;
9950 let dust_htlc_on_counterparty_tx_msat: u64 = max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9953 if dust_outbound_balance {
9954 // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9955 // Outbound dust balance: 4372 sats
9956 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9957 for _ in 0..dust_outbound_htlc_on_holder_tx {
9958 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9959 nodes[0].node.send_payment_with_route(&route, payment_hash,
9960 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9963 // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9964 // Inbound dust balance: 4372 sats
9965 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9966 for _ in 0..dust_inbound_htlc_on_holder_tx {
9967 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9971 if dust_outbound_balance {
9972 // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9973 // Outbound dust balance: 5000 sats
9974 for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9975 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9976 nodes[0].node.send_payment_with_route(&route, payment_hash,
9977 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9980 // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9981 // Inbound dust balance: 5000 sats
9982 for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9983 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9988 if exposure_breach_event == ExposureEvent::AtHTLCForward {
9989 route.paths[0].hops.last_mut().unwrap().fee_msat =
9990 if on_holder_tx { dust_outbound_htlc_on_holder_tx_msat } else { dust_htlc_on_counterparty_tx_msat + 1 };
9991 // With default dust exposure: 5000 sats
9993 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9994 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9995 ), true, APIError::ChannelUnavailable { .. }, {});
9997 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9998 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9999 ), true, APIError::ChannelUnavailable { .. }, {});
10001 } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
10002 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 });
10003 nodes[1].node.send_payment_with_route(&route, payment_hash,
10004 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
10005 check_added_monitors!(nodes[1], 1);
10006 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
10007 assert_eq!(events.len(), 1);
10008 let payment_event = SendEvent::from_event(events.remove(0));
10009 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
10010 // With default dust exposure: 5000 sats
10012 // Outbound dust balance: 6399 sats
10013 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
10014 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
10015 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);
10017 // Outbound dust balance: 5200 sats
10018 nodes[0].logger.assert_log("lightning::ln::channel",
10019 format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx",
10020 dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx - 1) + dust_htlc_on_counterparty_tx_msat + 4,
10021 max_dust_htlc_exposure_msat), 1);
10023 } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
10024 route.paths[0].hops.last_mut().unwrap().fee_msat = 2_500_000;
10025 // For the multiplier dust exposure limit, since it scales with feerate,
10026 // we need to add a lot of HTLCs that will become dust at the new feerate
10027 // to cross the threshold.
10029 let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[1], Some(1_000), None);
10030 nodes[0].node.send_payment_with_route(&route, payment_hash,
10031 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
10034 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10035 *feerate_lock = *feerate_lock * 10;
10037 nodes[0].node.timer_tick_occurred();
10038 check_added_monitors!(nodes[0], 1);
10039 nodes[0].logger.assert_log_contains("lightning::ln::channel", "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure", 1);
10042 let _ = nodes[0].node.get_and_clear_pending_msg_events();
10043 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
10044 added_monitors.clear();
10047 fn do_test_max_dust_htlc_exposure_by_threshold_type(multiplier_dust_limit: bool) {
10048 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true, multiplier_dust_limit);
10049 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true, multiplier_dust_limit);
10050 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true, multiplier_dust_limit);
10051 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false, multiplier_dust_limit);
10052 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false, multiplier_dust_limit);
10053 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false, multiplier_dust_limit);
10054 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true, multiplier_dust_limit);
10055 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false, multiplier_dust_limit);
10056 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true, multiplier_dust_limit);
10057 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false, multiplier_dust_limit);
10058 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false, multiplier_dust_limit);
10059 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true, multiplier_dust_limit);
10063 fn test_max_dust_htlc_exposure() {
10064 do_test_max_dust_htlc_exposure_by_threshold_type(false);
10065 do_test_max_dust_htlc_exposure_by_threshold_type(true);
10069 fn test_non_final_funding_tx() {
10070 let chanmon_cfgs = create_chanmon_cfgs(2);
10071 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10072 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10073 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10075 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
10076 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10077 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10078 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10079 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10081 let best_height = nodes[0].node.best_block.read().unwrap().height();
10083 let chan_id = *nodes[0].network_chan_count.borrow();
10084 let events = nodes[0].node.get_and_clear_pending_events();
10085 let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::ScriptBuf::new(), sequence: Sequence(1), witness: Witness::from_slice(&[&[1]]) };
10086 assert_eq!(events.len(), 1);
10087 let mut tx = match events[0] {
10088 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
10089 // Timelock the transaction _beyond_ the best client height + 1.
10090 Transaction { version: chan_id as i32, lock_time: LockTime::from_height(best_height + 2).unwrap(), input: vec![input], output: vec![TxOut {
10091 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
10094 _ => panic!("Unexpected event"),
10096 // Transaction should fail as it's evaluated as non-final for propagation.
10097 match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
10098 Err(APIError::APIMisuseError { err }) => {
10099 assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
10103 let events = nodes[0].node.get_and_clear_pending_events();
10104 assert_eq!(events.len(), 1);
10106 Event::ChannelClosed { channel_id, .. } => {
10107 assert_eq!(channel_id, temp_channel_id);
10109 _ => panic!("Unexpected event"),
10114 fn test_non_final_funding_tx_within_headroom() {
10115 let chanmon_cfgs = create_chanmon_cfgs(2);
10116 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10117 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10118 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10120 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
10121 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10122 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10123 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10124 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10126 let best_height = nodes[0].node.best_block.read().unwrap().height();
10128 let chan_id = *nodes[0].network_chan_count.borrow();
10129 let events = nodes[0].node.get_and_clear_pending_events();
10130 let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::ScriptBuf::new(), sequence: Sequence(1), witness: Witness::from_slice(&[[1]]) };
10131 assert_eq!(events.len(), 1);
10132 let mut tx = match events[0] {
10133 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
10134 // Timelock the transaction within a +1 headroom from the best block.
10135 Transaction { version: chan_id as i32, lock_time: LockTime::from_consensus(best_height + 1), input: vec![input], output: vec![TxOut {
10136 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
10139 _ => panic!("Unexpected event"),
10142 // Transaction should be accepted if it's in a +1 headroom from best block.
10143 assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
10144 get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
10148 fn accept_busted_but_better_fee() {
10149 // If a peer sends us a fee update that is too low, but higher than our previous channel
10150 // feerate, we should accept it. In the future we may want to consider closing the channel
10151 // later, but for now we only accept the update.
10152 let mut chanmon_cfgs = create_chanmon_cfgs(2);
10153 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10154 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10155 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10157 create_chan_between_nodes(&nodes[0], &nodes[1]);
10159 // Set nodes[1] to expect 5,000 sat/kW.
10161 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
10162 *feerate_lock = 5000;
10165 // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
10167 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10168 *feerate_lock = 1000;
10170 nodes[0].node.timer_tick_occurred();
10171 check_added_monitors!(nodes[0], 1);
10173 let events = nodes[0].node.get_and_clear_pending_msg_events();
10174 assert_eq!(events.len(), 1);
10176 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
10177 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
10178 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
10180 _ => panic!("Unexpected event"),
10183 // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
10186 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10187 *feerate_lock = 2000;
10189 nodes[0].node.timer_tick_occurred();
10190 check_added_monitors!(nodes[0], 1);
10192 let events = nodes[0].node.get_and_clear_pending_msg_events();
10193 assert_eq!(events.len(), 1);
10195 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
10196 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
10197 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
10199 _ => panic!("Unexpected event"),
10202 // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
10205 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10206 *feerate_lock = 1000;
10208 nodes[0].node.timer_tick_occurred();
10209 check_added_monitors!(nodes[0], 1);
10211 let events = nodes[0].node.get_and_clear_pending_msg_events();
10212 assert_eq!(events.len(), 1);
10214 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
10215 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
10216 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
10217 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000".to_owned() },
10218 [nodes[0].node.get_our_node_id()], 100000);
10219 check_closed_broadcast!(nodes[1], true);
10220 check_added_monitors!(nodes[1], 1);
10222 _ => panic!("Unexpected event"),
10226 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
10227 let mut chanmon_cfgs = create_chanmon_cfgs(2);
10228 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10229 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10230 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10231 let min_final_cltv_expiry_delta = 120;
10232 let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
10233 min_final_cltv_expiry_delta - 2 };
10234 let recv_value = 100_000;
10236 create_chan_between_nodes(&nodes[0], &nodes[1]);
10238 let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), final_cltv_expiry_delta as u32);
10239 let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
10240 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
10241 Some(recv_value), Some(min_final_cltv_expiry_delta));
10242 (payment_hash, payment_preimage, payment_secret)
10244 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
10245 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
10247 let route = get_route!(nodes[0], payment_parameters, recv_value).unwrap();
10248 nodes[0].node.send_payment_with_route(&route, payment_hash,
10249 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
10250 check_added_monitors!(nodes[0], 1);
10251 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10252 assert_eq!(events.len(), 1);
10253 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
10254 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
10255 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
10256 expect_pending_htlcs_forwardable!(nodes[1]);
10259 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
10260 None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
10262 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
10264 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
10266 check_added_monitors!(nodes[1], 1);
10268 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
10269 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
10270 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
10272 expect_payment_failed!(nodes[0], payment_hash, true);
10277 fn test_payment_with_custom_min_cltv_expiry_delta() {
10278 do_payment_with_custom_min_final_cltv_expiry(false, false);
10279 do_payment_with_custom_min_final_cltv_expiry(false, true);
10280 do_payment_with_custom_min_final_cltv_expiry(true, false);
10281 do_payment_with_custom_min_final_cltv_expiry(true, true);
10285 fn test_disconnects_peer_awaiting_response_ticks() {
10286 // Tests that nodes which are awaiting on a response critical for channel responsiveness
10287 // disconnect their counterparty after `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10288 let mut chanmon_cfgs = create_chanmon_cfgs(2);
10289 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10290 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10291 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10293 // Asserts a disconnect event is queued to the user.
10294 let check_disconnect_event = |node: &Node, should_disconnect: bool| {
10295 let disconnect_event = node.node.get_and_clear_pending_msg_events().iter().find_map(|event|
10296 if let MessageSendEvent::HandleError { action, .. } = event {
10297 if let msgs::ErrorAction::DisconnectPeerWithWarning { .. } = action {
10306 assert_eq!(disconnect_event.is_some(), should_disconnect);
10309 // Fires timer ticks ensuring we only attempt to disconnect peers after reaching
10310 // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10311 let check_disconnect = |node: &Node| {
10312 // No disconnect without any timer ticks.
10313 check_disconnect_event(node, false);
10315 // No disconnect with 1 timer tick less than required.
10316 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS - 1 {
10317 node.node.timer_tick_occurred();
10318 check_disconnect_event(node, false);
10321 // Disconnect after reaching the required ticks.
10322 node.node.timer_tick_occurred();
10323 check_disconnect_event(node, true);
10325 // Disconnect again on the next tick if the peer hasn't been disconnected yet.
10326 node.node.timer_tick_occurred();
10327 check_disconnect_event(node, true);
10330 create_chan_between_nodes(&nodes[0], &nodes[1]);
10332 // We'll start by performing a fee update with Alice (nodes[0]) on the channel.
10333 *nodes[0].fee_estimator.sat_per_kw.lock().unwrap() *= 2;
10334 nodes[0].node.timer_tick_occurred();
10335 check_added_monitors!(&nodes[0], 1);
10336 let alice_fee_update = get_htlc_update_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
10337 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), alice_fee_update.update_fee.as_ref().unwrap());
10338 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &alice_fee_update.commitment_signed);
10339 check_added_monitors!(&nodes[1], 1);
10341 // This will prompt Bob (nodes[1]) to respond with his `CommitmentSigned` and `RevokeAndACK`.
10342 let (bob_revoke_and_ack, bob_commitment_signed) = get_revoke_commit_msgs!(&nodes[1], nodes[0].node.get_our_node_id());
10343 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revoke_and_ack);
10344 check_added_monitors!(&nodes[0], 1);
10345 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_commitment_signed);
10346 check_added_monitors(&nodes[0], 1);
10348 // Alice then needs to send her final `RevokeAndACK` to complete the commitment dance. We
10349 // pretend Bob hasn't received the message and check whether he'll disconnect Alice after
10350 // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10351 let alice_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
10352 check_disconnect(&nodes[1]);
10354 // Now, we'll reconnect them to test awaiting a `ChannelReestablish` message.
10356 // Note that since the commitment dance didn't complete above, Alice is expected to resend her
10357 // final `RevokeAndACK` to Bob to complete it.
10358 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
10359 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10360 let bob_init = msgs::Init {
10361 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
10363 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &bob_init, true).unwrap();
10364 let alice_init = msgs::Init {
10365 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
10367 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &alice_init, true).unwrap();
10369 // Upon reconnection, Alice sends her `ChannelReestablish` to Bob. Alice, however, hasn't
10370 // received Bob's yet, so she should disconnect him after reaching
10371 // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10372 let alice_channel_reestablish = get_event_msg!(
10373 nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id()
10375 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &alice_channel_reestablish);
10376 check_disconnect(&nodes[0]);
10378 // Bob now sends his `ChannelReestablish` to Alice to resume the channel and consider it "live".
10379 let bob_channel_reestablish = nodes[1].node.get_and_clear_pending_msg_events().iter().find_map(|event|
10380 if let MessageSendEvent::SendChannelReestablish { node_id, msg } = event {
10381 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
10387 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bob_channel_reestablish);
10389 // Sanity check that Alice won't disconnect Bob since she's no longer waiting for any messages.
10390 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
10391 nodes[0].node.timer_tick_occurred();
10392 check_disconnect_event(&nodes[0], false);
10395 // However, Bob is still waiting on Alice's `RevokeAndACK`, so he should disconnect her after
10396 // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10397 check_disconnect(&nodes[1]);
10399 // Finally, have Bob process the last message.
10400 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &alice_revoke_and_ack);
10401 check_added_monitors(&nodes[1], 1);
10403 // At this point, neither node should attempt to disconnect each other, since they aren't
10404 // waiting on any messages.
10405 for node in &nodes {
10406 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
10407 node.node.timer_tick_occurred();
10408 check_disconnect_event(node, false);
10414 fn test_remove_expired_outbound_unfunded_channels() {
10415 let chanmon_cfgs = create_chanmon_cfgs(2);
10416 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10417 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10418 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10420 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
10421 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10422 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10423 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10424 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10426 let events = nodes[0].node.get_and_clear_pending_events();
10427 assert_eq!(events.len(), 1);
10429 Event::FundingGenerationReady { .. } => (),
10430 _ => panic!("Unexpected event"),
10433 // Asserts the outbound channel has been removed from a nodes[0]'s peer state map.
10434 let check_outbound_channel_existence = |should_exist: bool| {
10435 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
10436 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
10437 assert_eq!(chan_lock.channel_by_id.contains_key(&temp_channel_id), should_exist);
10440 // Channel should exist without any timer ticks.
10441 check_outbound_channel_existence(true);
10443 // Channel should exist with 1 timer tick less than required.
10444 for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS - 1 {
10445 nodes[0].node.timer_tick_occurred();
10446 check_outbound_channel_existence(true)
10449 // Remove channel after reaching the required ticks.
10450 nodes[0].node.timer_tick_occurred();
10451 check_outbound_channel_existence(false);
10453 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
10454 assert_eq!(msg_events.len(), 1);
10455 match msg_events[0] {
10456 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
10457 assert_eq!(msg.data, "Force-closing pending channel due to timeout awaiting establishment handshake");
10459 _ => panic!("Unexpected event"),
10461 check_closed_event(&nodes[0], 1, ClosureReason::HolderForceClosed, false, &[nodes[1].node.get_our_node_id()], 100000);
10465 fn test_remove_expired_inbound_unfunded_channels() {
10466 let chanmon_cfgs = create_chanmon_cfgs(2);
10467 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10468 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10469 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10471 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
10472 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10473 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10474 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10475 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10477 let events = nodes[0].node.get_and_clear_pending_events();
10478 assert_eq!(events.len(), 1);
10480 Event::FundingGenerationReady { .. } => (),
10481 _ => panic!("Unexpected event"),
10484 // Asserts the inbound channel has been removed from a nodes[1]'s peer state map.
10485 let check_inbound_channel_existence = |should_exist: bool| {
10486 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
10487 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
10488 assert_eq!(chan_lock.channel_by_id.contains_key(&temp_channel_id), should_exist);
10491 // Channel should exist without any timer ticks.
10492 check_inbound_channel_existence(true);
10494 // Channel should exist with 1 timer tick less than required.
10495 for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS - 1 {
10496 nodes[1].node.timer_tick_occurred();
10497 check_inbound_channel_existence(true)
10500 // Remove channel after reaching the required ticks.
10501 nodes[1].node.timer_tick_occurred();
10502 check_inbound_channel_existence(false);
10504 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
10505 assert_eq!(msg_events.len(), 1);
10506 match msg_events[0] {
10507 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
10508 assert_eq!(msg.data, "Force-closing pending channel due to timeout awaiting establishment handshake");
10510 _ => panic!("Unexpected event"),
10512 check_closed_event(&nodes[1], 1, ClosureReason::HolderForceClosed, false, &[nodes[0].node.get_our_node_id()], 100000);
10515 fn do_test_multi_post_event_actions(do_reload: bool) {
10516 // Tests handling multiple post-Event actions at once.
10517 // There is specific code in ChannelManager to handle channels where multiple post-Event
10518 // `ChannelMonitorUpdates` are pending at once. This test exercises that code.
10520 // Specifically, we test calling `get_and_clear_pending_events` while there are two
10521 // PaymentSents from different channels and one channel has two pending `ChannelMonitorUpdate`s
10522 // - one from an RAA and one from an inbound commitment_signed.
10523 let chanmon_cfgs = create_chanmon_cfgs(3);
10524 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10525 let (persister, chain_monitor);
10526 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10527 let nodes_0_deserialized;
10528 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10530 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
10531 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 0, 2).2;
10533 send_payment(&nodes[0], &[&nodes[1]], 1_000_000);
10534 send_payment(&nodes[0], &[&nodes[2]], 1_000_000);
10536 let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
10537 let (payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[2]], 1_000_000);
10539 nodes[1].node.claim_funds(our_payment_preimage);
10540 check_added_monitors!(nodes[1], 1);
10541 expect_payment_claimed!(nodes[1], our_payment_hash, 1_000_000);
10543 nodes[2].node.claim_funds(payment_preimage_2);
10544 check_added_monitors!(nodes[2], 1);
10545 expect_payment_claimed!(nodes[2], payment_hash_2, 1_000_000);
10547 for dest in &[1, 2] {
10548 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[*dest], nodes[0].node.get_our_node_id());
10549 nodes[0].node.handle_update_fulfill_htlc(&nodes[*dest].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
10550 commitment_signed_dance!(nodes[0], nodes[*dest], htlc_fulfill_updates.commitment_signed, false);
10551 check_added_monitors(&nodes[0], 0);
10554 let (route, payment_hash_3, _, payment_secret_3) =
10555 get_route_and_payment_hash!(nodes[1], nodes[0], 100_000);
10556 let payment_id = PaymentId(payment_hash_3.0);
10557 nodes[1].node.send_payment_with_route(&route, payment_hash_3,
10558 RecipientOnionFields::secret_only(payment_secret_3), payment_id).unwrap();
10559 check_added_monitors(&nodes[1], 1);
10561 let send_event = SendEvent::from_node(&nodes[1]);
10562 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event.msgs[0]);
10563 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_event.commitment_msg);
10564 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
10567 let nodes_0_serialized = nodes[0].node.encode();
10568 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
10569 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_2).encode();
10570 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);
10572 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10573 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10575 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
10576 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[2]));
10579 let events = nodes[0].node.get_and_clear_pending_events();
10580 assert_eq!(events.len(), 4);
10581 if let Event::PaymentSent { payment_preimage, .. } = events[0] {
10582 assert!(payment_preimage == our_payment_preimage || payment_preimage == payment_preimage_2);
10583 } else { panic!(); }
10584 if let Event::PaymentSent { payment_preimage, .. } = events[1] {
10585 assert!(payment_preimage == our_payment_preimage || payment_preimage == payment_preimage_2);
10586 } else { panic!(); }
10587 if let Event::PaymentPathSuccessful { .. } = events[2] {} else { panic!(); }
10588 if let Event::PaymentPathSuccessful { .. } = events[3] {} else { panic!(); }
10590 // After the events are processed, the ChannelMonitorUpdates will be released and, upon their
10591 // completion, we'll respond to nodes[1] with an RAA + CS.
10592 get_revoke_commit_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
10593 check_added_monitors(&nodes[0], 3);
10597 fn test_multi_post_event_actions() {
10598 do_test_multi_post_event_actions(true);
10599 do_test_multi_post_event_actions(false);
10603 fn test_batch_channel_open() {
10604 let chanmon_cfgs = create_chanmon_cfgs(3);
10605 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10606 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10607 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10609 // Initiate channel opening and create the batch channel funding transaction.
10610 let (tx, funding_created_msgs) = create_batch_channel_funding(&nodes[0], &[
10611 (&nodes[1], 100_000, 0, 42, None),
10612 (&nodes[2], 200_000, 0, 43, None),
10615 // Go through the funding_created and funding_signed flow with node 1.
10616 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[0]);
10617 check_added_monitors(&nodes[1], 1);
10618 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
10620 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10621 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
10622 check_added_monitors(&nodes[0], 1);
10624 // The transaction should not have been broadcast before all channels are ready.
10625 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
10627 // Go through the funding_created and funding_signed flow with node 2.
10628 nodes[2].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[1]);
10629 check_added_monitors(&nodes[2], 1);
10630 expect_channel_pending_event(&nodes[2], &nodes[0].node.get_our_node_id());
10632 let funding_signed_msg = get_event_msg!(nodes[2], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10633 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
10634 nodes[0].node.handle_funding_signed(&nodes[2].node.get_our_node_id(), &funding_signed_msg);
10635 check_added_monitors(&nodes[0], 1);
10637 // The transaction should not have been broadcast before persisting all monitors has been
10639 assert_eq!(nodes[0].tx_broadcaster.txn_broadcast().len(), 0);
10640 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
10642 // Complete the persistence of the monitor.
10643 nodes[0].chain_monitor.complete_sole_pending_chan_update(
10644 &ChannelId::v1_from_funding_outpoint(OutPoint { txid: tx.txid(), index: 1 })
10646 let events = nodes[0].node.get_and_clear_pending_events();
10648 // The transaction should only have been broadcast now.
10649 let broadcasted_txs = nodes[0].tx_broadcaster.txn_broadcast();
10650 assert_eq!(broadcasted_txs.len(), 1);
10651 assert_eq!(broadcasted_txs[0], tx);
10653 assert_eq!(events.len(), 2);
10654 assert!(events.iter().any(|e| matches!(
10656 crate::events::Event::ChannelPending {
10657 ref counterparty_node_id,
10659 } if counterparty_node_id == &nodes[1].node.get_our_node_id(),
10661 assert!(events.iter().any(|e| matches!(
10663 crate::events::Event::ChannelPending {
10664 ref counterparty_node_id,
10666 } if counterparty_node_id == &nodes[2].node.get_our_node_id(),
10671 fn test_disconnect_in_funding_batch() {
10672 let chanmon_cfgs = create_chanmon_cfgs(3);
10673 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10674 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10675 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10677 // Initiate channel opening and create the batch channel funding transaction.
10678 let (tx, funding_created_msgs) = create_batch_channel_funding(&nodes[0], &[
10679 (&nodes[1], 100_000, 0, 42, None),
10680 (&nodes[2], 200_000, 0, 43, None),
10683 // Go through the funding_created and funding_signed flow with node 1.
10684 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[0]);
10685 check_added_monitors(&nodes[1], 1);
10686 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
10688 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10689 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
10690 check_added_monitors(&nodes[0], 1);
10692 // The transaction should not have been broadcast before all channels are ready.
10693 assert_eq!(nodes[0].tx_broadcaster.txn_broadcast().len(), 0);
10695 // The remaining peer in the batch disconnects.
10696 nodes[0].node.peer_disconnected(&nodes[2].node.get_our_node_id());
10698 // The channels in the batch will close immediately.
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);
10703 check_closed_events(&nodes[0], &[
10704 ExpectedCloseEvent {
10705 channel_id: Some(channel_id_1),
10706 discard_funding: true,
10707 channel_funding_txo: Some(funding_txo_1),
10708 user_channel_id: Some(42),
10709 ..Default::default()
10711 ExpectedCloseEvent {
10712 channel_id: Some(channel_id_2),
10713 discard_funding: true,
10714 channel_funding_txo: Some(funding_txo_2),
10715 user_channel_id: Some(43),
10716 ..Default::default()
10720 // The monitor should become closed.
10721 check_added_monitors(&nodes[0], 1);
10723 let mut monitor_updates = nodes[0].chain_monitor.monitor_updates.lock().unwrap();
10724 let monitor_updates_1 = monitor_updates.get(&channel_id_1).unwrap();
10725 assert_eq!(monitor_updates_1.len(), 1);
10726 assert_eq!(monitor_updates_1[0].update_id, CLOSED_CHANNEL_UPDATE_ID);
10729 // The funding transaction should not have been broadcast, and therefore, we don't need
10730 // to broadcast a force-close transaction for the closed monitor.
10731 assert_eq!(nodes[0].tx_broadcaster.txn_broadcast().len(), 0);
10733 // Ensure the channels don't exist anymore.
10734 assert!(nodes[0].node.list_channels().is_empty());
10738 fn test_batch_funding_close_after_funding_signed() {
10739 let chanmon_cfgs = create_chanmon_cfgs(3);
10740 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10741 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10742 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10744 // Initiate channel opening and create the batch channel funding transaction.
10745 let (tx, funding_created_msgs) = create_batch_channel_funding(&nodes[0], &[
10746 (&nodes[1], 100_000, 0, 42, None),
10747 (&nodes[2], 200_000, 0, 43, None),
10750 // Go through the funding_created and funding_signed flow with node 1.
10751 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[0]);
10752 check_added_monitors(&nodes[1], 1);
10753 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
10755 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10756 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
10757 check_added_monitors(&nodes[0], 1);
10759 // Go through the funding_created and funding_signed flow with node 2.
10760 nodes[2].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[1]);
10761 check_added_monitors(&nodes[2], 1);
10762 expect_channel_pending_event(&nodes[2], &nodes[0].node.get_our_node_id());
10764 let funding_signed_msg = get_event_msg!(nodes[2], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10765 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
10766 nodes[0].node.handle_funding_signed(&nodes[2].node.get_our_node_id(), &funding_signed_msg);
10767 check_added_monitors(&nodes[0], 1);
10769 // The transaction should not have been broadcast before all channels are ready.
10770 assert_eq!(nodes[0].tx_broadcaster.txn_broadcast().len(), 0);
10772 // Force-close the channel for which we've completed the initial monitor.
10773 let funding_txo_1 = OutPoint { txid: tx.txid(), index: 0 };
10774 let funding_txo_2 = OutPoint { txid: tx.txid(), index: 1 };
10775 let channel_id_1 = ChannelId::v1_from_funding_outpoint(funding_txo_1);
10776 let channel_id_2 = ChannelId::v1_from_funding_outpoint(funding_txo_2);
10777 nodes[0].node.force_close_broadcasting_latest_txn(&channel_id_1, &nodes[1].node.get_our_node_id()).unwrap();
10778 check_added_monitors(&nodes[0], 2);
10780 let mut monitor_updates = nodes[0].chain_monitor.monitor_updates.lock().unwrap();
10781 let monitor_updates_1 = monitor_updates.get(&channel_id_1).unwrap();
10782 assert_eq!(monitor_updates_1.len(), 1);
10783 assert_eq!(monitor_updates_1[0].update_id, CLOSED_CHANNEL_UPDATE_ID);
10784 let monitor_updates_2 = monitor_updates.get(&channel_id_2).unwrap();
10785 assert_eq!(monitor_updates_2.len(), 1);
10786 assert_eq!(monitor_updates_2[0].update_id, CLOSED_CHANNEL_UPDATE_ID);
10788 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
10789 match msg_events[0] {
10790 MessageSendEvent::HandleError { .. } => (),
10791 _ => panic!("Unexpected message."),
10794 // We broadcast the commitment transaction as part of the force-close.
10796 let broadcasted_txs = nodes[0].tx_broadcaster.txn_broadcast();
10797 assert_eq!(broadcasted_txs.len(), 1);
10798 assert!(broadcasted_txs[0].txid() != tx.txid());
10799 assert_eq!(broadcasted_txs[0].input.len(), 1);
10800 assert_eq!(broadcasted_txs[0].input[0].previous_output.txid, tx.txid());
10803 // All channels in the batch should close immediately.
10804 check_closed_events(&nodes[0], &[
10805 ExpectedCloseEvent {
10806 channel_id: Some(channel_id_1),
10807 discard_funding: true,
10808 channel_funding_txo: Some(funding_txo_1),
10809 user_channel_id: Some(42),
10810 ..Default::default()
10812 ExpectedCloseEvent {
10813 channel_id: Some(channel_id_2),
10814 discard_funding: true,
10815 channel_funding_txo: Some(funding_txo_2),
10816 user_channel_id: Some(43),
10817 ..Default::default()
10821 // Ensure the channels don't exist anymore.
10822 assert!(nodes[0].node.list_channels().is_empty());
10825 fn do_test_funding_and_commitment_tx_confirm_same_block(confirm_remote_commitment: bool) {
10826 // Tests that a node will forget the channel (when it only requires 1 confirmation) if the
10827 // funding and commitment transaction confirm in the same block.
10828 let chanmon_cfgs = create_chanmon_cfgs(2);
10829 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10830 let mut min_depth_1_block_cfg = test_default_channel_config();
10831 min_depth_1_block_cfg.channel_handshake_config.minimum_depth = 1;
10832 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(min_depth_1_block_cfg), Some(min_depth_1_block_cfg)]);
10833 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10835 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
10836 let chan_id = ChannelId::v1_from_funding_outpoint(chain::transaction::OutPoint { txid: funding_tx.txid(), index: 0 });
10838 assert_eq!(nodes[0].node.list_channels().len(), 1);
10839 assert_eq!(nodes[1].node.list_channels().len(), 1);
10841 let (closing_node, other_node) = if confirm_remote_commitment {
10842 (&nodes[1], &nodes[0])
10844 (&nodes[0], &nodes[1])
10847 closing_node.node.force_close_broadcasting_latest_txn(&chan_id, &other_node.node.get_our_node_id()).unwrap();
10848 let mut msg_events = closing_node.node.get_and_clear_pending_msg_events();
10849 assert_eq!(msg_events.len(), 1);
10850 match msg_events.pop().unwrap() {
10851 MessageSendEvent::HandleError { action: msgs::ErrorAction::DisconnectPeer { .. }, .. } => {},
10852 _ => panic!("Unexpected event"),
10854 check_added_monitors(closing_node, 1);
10855 check_closed_event(closing_node, 1, ClosureReason::HolderForceClosed, false, &[other_node.node.get_our_node_id()], 1_000_000);
10857 let commitment_tx = {
10858 let mut txn = closing_node.tx_broadcaster.txn_broadcast();
10859 assert_eq!(txn.len(), 1);
10860 let commitment_tx = txn.pop().unwrap();
10861 check_spends!(commitment_tx, funding_tx);
10865 mine_transactions(&nodes[0], &[&funding_tx, &commitment_tx]);
10866 mine_transactions(&nodes[1], &[&funding_tx, &commitment_tx]);
10868 check_closed_broadcast(other_node, 1, true);
10869 check_added_monitors(other_node, 1);
10870 check_closed_event(other_node, 1, ClosureReason::CommitmentTxConfirmed, false, &[closing_node.node.get_our_node_id()], 1_000_000);
10872 assert!(nodes[0].node.list_channels().is_empty());
10873 assert!(nodes[1].node.list_channels().is_empty());
10877 fn test_funding_and_commitment_tx_confirm_same_block() {
10878 do_test_funding_and_commitment_tx_confirm_same_block(false);
10879 do_test_funding_and_commitment_tx_confirm_same_block(true);