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("lightning::ln::channelmanager", "Funding remote cannot afford proposed new fee".to_string(), 1);
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("lightning::ln::channelmanager", "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value".to_string(), 1);
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("lightning::ln::channelmanager", "Remote HTLC add would put them under remote reserve value".to_string(), 1);
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);
2277 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2278 assert_eq!(node_txn.len(), 1);
2279 mine_transaction(&nodes[0], &node_txn[0]);
2280 check_added_monitors!(nodes[0], 1);
2281 test_txn_broadcast(&nodes[0], &chan_1, Some(node_txn[0].clone()), HTLCType::NONE);
2283 check_closed_broadcast!(nodes[0], true);
2284 assert_eq!(nodes[0].node.list_channels().len(), 0);
2285 assert_eq!(nodes[1].node.list_channels().len(), 1);
2286 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2287 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[0].node.get_our_node_id()], 100000);
2289 // One pending HTLC is discarded by the force-close:
2290 let (payment_preimage_1, payment_hash_1, ..) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2292 // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2293 // broadcasted until we reach the timelock time).
2294 nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2295 check_closed_broadcast!(nodes[1], true);
2296 check_added_monitors!(nodes[1], 1);
2298 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2299 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2300 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2301 mine_transaction(&nodes[2], &node_txn[0]);
2302 check_added_monitors!(nodes[2], 1);
2303 test_txn_broadcast(&nodes[2], &chan_2, Some(node_txn[0].clone()), HTLCType::NONE);
2305 check_closed_broadcast!(nodes[2], true);
2306 assert_eq!(nodes[1].node.list_channels().len(), 0);
2307 assert_eq!(nodes[2].node.list_channels().len(), 1);
2308 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[2].node.get_our_node_id()], 100000);
2309 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2311 macro_rules! claim_funds {
2312 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2314 $node.node.claim_funds($preimage);
2315 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2316 check_added_monitors!($node, 1);
2318 let events = $node.node.get_and_clear_pending_msg_events();
2319 assert_eq!(events.len(), 1);
2321 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2322 assert!(update_add_htlcs.is_empty());
2323 assert!(update_fail_htlcs.is_empty());
2324 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2326 _ => panic!("Unexpected event"),
2332 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2333 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2334 nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2335 check_added_monitors!(nodes[2], 1);
2336 check_closed_broadcast!(nodes[2], true);
2337 let node2_commitment_txid;
2339 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2340 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2341 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2342 node2_commitment_txid = node_txn[0].txid();
2344 // Claim the payment on nodes[3], giving it knowledge of the preimage
2345 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2346 mine_transaction(&nodes[3], &node_txn[0]);
2347 check_added_monitors!(nodes[3], 1);
2348 check_preimage_claim(&nodes[3], &node_txn);
2350 check_closed_broadcast!(nodes[3], true);
2351 assert_eq!(nodes[2].node.list_channels().len(), 0);
2352 assert_eq!(nodes[3].node.list_channels().len(), 1);
2353 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed, [nodes[3].node.get_our_node_id()], 100000);
2354 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
2356 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2357 // confusing us in the following tests.
2358 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2360 // One pending HTLC to time out:
2361 let (payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2362 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2365 let (close_chan_update_1, close_chan_update_2) = {
2366 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2367 let events = nodes[3].node.get_and_clear_pending_msg_events();
2368 assert_eq!(events.len(), 2);
2369 let close_chan_update_1 = match events[0] {
2370 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2373 _ => panic!("Unexpected event"),
2376 MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { .. }, node_id } => {
2377 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2379 _ => panic!("Unexpected event"),
2381 check_added_monitors!(nodes[3], 1);
2383 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2385 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2386 node_txn.retain(|tx| {
2387 if tx.input[0].previous_output.txid == node2_commitment_txid {
2393 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2395 // Claim the payment on nodes[4], giving it knowledge of the preimage
2396 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2398 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2399 let events = nodes[4].node.get_and_clear_pending_msg_events();
2400 assert_eq!(events.len(), 2);
2401 let close_chan_update_2 = match events[0] {
2402 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2405 _ => panic!("Unexpected event"),
2408 MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { .. }, node_id } => {
2409 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2411 _ => panic!("Unexpected event"),
2413 check_added_monitors!(nodes[4], 1);
2414 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2415 check_closed_event!(nodes[4], 1, ClosureReason::HolderForceClosed, [nodes[3].node.get_our_node_id()], 100000);
2417 mine_transaction(&nodes[4], &node_txn[0]);
2418 check_preimage_claim(&nodes[4], &node_txn);
2419 (close_chan_update_1, close_chan_update_2)
2421 nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2422 nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2423 assert_eq!(nodes[3].node.list_channels().len(), 0);
2424 assert_eq!(nodes[4].node.list_channels().len(), 0);
2426 assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2427 Ok(ChannelMonitorUpdateStatus::Completed));
2428 check_closed_event!(nodes[3], 1, ClosureReason::HolderForceClosed, [nodes[4].node.get_our_node_id()], 100000);
2432 fn test_justice_tx_htlc_timeout() {
2433 // Test justice txn built on revoked HTLC-Timeout tx, against both sides
2434 let mut alice_config = UserConfig::default();
2435 alice_config.channel_handshake_config.announced_channel = true;
2436 alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2437 alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2438 let mut bob_config = UserConfig::default();
2439 bob_config.channel_handshake_config.announced_channel = true;
2440 bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2441 bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2442 let user_cfgs = [Some(alice_config), Some(bob_config)];
2443 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2444 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2445 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2446 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2447 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2448 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2449 // Create some new channels:
2450 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
2452 // A pending HTLC which will be revoked:
2453 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2454 // Get the will-be-revoked local txn from nodes[0]
2455 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2456 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2457 assert_eq!(revoked_local_txn[0].input.len(), 1);
2458 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2459 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2460 assert_eq!(revoked_local_txn[1].input.len(), 1);
2461 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2462 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2463 // Revoke the old state
2464 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2467 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2469 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2470 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2471 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2472 check_spends!(node_txn[0], revoked_local_txn[0]);
2473 node_txn.swap_remove(0);
2475 check_added_monitors!(nodes[1], 1);
2476 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2477 test_txn_broadcast(&nodes[1], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2479 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2480 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2481 // Verify broadcast of revoked HTLC-timeout
2482 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2483 check_added_monitors!(nodes[0], 1);
2484 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2485 // Broadcast revoked HTLC-timeout on node 1
2486 mine_transaction(&nodes[1], &node_txn[1]);
2487 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2489 get_announce_close_broadcast_events(&nodes, 0, 1);
2490 assert_eq!(nodes[0].node.list_channels().len(), 0);
2491 assert_eq!(nodes[1].node.list_channels().len(), 0);
2495 fn test_justice_tx_htlc_success() {
2496 // Test justice txn built on revoked HTLC-Success tx, against both sides
2497 let mut alice_config = UserConfig::default();
2498 alice_config.channel_handshake_config.announced_channel = true;
2499 alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2500 alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2501 let mut bob_config = UserConfig::default();
2502 bob_config.channel_handshake_config.announced_channel = true;
2503 bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2504 bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2505 let user_cfgs = [Some(alice_config), Some(bob_config)];
2506 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2507 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2508 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2509 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2510 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2511 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2512 // Create some new channels:
2513 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
2515 // A pending HTLC which will be revoked:
2516 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2517 // Get the will-be-revoked local txn from B
2518 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2519 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2520 assert_eq!(revoked_local_txn[0].input.len(), 1);
2521 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2522 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2523 // Revoke the old state
2524 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2526 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2528 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2529 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2530 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2532 check_spends!(node_txn[0], revoked_local_txn[0]);
2533 node_txn.swap_remove(0);
2535 check_added_monitors!(nodes[0], 1);
2536 test_txn_broadcast(&nodes[0], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2538 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2539 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2540 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2541 check_added_monitors!(nodes[1], 1);
2542 mine_transaction(&nodes[0], &node_txn[1]);
2543 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2544 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2546 get_announce_close_broadcast_events(&nodes, 0, 1);
2547 assert_eq!(nodes[0].node.list_channels().len(), 0);
2548 assert_eq!(nodes[1].node.list_channels().len(), 0);
2552 fn revoked_output_claim() {
2553 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2554 // transaction is broadcast by its counterparty
2555 let chanmon_cfgs = create_chanmon_cfgs(2);
2556 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2557 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2558 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2559 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2560 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2561 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2562 assert_eq!(revoked_local_txn.len(), 1);
2563 // Only output is the full channel value back to nodes[0]:
2564 assert_eq!(revoked_local_txn[0].output.len(), 1);
2565 // Send a payment through, updating everyone's latest commitment txn
2566 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2568 // Inform nodes[1] that nodes[0] broadcast a stale tx
2569 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2570 check_added_monitors!(nodes[1], 1);
2571 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2572 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2573 assert_eq!(node_txn.len(), 1); // ChannelMonitor: justice tx against revoked to_local output
2575 check_spends!(node_txn[0], revoked_local_txn[0]);
2577 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2578 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2579 get_announce_close_broadcast_events(&nodes, 0, 1);
2580 check_added_monitors!(nodes[0], 1);
2581 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2585 fn test_forming_justice_tx_from_monitor_updates() {
2586 do_test_forming_justice_tx_from_monitor_updates(true);
2587 do_test_forming_justice_tx_from_monitor_updates(false);
2590 fn do_test_forming_justice_tx_from_monitor_updates(broadcast_initial_commitment: bool) {
2591 // Simple test to make sure that the justice tx formed in WatchtowerPersister
2592 // is properly formed and can be broadcasted/confirmed successfully in the event
2593 // that a revoked commitment transaction is broadcasted
2594 // (Similar to `revoked_output_claim` test but we get the justice tx + broadcast manually)
2595 let chanmon_cfgs = create_chanmon_cfgs(2);
2596 let destination_script0 = chanmon_cfgs[0].keys_manager.get_destination_script([0; 32]).unwrap();
2597 let destination_script1 = chanmon_cfgs[1].keys_manager.get_destination_script([0; 32]).unwrap();
2598 let persisters = vec![WatchtowerPersister::new(destination_script0),
2599 WatchtowerPersister::new(destination_script1)];
2600 let node_cfgs = create_node_cfgs_with_persisters(2, &chanmon_cfgs, persisters.iter().collect());
2601 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2602 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2603 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
2604 let funding_txo = OutPoint { txid: funding_tx.txid(), index: 0 };
2606 if !broadcast_initial_commitment {
2607 // Send a payment to move the channel forward
2608 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5_000_000);
2611 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output.
2612 // We'll keep this commitment transaction to broadcast once it's revoked.
2613 let revoked_local_txn = get_local_commitment_txn!(nodes[0], channel_id);
2614 assert_eq!(revoked_local_txn.len(), 1);
2615 let revoked_commitment_tx = &revoked_local_txn[0];
2617 // Send another payment, now revoking the previous commitment tx
2618 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5_000_000);
2620 let justice_tx = persisters[1].justice_tx(funding_txo, &revoked_commitment_tx.txid()).unwrap();
2621 check_spends!(justice_tx, revoked_commitment_tx);
2623 mine_transactions(&nodes[1], &[revoked_commitment_tx, &justice_tx]);
2624 mine_transactions(&nodes[0], &[revoked_commitment_tx, &justice_tx]);
2626 check_added_monitors!(nodes[1], 1);
2627 check_closed_event(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false,
2628 &[nodes[0].node.get_our_node_id()], 100_000);
2629 get_announce_close_broadcast_events(&nodes, 1, 0);
2631 check_added_monitors!(nodes[0], 1);
2632 check_closed_event(&nodes[0], 1, ClosureReason::CommitmentTxConfirmed, false,
2633 &[nodes[1].node.get_our_node_id()], 100_000);
2635 // Check that the justice tx has sent the revoked output value to nodes[1]
2636 let monitor = get_monitor!(nodes[1], channel_id);
2637 let total_claimable_balance = monitor.get_claimable_balances().iter().fold(0, |sum, balance| {
2639 channelmonitor::Balance::ClaimableAwaitingConfirmations { amount_satoshis, .. } => sum + amount_satoshis,
2640 _ => panic!("Unexpected balance type"),
2643 // On the first commitment, node[1]'s balance was below dust so it didn't have an output
2644 let node1_channel_balance = if broadcast_initial_commitment { 0 } else { revoked_commitment_tx.output[0].value };
2645 let expected_claimable_balance = node1_channel_balance + justice_tx.output[0].value;
2646 assert_eq!(total_claimable_balance, expected_claimable_balance);
2651 fn claim_htlc_outputs_shared_tx() {
2652 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2653 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2654 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2655 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2656 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2657 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2659 // Create some new channel:
2660 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2662 // Rebalance the network to generate htlc in the two directions
2663 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2664 // 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
2665 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2666 let (_payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2668 // Get the will-be-revoked local txn from node[0]
2669 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2670 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2671 assert_eq!(revoked_local_txn[0].input.len(), 1);
2672 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2673 assert_eq!(revoked_local_txn[1].input.len(), 1);
2674 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2675 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2676 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2678 //Revoke the old state
2679 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2682 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2683 check_added_monitors!(nodes[0], 1);
2684 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2685 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2686 check_added_monitors!(nodes[1], 1);
2687 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2688 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2689 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2691 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2692 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2694 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2695 check_spends!(node_txn[0], revoked_local_txn[0]);
2697 let mut witness_lens = BTreeSet::new();
2698 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2699 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2700 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2701 assert_eq!(witness_lens.len(), 3);
2702 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2703 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2704 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2706 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2707 // ANTI_REORG_DELAY confirmations.
2708 mine_transaction(&nodes[1], &node_txn[0]);
2709 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2710 expect_payment_failed!(nodes[1], payment_hash_2, false);
2712 get_announce_close_broadcast_events(&nodes, 0, 1);
2713 assert_eq!(nodes[0].node.list_channels().len(), 0);
2714 assert_eq!(nodes[1].node.list_channels().len(), 0);
2718 fn claim_htlc_outputs_single_tx() {
2719 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2720 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2721 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2722 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2723 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2724 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2726 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2728 // Rebalance the network to generate htlc in the two directions
2729 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2730 // 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
2731 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2732 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2733 let (_payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2735 // Get the will-be-revoked local txn from node[0]
2736 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2738 //Revoke the old state
2739 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2742 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2743 check_added_monitors!(nodes[0], 1);
2744 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2745 check_added_monitors!(nodes[1], 1);
2746 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2747 let mut events = nodes[0].node.get_and_clear_pending_events();
2748 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2749 match events.last().unwrap() {
2750 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2751 _ => panic!("Unexpected event"),
2754 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2755 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2757 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcast();
2759 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2760 assert_eq!(node_txn[0].input.len(), 1);
2761 check_spends!(node_txn[0], chan_1.3);
2762 assert_eq!(node_txn[1].input.len(), 1);
2763 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2764 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2765 check_spends!(node_txn[1], node_txn[0]);
2767 // Filter out any non justice transactions.
2768 node_txn.retain(|tx| tx.input[0].previous_output.txid == revoked_local_txn[0].txid());
2769 assert!(node_txn.len() > 3);
2771 assert_eq!(node_txn[0].input.len(), 1);
2772 assert_eq!(node_txn[1].input.len(), 1);
2773 assert_eq!(node_txn[2].input.len(), 1);
2775 check_spends!(node_txn[0], revoked_local_txn[0]);
2776 check_spends!(node_txn[1], revoked_local_txn[0]);
2777 check_spends!(node_txn[2], revoked_local_txn[0]);
2779 let mut witness_lens = BTreeSet::new();
2780 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2781 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2782 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2783 assert_eq!(witness_lens.len(), 3);
2784 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2785 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2786 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2788 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2789 // ANTI_REORG_DELAY confirmations.
2790 mine_transaction(&nodes[1], &node_txn[0]);
2791 mine_transaction(&nodes[1], &node_txn[1]);
2792 mine_transaction(&nodes[1], &node_txn[2]);
2793 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2794 expect_payment_failed!(nodes[1], payment_hash_2, false);
2796 get_announce_close_broadcast_events(&nodes, 0, 1);
2797 assert_eq!(nodes[0].node.list_channels().len(), 0);
2798 assert_eq!(nodes[1].node.list_channels().len(), 0);
2802 fn test_htlc_on_chain_success() {
2803 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2804 // the preimage backward accordingly. So here we test that ChannelManager is
2805 // broadcasting the right event to other nodes in payment path.
2806 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2807 // A --------------------> B ----------------------> C (preimage)
2808 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2809 // commitment transaction was broadcast.
2810 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2812 // B should be able to claim via preimage if A then broadcasts its local tx.
2813 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2814 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2815 // PaymentSent event).
2817 let chanmon_cfgs = create_chanmon_cfgs(3);
2818 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2819 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2820 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2822 // Create some initial channels
2823 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2824 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2826 // Ensure all nodes are at the same height
2827 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2828 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2829 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2830 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2832 // Rebalance the network a bit by relaying one payment through all the channels...
2833 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2834 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2836 let (our_payment_preimage, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2837 let (our_payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2839 // Broadcast legit commitment tx from C on B's chain
2840 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2841 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2842 assert_eq!(commitment_tx.len(), 1);
2843 check_spends!(commitment_tx[0], chan_2.3);
2844 nodes[2].node.claim_funds(our_payment_preimage);
2845 expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2846 nodes[2].node.claim_funds(our_payment_preimage_2);
2847 expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2848 check_added_monitors!(nodes[2], 2);
2849 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2850 assert!(updates.update_add_htlcs.is_empty());
2851 assert!(updates.update_fail_htlcs.is_empty());
2852 assert!(updates.update_fail_malformed_htlcs.is_empty());
2853 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2855 mine_transaction(&nodes[2], &commitment_tx[0]);
2856 check_closed_broadcast!(nodes[2], true);
2857 check_added_monitors!(nodes[2], 1);
2858 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2859 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 2 (2 * HTLC-Success tx)
2860 assert_eq!(node_txn.len(), 2);
2861 check_spends!(node_txn[0], commitment_tx[0]);
2862 check_spends!(node_txn[1], commitment_tx[0]);
2863 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2864 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2865 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2866 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2867 assert_eq!(node_txn[0].lock_time, LockTime::ZERO);
2868 assert_eq!(node_txn[1].lock_time, LockTime::ZERO);
2870 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2871 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()]));
2872 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2874 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2875 assert_eq!(added_monitors.len(), 1);
2876 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2877 added_monitors.clear();
2879 let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2880 assert_eq!(forwarded_events.len(), 3);
2881 match forwarded_events[0] {
2882 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2883 _ => panic!("Unexpected event"),
2885 let chan_id = Some(chan_1.2);
2886 match forwarded_events[1] {
2887 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2888 assert_eq!(fee_earned_msat, Some(1000));
2889 assert_eq!(prev_channel_id, chan_id);
2890 assert_eq!(claim_from_onchain_tx, true);
2891 assert_eq!(next_channel_id, Some(chan_2.2));
2892 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2896 match forwarded_events[2] {
2897 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2898 assert_eq!(fee_earned_msat, Some(1000));
2899 assert_eq!(prev_channel_id, chan_id);
2900 assert_eq!(claim_from_onchain_tx, true);
2901 assert_eq!(next_channel_id, Some(chan_2.2));
2902 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2906 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2908 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2909 assert_eq!(added_monitors.len(), 2);
2910 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2911 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2912 added_monitors.clear();
2914 assert_eq!(events.len(), 3);
2916 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
2917 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
2919 match nodes_2_event {
2920 MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { .. }, node_id: _ } => {},
2921 _ => panic!("Unexpected event"),
2924 match nodes_0_event {
2925 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, .. } } => {
2926 assert!(update_add_htlcs.is_empty());
2927 assert!(update_fail_htlcs.is_empty());
2928 assert_eq!(update_fulfill_htlcs.len(), 1);
2929 assert!(update_fail_malformed_htlcs.is_empty());
2930 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2932 _ => panic!("Unexpected event"),
2935 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
2937 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2938 _ => panic!("Unexpected event"),
2941 macro_rules! check_tx_local_broadcast {
2942 ($node: expr, $htlc_offered: expr, $commitment_tx: expr) => { {
2943 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2944 assert_eq!(node_txn.len(), 2);
2945 // Node[1]: 2 * HTLC-timeout tx
2946 // Node[0]: 2 * HTLC-timeout tx
2947 check_spends!(node_txn[0], $commitment_tx);
2948 check_spends!(node_txn[1], $commitment_tx);
2949 assert_ne!(node_txn[0].lock_time, LockTime::ZERO);
2950 assert_ne!(node_txn[1].lock_time, LockTime::ZERO);
2952 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2953 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2954 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2955 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2957 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2958 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2959 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2960 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2965 // nodes[1] now broadcasts its own timeout-claim of the output that nodes[2] just claimed via success.
2966 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0]);
2968 // Broadcast legit commitment tx from A on B's chain
2969 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2970 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2971 check_spends!(node_a_commitment_tx[0], chan_1.3);
2972 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2973 check_closed_broadcast!(nodes[1], true);
2974 check_added_monitors!(nodes[1], 1);
2975 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2976 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2977 assert!(node_txn.len() == 1 || node_txn.len() == 3); // HTLC-Success, 2* RBF bumps of above HTLC txn
2978 let commitment_spend =
2979 if node_txn.len() == 1 {
2982 // Certain `ConnectStyle`s will cause RBF bumps of the previous HTLC transaction to be broadcast.
2983 // FullBlockViaListen
2984 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2985 check_spends!(node_txn[1], commitment_tx[0]);
2986 check_spends!(node_txn[2], commitment_tx[0]);
2987 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2990 check_spends!(node_txn[0], commitment_tx[0]);
2991 check_spends!(node_txn[1], commitment_tx[0]);
2992 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2997 check_spends!(commitment_spend, node_a_commitment_tx[0]);
2998 assert_eq!(commitment_spend.input.len(), 2);
2999 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3000 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3001 assert_eq!(commitment_spend.lock_time.to_consensus_u32(), nodes[1].best_block_info().1);
3002 assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
3003 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
3004 // we already checked the same situation with A.
3006 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
3007 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()]));
3008 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
3009 check_closed_broadcast!(nodes[0], true);
3010 check_added_monitors!(nodes[0], 1);
3011 let events = nodes[0].node.get_and_clear_pending_events();
3012 assert_eq!(events.len(), 5);
3013 let mut first_claimed = false;
3014 for event in events {
3016 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3017 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
3018 assert!(!first_claimed);
3019 first_claimed = true;
3021 assert_eq!(payment_preimage, our_payment_preimage_2);
3022 assert_eq!(payment_hash, payment_hash_2);
3025 Event::PaymentPathSuccessful { .. } => {},
3026 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
3027 _ => panic!("Unexpected event"),
3030 check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0]);
3033 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
3034 // Test that in case of a unilateral close onchain, we detect the state of output and
3035 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
3036 // broadcasting the right event to other nodes in payment path.
3037 // A ------------------> B ----------------------> C (timeout)
3038 // B's commitment tx C's commitment tx
3040 // B's HTLC timeout tx B's timeout tx
3042 let chanmon_cfgs = create_chanmon_cfgs(3);
3043 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3044 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3045 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3046 *nodes[0].connect_style.borrow_mut() = connect_style;
3047 *nodes[1].connect_style.borrow_mut() = connect_style;
3048 *nodes[2].connect_style.borrow_mut() = connect_style;
3050 // Create some intial channels
3051 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
3052 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3054 // Rebalance the network a bit by relaying one payment thorugh all the channels...
3055 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
3056 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
3058 let (_payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
3060 // Broadcast legit commitment tx from C on B's chain
3061 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
3062 check_spends!(commitment_tx[0], chan_2.3);
3063 nodes[2].node.fail_htlc_backwards(&payment_hash);
3064 check_added_monitors!(nodes[2], 0);
3065 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
3066 check_added_monitors!(nodes[2], 1);
3068 let events = nodes[2].node.get_and_clear_pending_msg_events();
3069 assert_eq!(events.len(), 1);
3071 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, .. } } => {
3072 assert!(update_add_htlcs.is_empty());
3073 assert!(!update_fail_htlcs.is_empty());
3074 assert!(update_fulfill_htlcs.is_empty());
3075 assert!(update_fail_malformed_htlcs.is_empty());
3076 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
3078 _ => panic!("Unexpected event"),
3080 mine_transaction(&nodes[2], &commitment_tx[0]);
3081 check_closed_broadcast!(nodes[2], true);
3082 check_added_monitors!(nodes[2], 1);
3083 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
3084 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
3085 assert_eq!(node_txn.len(), 0);
3087 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
3088 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
3089 mine_transaction(&nodes[1], &commitment_tx[0]);
3090 check_closed_event!(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false
3091 , [nodes[2].node.get_our_node_id()], 100000);
3092 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
3094 let mut txn = nodes[1].tx_broadcaster.txn_broadcast();
3095 if nodes[1].connect_style.borrow().skips_blocks() {
3096 assert_eq!(txn.len(), 1);
3098 assert_eq!(txn.len(), 3); // Two extra fee bumps for timeout transaction
3100 txn.iter().for_each(|tx| check_spends!(tx, commitment_tx[0]));
3101 assert_eq!(txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3105 mine_transaction(&nodes[1], &timeout_tx);
3106 check_added_monitors!(nodes[1], 1);
3107 check_closed_broadcast!(nodes[1], true);
3109 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3111 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 }]);
3112 check_added_monitors!(nodes[1], 1);
3113 let events = nodes[1].node.get_and_clear_pending_msg_events();
3114 assert_eq!(events.len(), 1);
3116 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, .. } } => {
3117 assert!(update_add_htlcs.is_empty());
3118 assert!(!update_fail_htlcs.is_empty());
3119 assert!(update_fulfill_htlcs.is_empty());
3120 assert!(update_fail_malformed_htlcs.is_empty());
3121 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3123 _ => panic!("Unexpected event"),
3126 // Broadcast legit commitment tx from B on A's chain
3127 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3128 check_spends!(commitment_tx[0], chan_1.3);
3130 mine_transaction(&nodes[0], &commitment_tx[0]);
3131 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
3133 check_closed_broadcast!(nodes[0], true);
3134 check_added_monitors!(nodes[0], 1);
3135 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
3136 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // 1 timeout tx
3137 assert_eq!(node_txn.len(), 1);
3138 check_spends!(node_txn[0], commitment_tx[0]);
3139 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3143 fn test_htlc_on_chain_timeout() {
3144 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3145 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3146 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3150 fn test_simple_commitment_revoked_fail_backward() {
3151 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3152 // and fail backward accordingly.
3154 let chanmon_cfgs = create_chanmon_cfgs(3);
3155 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3156 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3157 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3159 // Create some initial channels
3160 create_announced_chan_between_nodes(&nodes, 0, 1);
3161 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3163 let (payment_preimage, _payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3164 // Get the will-be-revoked local txn from nodes[2]
3165 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3166 // Revoke the old state
3167 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3169 let (_, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3171 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3172 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
3173 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3174 check_added_monitors!(nodes[1], 1);
3175 check_closed_broadcast!(nodes[1], true);
3177 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 }]);
3178 check_added_monitors!(nodes[1], 1);
3179 let events = nodes[1].node.get_and_clear_pending_msg_events();
3180 assert_eq!(events.len(), 1);
3182 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, .. } } => {
3183 assert!(update_add_htlcs.is_empty());
3184 assert_eq!(update_fail_htlcs.len(), 1);
3185 assert!(update_fulfill_htlcs.is_empty());
3186 assert!(update_fail_malformed_htlcs.is_empty());
3187 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3189 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3190 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3191 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3193 _ => panic!("Unexpected event"),
3197 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3198 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3199 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3200 // commitment transaction anymore.
3201 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3202 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3203 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3204 // technically disallowed and we should probably handle it reasonably.
3205 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3206 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3208 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3209 // commitment_signed (implying it will be in the latest remote commitment transaction).
3210 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3211 // and once they revoke the previous commitment transaction (allowing us to send a new
3212 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3213 let chanmon_cfgs = create_chanmon_cfgs(3);
3214 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3215 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3216 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3218 // Create some initial channels
3219 create_announced_chan_between_nodes(&nodes, 0, 1);
3220 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3222 let (payment_preimage, _payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3223 // Get the will-be-revoked local txn from nodes[2]
3224 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3225 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3226 // Revoke the old state
3227 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3229 let value = if use_dust {
3230 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3231 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3232 nodes[2].node.per_peer_state.read().unwrap().get(&nodes[1].node.get_our_node_id())
3233 .unwrap().lock().unwrap().channel_by_id.get(&chan_2.2).unwrap().context().holder_dust_limit_satoshis * 1000
3236 let (_, first_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3237 let (_, second_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3238 let (_, third_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3240 nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3241 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3242 check_added_monitors!(nodes[2], 1);
3243 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3244 assert!(updates.update_add_htlcs.is_empty());
3245 assert!(updates.update_fulfill_htlcs.is_empty());
3246 assert!(updates.update_fail_malformed_htlcs.is_empty());
3247 assert_eq!(updates.update_fail_htlcs.len(), 1);
3248 assert!(updates.update_fee.is_none());
3249 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3250 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3251 // Drop the last RAA from 3 -> 2
3253 nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3254 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3255 check_added_monitors!(nodes[2], 1);
3256 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3257 assert!(updates.update_add_htlcs.is_empty());
3258 assert!(updates.update_fulfill_htlcs.is_empty());
3259 assert!(updates.update_fail_malformed_htlcs.is_empty());
3260 assert_eq!(updates.update_fail_htlcs.len(), 1);
3261 assert!(updates.update_fee.is_none());
3262 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3263 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3264 check_added_monitors!(nodes[1], 1);
3265 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3266 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3267 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3268 check_added_monitors!(nodes[2], 1);
3270 nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3271 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3272 check_added_monitors!(nodes[2], 1);
3273 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3274 assert!(updates.update_add_htlcs.is_empty());
3275 assert!(updates.update_fulfill_htlcs.is_empty());
3276 assert!(updates.update_fail_malformed_htlcs.is_empty());
3277 assert_eq!(updates.update_fail_htlcs.len(), 1);
3278 assert!(updates.update_fee.is_none());
3279 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3280 // At this point first_payment_hash has dropped out of the latest two commitment
3281 // transactions that nodes[1] is tracking...
3282 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3283 check_added_monitors!(nodes[1], 1);
3284 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3285 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3286 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3287 check_added_monitors!(nodes[2], 1);
3289 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3290 // on nodes[2]'s RAA.
3291 let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3292 nodes[1].node.send_payment_with_route(&route, fourth_payment_hash,
3293 RecipientOnionFields::secret_only(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3294 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3295 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3296 check_added_monitors!(nodes[1], 0);
3299 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3300 // One monitor for the new revocation preimage, no second on as we won't generate a new
3301 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3302 check_added_monitors!(nodes[1], 1);
3303 let events = nodes[1].node.get_and_clear_pending_events();
3304 assert_eq!(events.len(), 2);
3306 Event::PendingHTLCsForwardable { .. } => { },
3307 _ => panic!("Unexpected event"),
3310 Event::HTLCHandlingFailed { .. } => { },
3311 _ => panic!("Unexpected event"),
3313 // Deliberately don't process the pending fail-back so they all fail back at once after
3314 // block connection just like the !deliver_bs_raa case
3317 let mut failed_htlcs = HashSet::new();
3318 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3320 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3321 check_added_monitors!(nodes[1], 1);
3322 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3324 let events = nodes[1].node.get_and_clear_pending_events();
3325 assert_eq!(events.len(), if deliver_bs_raa { 3 + nodes.len() - 1 } else { 4 + nodes.len() });
3327 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3328 _ => panic!("Unexepected event"),
3331 Event::PaymentPathFailed { ref payment_hash, .. } => {
3332 assert_eq!(*payment_hash, fourth_payment_hash);
3334 _ => panic!("Unexpected event"),
3337 Event::PaymentFailed { ref payment_hash, .. } => {
3338 assert_eq!(*payment_hash, fourth_payment_hash);
3340 _ => panic!("Unexpected event"),
3343 nodes[1].node.process_pending_htlc_forwards();
3344 check_added_monitors!(nodes[1], 1);
3346 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
3347 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3350 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3351 match nodes_2_event {
3352 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, .. } } => {
3353 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3354 assert_eq!(update_add_htlcs.len(), 1);
3355 assert!(update_fulfill_htlcs.is_empty());
3356 assert!(update_fail_htlcs.is_empty());
3357 assert!(update_fail_malformed_htlcs.is_empty());
3359 _ => panic!("Unexpected event"),
3363 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3364 match nodes_2_event {
3365 MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { msg: Some(msgs::ErrorMessage { channel_id, ref data }) }, node_id: _ } => {
3366 assert_eq!(channel_id, chan_2.2);
3367 assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3369 _ => panic!("Unexpected event"),
3372 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
3373 match nodes_0_event {
3374 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, .. } } => {
3375 assert!(update_add_htlcs.is_empty());
3376 assert_eq!(update_fail_htlcs.len(), 3);
3377 assert!(update_fulfill_htlcs.is_empty());
3378 assert!(update_fail_malformed_htlcs.is_empty());
3379 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3381 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3382 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3383 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3385 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3387 let events = nodes[0].node.get_and_clear_pending_events();
3388 assert_eq!(events.len(), 6);
3390 Event::PaymentPathFailed { ref payment_hash, ref failure, .. } => {
3391 assert!(failed_htlcs.insert(payment_hash.0));
3392 // If we delivered B's RAA we got an unknown preimage error, not something
3393 // that we should update our routing table for.
3394 if !deliver_bs_raa {
3395 if let PathFailure::OnPath { network_update: Some(_) } = failure { } else { panic!("Unexpected path failure") }
3398 _ => panic!("Unexpected event"),
3401 Event::PaymentFailed { ref payment_hash, .. } => {
3402 assert_eq!(*payment_hash, first_payment_hash);
3404 _ => panic!("Unexpected event"),
3407 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3408 assert!(failed_htlcs.insert(payment_hash.0));
3410 _ => panic!("Unexpected event"),
3413 Event::PaymentFailed { ref payment_hash, .. } => {
3414 assert_eq!(*payment_hash, second_payment_hash);
3416 _ => panic!("Unexpected event"),
3419 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3420 assert!(failed_htlcs.insert(payment_hash.0));
3422 _ => panic!("Unexpected event"),
3425 Event::PaymentFailed { ref payment_hash, .. } => {
3426 assert_eq!(*payment_hash, third_payment_hash);
3428 _ => panic!("Unexpected event"),
3431 _ => panic!("Unexpected event"),
3434 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
3436 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3437 _ => panic!("Unexpected event"),
3440 assert!(failed_htlcs.contains(&first_payment_hash.0));
3441 assert!(failed_htlcs.contains(&second_payment_hash.0));
3442 assert!(failed_htlcs.contains(&third_payment_hash.0));
3446 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3447 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3448 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3449 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3450 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3454 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3455 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3456 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3457 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3458 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3462 fn fail_backward_pending_htlc_upon_channel_failure() {
3463 let chanmon_cfgs = create_chanmon_cfgs(2);
3464 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3465 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3466 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3467 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
3469 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3471 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3472 nodes[0].node.send_payment_with_route(&route, payment_hash, RecipientOnionFields::secret_only(payment_secret),
3473 PaymentId(payment_hash.0)).unwrap();
3474 check_added_monitors!(nodes[0], 1);
3476 let payment_event = {
3477 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3478 assert_eq!(events.len(), 1);
3479 SendEvent::from_event(events.remove(0))
3481 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3482 assert_eq!(payment_event.msgs.len(), 1);
3485 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3486 let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3488 nodes[0].node.send_payment_with_route(&route, failed_payment_hash,
3489 RecipientOnionFields::secret_only(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3490 check_added_monitors!(nodes[0], 0);
3492 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3495 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3497 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3499 let secp_ctx = Secp256k1::new();
3500 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3501 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3502 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(
3503 &route.paths[0], 50_000, RecipientOnionFields::secret_only(payment_secret), current_height, &None).unwrap();
3504 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3505 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
3507 // Send a 0-msat update_add_htlc to fail the channel.
3508 let update_add_htlc = msgs::UpdateAddHTLC {
3514 onion_routing_packet,
3515 skimmed_fee_msat: None,
3516 blinding_point: None,
3518 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3520 let events = nodes[0].node.get_and_clear_pending_events();
3521 assert_eq!(events.len(), 3);
3522 // Check that Alice fails backward the pending HTLC from the second payment.
3524 Event::PaymentPathFailed { payment_hash, .. } => {
3525 assert_eq!(payment_hash, failed_payment_hash);
3527 _ => panic!("Unexpected event"),
3530 Event::PaymentFailed { payment_hash, .. } => {
3531 assert_eq!(payment_hash, failed_payment_hash);
3533 _ => panic!("Unexpected event"),
3536 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3537 assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3539 _ => panic!("Unexpected event {:?}", events[1]),
3541 check_closed_broadcast!(nodes[0], true);
3542 check_added_monitors!(nodes[0], 1);
3546 fn test_htlc_ignore_latest_remote_commitment() {
3547 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3548 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3549 let chanmon_cfgs = create_chanmon_cfgs(2);
3550 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3551 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3552 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3553 if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3554 // We rely on the ability to connect a block redundantly, which isn't allowed via
3555 // `chain::Listen`, so we never run the test if we randomly get assigned that
3559 create_announced_chan_between_nodes(&nodes, 0, 1);
3561 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3562 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3563 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3564 check_closed_broadcast!(nodes[0], true);
3565 check_added_monitors!(nodes[0], 1);
3566 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
3568 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3569 assert_eq!(node_txn.len(), 3);
3570 assert_eq!(node_txn[0].txid(), node_txn[1].txid());
3572 let block = create_dummy_block(nodes[1].best_block_hash(), 42, vec![node_txn[0].clone(), node_txn[1].clone()]);
3573 connect_block(&nodes[1], &block);
3574 check_closed_broadcast!(nodes[1], true);
3575 check_added_monitors!(nodes[1], 1);
3576 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
3578 // Duplicate the connect_block call since this may happen due to other listeners
3579 // registering new transactions
3580 connect_block(&nodes[1], &block);
3584 fn test_force_close_fail_back() {
3585 // Check which HTLCs are failed-backwards on channel force-closure
3586 let chanmon_cfgs = create_chanmon_cfgs(3);
3587 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3588 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3589 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3590 create_announced_chan_between_nodes(&nodes, 0, 1);
3591 create_announced_chan_between_nodes(&nodes, 1, 2);
3593 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3595 let mut payment_event = {
3596 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
3597 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3598 check_added_monitors!(nodes[0], 1);
3600 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3601 assert_eq!(events.len(), 1);
3602 SendEvent::from_event(events.remove(0))
3605 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3606 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3608 expect_pending_htlcs_forwardable!(nodes[1]);
3610 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3611 assert_eq!(events_2.len(), 1);
3612 payment_event = SendEvent::from_event(events_2.remove(0));
3613 assert_eq!(payment_event.msgs.len(), 1);
3615 check_added_monitors!(nodes[1], 1);
3616 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3617 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3618 check_added_monitors!(nodes[2], 1);
3619 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3621 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3622 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3623 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3625 nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3626 check_closed_broadcast!(nodes[2], true);
3627 check_added_monitors!(nodes[2], 1);
3628 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
3630 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3631 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3632 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3633 // back to nodes[1] upon timeout otherwise.
3634 assert_eq!(node_txn.len(), 1);
3638 mine_transaction(&nodes[1], &tx);
3640 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3641 check_closed_broadcast!(nodes[1], true);
3642 check_added_monitors!(nodes[1], 1);
3643 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
3645 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3647 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3648 .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);
3650 mine_transaction(&nodes[2], &tx);
3651 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3652 assert_eq!(node_txn.len(), 1);
3653 assert_eq!(node_txn[0].input.len(), 1);
3654 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3655 assert_eq!(node_txn[0].lock_time, LockTime::ZERO); // Must be an HTLC-Success
3656 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3658 check_spends!(node_txn[0], tx);
3662 fn test_dup_events_on_peer_disconnect() {
3663 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3664 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3665 // as we used to generate the event immediately upon receipt of the payment preimage in the
3666 // update_fulfill_htlc message.
3668 let chanmon_cfgs = create_chanmon_cfgs(2);
3669 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3670 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3671 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3672 create_announced_chan_between_nodes(&nodes, 0, 1);
3674 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3676 nodes[1].node.claim_funds(payment_preimage);
3677 expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3678 check_added_monitors!(nodes[1], 1);
3679 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3680 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3681 expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
3683 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3684 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3686 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3687 reconnect_args.pending_htlc_claims.0 = 1;
3688 reconnect_nodes(reconnect_args);
3689 expect_payment_path_successful!(nodes[0]);
3693 fn test_peer_disconnected_before_funding_broadcasted() {
3694 // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3695 // before the funding transaction has been broadcasted.
3696 let chanmon_cfgs = create_chanmon_cfgs(2);
3697 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3698 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3699 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3701 // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3702 // broadcasted, even though it's created by `nodes[0]`.
3703 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();
3704 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3705 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
3706 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3707 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
3709 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3710 assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3712 assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3714 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3715 assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3717 // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3718 // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3721 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3724 // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3725 // disconnected before the funding transaction was broadcasted.
3726 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3727 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3729 check_closed_event!(&nodes[0], 2, ClosureReason::DisconnectedPeer, true
3730 , [nodes[1].node.get_our_node_id()], 1000000);
3731 check_closed_event!(&nodes[1], 1, ClosureReason::DisconnectedPeer, false
3732 , [nodes[0].node.get_our_node_id()], 1000000);
3736 fn test_simple_peer_disconnect() {
3737 // Test that we can reconnect when there are no lost messages
3738 let chanmon_cfgs = create_chanmon_cfgs(3);
3739 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3740 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3741 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3742 create_announced_chan_between_nodes(&nodes, 0, 1);
3743 create_announced_chan_between_nodes(&nodes, 1, 2);
3745 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3746 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3747 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3748 reconnect_args.send_channel_ready = (true, true);
3749 reconnect_nodes(reconnect_args);
3751 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3752 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3753 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3754 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3756 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3757 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3758 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3760 let (payment_preimage_3, payment_hash_3, ..) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3761 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3762 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3763 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3765 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3766 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3768 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3769 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3771 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3772 reconnect_args.pending_cell_htlc_fails.0 = 1;
3773 reconnect_args.pending_cell_htlc_claims.0 = 1;
3774 reconnect_nodes(reconnect_args);
3776 let events = nodes[0].node.get_and_clear_pending_events();
3777 assert_eq!(events.len(), 4);
3779 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3780 assert_eq!(payment_preimage, payment_preimage_3);
3781 assert_eq!(payment_hash, payment_hash_3);
3783 _ => panic!("Unexpected event"),
3786 Event::PaymentPathSuccessful { .. } => {},
3787 _ => panic!("Unexpected event"),
3790 Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3791 assert_eq!(payment_hash, payment_hash_5);
3792 assert!(payment_failed_permanently);
3794 _ => panic!("Unexpected event"),
3797 Event::PaymentFailed { payment_hash, .. } => {
3798 assert_eq!(payment_hash, payment_hash_5);
3800 _ => panic!("Unexpected event"),
3803 check_added_monitors(&nodes[0], 1);
3805 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3806 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3809 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3810 // Test that we can reconnect when in-flight HTLC updates get dropped
3811 let chanmon_cfgs = create_chanmon_cfgs(2);
3812 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3813 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3814 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3816 let mut as_channel_ready = None;
3817 let channel_id = if messages_delivered == 0 {
3818 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3819 as_channel_ready = Some(channel_ready);
3820 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3821 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3822 // it before the channel_reestablish message.
3825 create_announced_chan_between_nodes(&nodes, 0, 1).2
3828 let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3830 let payment_event = {
3831 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
3832 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3833 check_added_monitors!(nodes[0], 1);
3835 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3836 assert_eq!(events.len(), 1);
3837 SendEvent::from_event(events.remove(0))
3839 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3841 if messages_delivered < 2 {
3842 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3844 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3845 if messages_delivered >= 3 {
3846 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3847 check_added_monitors!(nodes[1], 1);
3848 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3850 if messages_delivered >= 4 {
3851 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3852 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3853 check_added_monitors!(nodes[0], 1);
3855 if messages_delivered >= 5 {
3856 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3857 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3858 // No commitment_signed so get_event_msg's assert(len == 1) passes
3859 check_added_monitors!(nodes[0], 1);
3861 if messages_delivered >= 6 {
3862 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3863 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3864 check_added_monitors!(nodes[1], 1);
3871 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3872 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3873 if messages_delivered < 3 {
3874 if simulate_broken_lnd {
3875 // lnd has a long-standing bug where they send a channel_ready prior to a
3876 // channel_reestablish if you reconnect prior to channel_ready time.
3878 // Here we simulate that behavior, delivering a channel_ready immediately on
3879 // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3880 // in `reconnect_nodes` but we currently don't fail based on that.
3882 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3883 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3885 // Even if the channel_ready messages get exchanged, as long as nothing further was
3886 // received on either side, both sides will need to resend them.
3887 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3888 reconnect_args.send_channel_ready = (true, true);
3889 reconnect_args.pending_htlc_adds.1 = 1;
3890 reconnect_nodes(reconnect_args);
3891 } else if messages_delivered == 3 {
3892 // nodes[0] still wants its RAA + commitment_signed
3893 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3894 reconnect_args.pending_responding_commitment_signed.0 = true;
3895 reconnect_args.pending_raa.0 = true;
3896 reconnect_nodes(reconnect_args);
3897 } else if messages_delivered == 4 {
3898 // nodes[0] still wants its commitment_signed
3899 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3900 reconnect_args.pending_responding_commitment_signed.0 = true;
3901 reconnect_nodes(reconnect_args);
3902 } else if messages_delivered == 5 {
3903 // nodes[1] still wants its final RAA
3904 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3905 reconnect_args.pending_raa.1 = true;
3906 reconnect_nodes(reconnect_args);
3907 } else if messages_delivered == 6 {
3908 // Everything was delivered...
3909 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3912 let events_1 = nodes[1].node.get_and_clear_pending_events();
3913 if messages_delivered == 0 {
3914 assert_eq!(events_1.len(), 2);
3916 Event::ChannelReady { .. } => { },
3917 _ => panic!("Unexpected event"),
3920 Event::PendingHTLCsForwardable { .. } => { },
3921 _ => panic!("Unexpected event"),
3924 assert_eq!(events_1.len(), 1);
3926 Event::PendingHTLCsForwardable { .. } => { },
3927 _ => panic!("Unexpected event"),
3931 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3932 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3933 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3935 nodes[1].node.process_pending_htlc_forwards();
3937 let events_2 = nodes[1].node.get_and_clear_pending_events();
3938 assert_eq!(events_2.len(), 1);
3940 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
3941 assert_eq!(payment_hash_1, *payment_hash);
3942 assert_eq!(amount_msat, 1_000_000);
3943 assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3944 assert_eq!(via_channel_id, Some(channel_id));
3946 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3947 assert!(payment_preimage.is_none());
3948 assert_eq!(payment_secret_1, *payment_secret);
3950 _ => panic!("expected PaymentPurpose::InvoicePayment")
3953 _ => panic!("Unexpected event"),
3956 nodes[1].node.claim_funds(payment_preimage_1);
3957 check_added_monitors!(nodes[1], 1);
3958 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3960 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3961 assert_eq!(events_3.len(), 1);
3962 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3963 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3964 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3965 assert!(updates.update_add_htlcs.is_empty());
3966 assert!(updates.update_fail_htlcs.is_empty());
3967 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3968 assert!(updates.update_fail_malformed_htlcs.is_empty());
3969 assert!(updates.update_fee.is_none());
3970 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3972 _ => panic!("Unexpected event"),
3975 if messages_delivered >= 1 {
3976 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3978 let events_4 = nodes[0].node.get_and_clear_pending_events();
3979 assert_eq!(events_4.len(), 1);
3981 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3982 assert_eq!(payment_preimage_1, *payment_preimage);
3983 assert_eq!(payment_hash_1, *payment_hash);
3985 _ => panic!("Unexpected event"),
3988 if messages_delivered >= 2 {
3989 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3990 check_added_monitors!(nodes[0], 1);
3991 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3993 if messages_delivered >= 3 {
3994 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3995 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3996 check_added_monitors!(nodes[1], 1);
3998 if messages_delivered >= 4 {
3999 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
4000 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4001 // No commitment_signed so get_event_msg's assert(len == 1) passes
4002 check_added_monitors!(nodes[1], 1);
4004 if messages_delivered >= 5 {
4005 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4006 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4007 check_added_monitors!(nodes[0], 1);
4014 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4015 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4016 if messages_delivered < 2 {
4017 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4018 reconnect_args.pending_htlc_claims.0 = 1;
4019 reconnect_nodes(reconnect_args);
4020 if messages_delivered < 1 {
4021 expect_payment_sent!(nodes[0], payment_preimage_1);
4023 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4025 } else if messages_delivered == 2 {
4026 // nodes[0] still wants its RAA + commitment_signed
4027 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4028 reconnect_args.pending_responding_commitment_signed.1 = true;
4029 reconnect_args.pending_raa.1 = true;
4030 reconnect_nodes(reconnect_args);
4031 } else if messages_delivered == 3 {
4032 // nodes[0] still wants its commitment_signed
4033 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4034 reconnect_args.pending_responding_commitment_signed.1 = true;
4035 reconnect_nodes(reconnect_args);
4036 } else if messages_delivered == 4 {
4037 // nodes[1] still wants its final RAA
4038 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4039 reconnect_args.pending_raa.0 = true;
4040 reconnect_nodes(reconnect_args);
4041 } else if messages_delivered == 5 {
4042 // Everything was delivered...
4043 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
4046 if messages_delivered == 1 || messages_delivered == 2 {
4047 expect_payment_path_successful!(nodes[0]);
4049 if messages_delivered <= 5 {
4050 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4051 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4053 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
4055 if messages_delivered > 2 {
4056 expect_payment_path_successful!(nodes[0]);
4059 // Channel should still work fine...
4060 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4061 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
4062 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4066 fn test_drop_messages_peer_disconnect_a() {
4067 do_test_drop_messages_peer_disconnect(0, true);
4068 do_test_drop_messages_peer_disconnect(0, false);
4069 do_test_drop_messages_peer_disconnect(1, false);
4070 do_test_drop_messages_peer_disconnect(2, false);
4074 fn test_drop_messages_peer_disconnect_b() {
4075 do_test_drop_messages_peer_disconnect(3, false);
4076 do_test_drop_messages_peer_disconnect(4, false);
4077 do_test_drop_messages_peer_disconnect(5, false);
4078 do_test_drop_messages_peer_disconnect(6, false);
4082 fn test_channel_ready_without_best_block_updated() {
4083 // Previously, if we were offline when a funding transaction was locked in, and then we came
4084 // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
4085 // generate a channel_ready until a later best_block_updated. This tests that we generate the
4086 // channel_ready immediately instead.
4087 let chanmon_cfgs = create_chanmon_cfgs(2);
4088 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4089 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4090 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4091 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
4093 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
4095 let conf_height = nodes[0].best_block_info().1 + 1;
4096 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4097 let block_txn = [funding_tx];
4098 let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
4099 let conf_block_header = nodes[0].get_block_header(conf_height);
4100 nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
4102 // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4103 let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4104 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4108 fn test_channel_monitor_skipping_block_when_channel_manager_is_leading() {
4109 let chanmon_cfgs = create_chanmon_cfgs(2);
4110 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4111 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4112 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4114 // Let channel_manager get ahead of chain_monitor by 1 block.
4115 // This is to emulate race-condition where newly added channel_monitor skips processing 1 block,
4116 // in case where client calls block_connect on channel_manager first and then on chain_monitor.
4117 let height_1 = nodes[0].best_block_info().1 + 1;
4118 let mut block_1 = create_dummy_block(nodes[0].best_block_hash(), height_1, Vec::new());
4120 nodes[0].blocks.lock().unwrap().push((block_1.clone(), height_1));
4121 nodes[0].node.block_connected(&block_1, height_1);
4123 // Create channel, and it gets added to chain_monitor in funding_created.
4124 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
4126 // Now, newly added channel_monitor in chain_monitor hasn't processed block_1,
4127 // but it's best_block is block_1, since that was populated by channel_manager, and channel_manager
4128 // was running ahead of chain_monitor at the time of funding_created.
4129 // Later on, subsequent blocks are connected to both channel_manager and chain_monitor.
4130 // Hence, this channel's channel_monitor skipped block_1, directly tries to process subsequent blocks.
4131 confirm_transaction_at(&nodes[0], &funding_tx, nodes[0].best_block_info().1 + 1);
4132 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4134 // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4135 let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4136 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4140 fn test_channel_monitor_skipping_block_when_channel_manager_is_lagging() {
4141 let chanmon_cfgs = create_chanmon_cfgs(2);
4142 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4143 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4144 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4146 // Let chain_monitor get ahead of channel_manager by 1 block.
4147 // This is to emulate race-condition where newly added channel_monitor skips processing 1 block,
4148 // in case where client calls block_connect on chain_monitor first and then on channel_manager.
4149 let height_1 = nodes[0].best_block_info().1 + 1;
4150 let mut block_1 = create_dummy_block(nodes[0].best_block_hash(), height_1, Vec::new());
4152 nodes[0].blocks.lock().unwrap().push((block_1.clone(), height_1));
4153 nodes[0].chain_monitor.chain_monitor.block_connected(&block_1, height_1);
4155 // Create channel, and it gets added to chain_monitor in funding_created.
4156 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
4158 // channel_manager can't really skip block_1, it should get it eventually.
4159 nodes[0].node.block_connected(&block_1, height_1);
4161 // Now, newly added channel_monitor in chain_monitor hasn't processed block_1, it's best_block is
4162 // the block before block_1, since that was populated by channel_manager, and channel_manager was
4163 // running behind at the time of funding_created.
4164 // Later on, subsequent blocks are connected to both channel_manager and chain_monitor.
4165 // Hence, this channel's channel_monitor skipped block_1, directly tries to process subsequent blocks.
4166 confirm_transaction_at(&nodes[0], &funding_tx, nodes[0].best_block_info().1 + 1);
4167 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4169 // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4170 let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4171 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4175 fn test_drop_messages_peer_disconnect_dual_htlc() {
4176 // Test that we can handle reconnecting when both sides of a channel have pending
4177 // commitment_updates when we disconnect.
4178 let chanmon_cfgs = create_chanmon_cfgs(2);
4179 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4180 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4181 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4182 create_announced_chan_between_nodes(&nodes, 0, 1);
4184 let (payment_preimage_1, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
4186 // Now try to send a second payment which will fail to send
4187 let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4188 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
4189 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
4190 check_added_monitors!(nodes[0], 1);
4192 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4193 assert_eq!(events_1.len(), 1);
4195 MessageSendEvent::UpdateHTLCs { .. } => {},
4196 _ => panic!("Unexpected event"),
4199 nodes[1].node.claim_funds(payment_preimage_1);
4200 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4201 check_added_monitors!(nodes[1], 1);
4203 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4204 assert_eq!(events_2.len(), 1);
4206 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 } } => {
4207 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4208 assert!(update_add_htlcs.is_empty());
4209 assert_eq!(update_fulfill_htlcs.len(), 1);
4210 assert!(update_fail_htlcs.is_empty());
4211 assert!(update_fail_malformed_htlcs.is_empty());
4212 assert!(update_fee.is_none());
4214 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4215 let events_3 = nodes[0].node.get_and_clear_pending_events();
4216 assert_eq!(events_3.len(), 1);
4218 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4219 assert_eq!(*payment_preimage, payment_preimage_1);
4220 assert_eq!(*payment_hash, payment_hash_1);
4222 _ => panic!("Unexpected event"),
4225 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4226 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4227 // No commitment_signed so get_event_msg's assert(len == 1) passes
4228 check_added_monitors!(nodes[0], 1);
4230 _ => panic!("Unexpected event"),
4233 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4234 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4236 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
4237 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
4239 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4240 assert_eq!(reestablish_1.len(), 1);
4241 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
4242 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
4244 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4245 assert_eq!(reestablish_2.len(), 1);
4247 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4248 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4249 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4250 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4252 assert!(as_resp.0.is_none());
4253 assert!(bs_resp.0.is_none());
4255 assert!(bs_resp.1.is_none());
4256 assert!(bs_resp.2.is_none());
4258 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4260 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4261 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4262 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4263 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4264 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4265 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4266 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4267 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4268 // No commitment_signed so get_event_msg's assert(len == 1) passes
4269 check_added_monitors!(nodes[1], 1);
4271 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4272 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4273 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4274 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4275 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4276 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4277 assert!(bs_second_commitment_signed.update_fee.is_none());
4278 check_added_monitors!(nodes[1], 1);
4280 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4281 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4282 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4283 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4284 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4285 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4286 assert!(as_commitment_signed.update_fee.is_none());
4287 check_added_monitors!(nodes[0], 1);
4289 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4290 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4291 // No commitment_signed so get_event_msg's assert(len == 1) passes
4292 check_added_monitors!(nodes[0], 1);
4294 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4295 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4296 // No commitment_signed so get_event_msg's assert(len == 1) passes
4297 check_added_monitors!(nodes[1], 1);
4299 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4300 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4301 check_added_monitors!(nodes[1], 1);
4303 expect_pending_htlcs_forwardable!(nodes[1]);
4305 let events_5 = nodes[1].node.get_and_clear_pending_events();
4306 assert_eq!(events_5.len(), 1);
4308 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4309 assert_eq!(payment_hash_2, *payment_hash);
4311 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4312 assert!(payment_preimage.is_none());
4313 assert_eq!(payment_secret_2, *payment_secret);
4315 _ => panic!("expected PaymentPurpose::InvoicePayment")
4318 _ => panic!("Unexpected event"),
4321 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4322 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4323 check_added_monitors!(nodes[0], 1);
4325 expect_payment_path_successful!(nodes[0]);
4326 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4329 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4330 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4331 // to avoid our counterparty failing the channel.
4332 let chanmon_cfgs = create_chanmon_cfgs(2);
4333 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4334 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4335 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4337 create_announced_chan_between_nodes(&nodes, 0, 1);
4339 let our_payment_hash = if send_partial_mpp {
4340 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4341 // Use the utility function send_payment_along_path to send the payment with MPP data which
4342 // indicates there are more HTLCs coming.
4343 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.
4344 let payment_id = PaymentId([42; 32]);
4345 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
4346 RecipientOnionFields::secret_only(payment_secret), payment_id, &route).unwrap();
4347 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
4348 RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id,
4349 &None, session_privs[0]).unwrap();
4350 check_added_monitors!(nodes[0], 1);
4351 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4352 assert_eq!(events.len(), 1);
4353 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4354 // hop should *not* yet generate any PaymentClaimable event(s).
4355 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4358 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4361 let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
4362 connect_block(&nodes[0], &block);
4363 connect_block(&nodes[1], &block);
4364 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4365 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4366 block.header.prev_blockhash = block.block_hash();
4367 connect_block(&nodes[0], &block);
4368 connect_block(&nodes[1], &block);
4371 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4373 check_added_monitors!(nodes[1], 1);
4374 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4375 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4376 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4377 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4378 assert!(htlc_timeout_updates.update_fee.is_none());
4380 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4381 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4382 // 100_000 msat as u64, followed by the height at which we failed back above
4383 let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4384 expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4385 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4389 fn test_htlc_timeout() {
4390 do_test_htlc_timeout(true);
4391 do_test_htlc_timeout(false);
4394 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4395 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4396 let chanmon_cfgs = create_chanmon_cfgs(3);
4397 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4398 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4399 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4400 create_announced_chan_between_nodes(&nodes, 0, 1);
4401 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4403 // Make sure all nodes are at the same starting height
4404 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4405 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4406 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4408 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4409 let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4410 nodes[1].node.send_payment_with_route(&route, first_payment_hash,
4411 RecipientOnionFields::secret_only(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4412 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4413 check_added_monitors!(nodes[1], 1);
4415 // Now attempt to route a second payment, which should be placed in the holding cell
4416 let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4417 let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4418 sending_node.node.send_payment_with_route(&route, second_payment_hash,
4419 RecipientOnionFields::secret_only(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4421 check_added_monitors!(nodes[0], 1);
4422 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4423 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4424 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4425 expect_pending_htlcs_forwardable!(nodes[1]);
4427 check_added_monitors!(nodes[1], 0);
4429 connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4430 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4431 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4432 connect_blocks(&nodes[1], 1);
4435 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 }]);
4436 check_added_monitors!(nodes[1], 1);
4437 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4438 assert_eq!(fail_commit.len(), 1);
4439 match fail_commit[0] {
4440 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4441 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4442 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4444 _ => unreachable!(),
4446 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4448 expect_payment_failed!(nodes[1], second_payment_hash, false);
4453 fn test_holding_cell_htlc_add_timeouts() {
4454 do_test_holding_cell_htlc_add_timeouts(false);
4455 do_test_holding_cell_htlc_add_timeouts(true);
4458 macro_rules! check_spendable_outputs {
4459 ($node: expr, $keysinterface: expr) => {
4461 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4462 let mut txn = Vec::new();
4463 let mut all_outputs = Vec::new();
4464 let secp_ctx = Secp256k1::new();
4465 for event in events.drain(..) {
4467 Event::SpendableOutputs { mut outputs, channel_id: _ } => {
4468 for outp in outputs.drain(..) {
4469 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());
4470 all_outputs.push(outp);
4473 _ => panic!("Unexpected event"),
4476 if all_outputs.len() > 1 {
4477 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) {
4487 fn test_claim_sizeable_push_msat() {
4488 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4489 let chanmon_cfgs = create_chanmon_cfgs(2);
4490 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4491 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4492 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4494 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4495 nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4496 check_closed_broadcast!(nodes[1], true);
4497 check_added_monitors!(nodes[1], 1);
4498 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[0].node.get_our_node_id()], 100000);
4499 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4500 assert_eq!(node_txn.len(), 1);
4501 check_spends!(node_txn[0], chan.3);
4502 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
4504 mine_transaction(&nodes[1], &node_txn[0]);
4505 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4507 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4508 assert_eq!(spend_txn.len(), 1);
4509 assert_eq!(spend_txn[0].input.len(), 1);
4510 check_spends!(spend_txn[0], node_txn[0]);
4511 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4515 fn test_claim_on_remote_sizeable_push_msat() {
4516 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4517 // to_remote output is encumbered by a P2WPKH
4518 let chanmon_cfgs = create_chanmon_cfgs(2);
4519 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4520 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4521 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4523 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4524 nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4525 check_closed_broadcast!(nodes[0], true);
4526 check_added_monitors!(nodes[0], 1);
4527 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
4529 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4530 assert_eq!(node_txn.len(), 1);
4531 check_spends!(node_txn[0], chan.3);
4532 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
4534 mine_transaction(&nodes[1], &node_txn[0]);
4535 check_closed_broadcast!(nodes[1], true);
4536 check_added_monitors!(nodes[1], 1);
4537 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4538 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4540 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4541 assert_eq!(spend_txn.len(), 1);
4542 check_spends!(spend_txn[0], node_txn[0]);
4546 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4547 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4548 // to_remote output is encumbered by a P2WPKH
4550 let chanmon_cfgs = create_chanmon_cfgs(2);
4551 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4552 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4553 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4555 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4556 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4557 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4558 assert_eq!(revoked_local_txn[0].input.len(), 1);
4559 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4561 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4562 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4563 check_closed_broadcast!(nodes[1], true);
4564 check_added_monitors!(nodes[1], 1);
4565 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4567 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4568 mine_transaction(&nodes[1], &node_txn[0]);
4569 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4571 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4572 assert_eq!(spend_txn.len(), 3);
4573 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4574 check_spends!(spend_txn[1], node_txn[0]);
4575 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4579 fn test_static_spendable_outputs_preimage_tx() {
4580 let chanmon_cfgs = create_chanmon_cfgs(2);
4581 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4582 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4583 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4585 // Create some initial channels
4586 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4588 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4590 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4591 assert_eq!(commitment_tx[0].input.len(), 1);
4592 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4594 // Settle A's commitment tx on B's chain
4595 nodes[1].node.claim_funds(payment_preimage);
4596 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4597 check_added_monitors!(nodes[1], 1);
4598 mine_transaction(&nodes[1], &commitment_tx[0]);
4599 check_added_monitors!(nodes[1], 1);
4600 let events = nodes[1].node.get_and_clear_pending_msg_events();
4602 MessageSendEvent::UpdateHTLCs { .. } => {},
4603 _ => panic!("Unexpected event"),
4606 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4607 _ => panic!("Unexepected event"),
4610 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4611 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4612 assert_eq!(node_txn.len(), 1);
4613 check_spends!(node_txn[0], commitment_tx[0]);
4614 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4616 mine_transaction(&nodes[1], &node_txn[0]);
4617 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4618 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4620 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4621 assert_eq!(spend_txn.len(), 1);
4622 check_spends!(spend_txn[0], node_txn[0]);
4626 fn test_static_spendable_outputs_timeout_tx() {
4627 let chanmon_cfgs = create_chanmon_cfgs(2);
4628 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4629 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4630 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4632 // Create some initial channels
4633 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4635 // Rebalance the network a bit by relaying one payment through all the channels ...
4636 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4638 let (_, our_payment_hash, ..) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4640 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4641 assert_eq!(commitment_tx[0].input.len(), 1);
4642 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4644 // Settle A's commitment tx on B' chain
4645 mine_transaction(&nodes[1], &commitment_tx[0]);
4646 check_added_monitors!(nodes[1], 1);
4647 let events = nodes[1].node.get_and_clear_pending_msg_events();
4649 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4650 _ => panic!("Unexpected event"),
4652 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4654 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4655 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4656 assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4657 check_spends!(node_txn[0], commitment_tx[0].clone());
4658 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4660 mine_transaction(&nodes[1], &node_txn[0]);
4661 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4662 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4663 expect_payment_failed!(nodes[1], our_payment_hash, false);
4665 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4666 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4667 check_spends!(spend_txn[0], commitment_tx[0]);
4668 check_spends!(spend_txn[1], node_txn[0]);
4669 check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4673 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4674 let chanmon_cfgs = create_chanmon_cfgs(2);
4675 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4676 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4677 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4679 // Create some initial channels
4680 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4682 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4683 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4684 assert_eq!(revoked_local_txn[0].input.len(), 1);
4685 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4687 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4689 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4690 check_closed_broadcast!(nodes[1], true);
4691 check_added_monitors!(nodes[1], 1);
4692 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4694 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4695 assert_eq!(node_txn.len(), 1);
4696 assert_eq!(node_txn[0].input.len(), 2);
4697 check_spends!(node_txn[0], revoked_local_txn[0]);
4699 mine_transaction(&nodes[1], &node_txn[0]);
4700 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4702 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4703 assert_eq!(spend_txn.len(), 1);
4704 check_spends!(spend_txn[0], node_txn[0]);
4708 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4709 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4710 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4711 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4712 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4713 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4715 // Create some initial channels
4716 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4718 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4719 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4720 assert_eq!(revoked_local_txn[0].input.len(), 1);
4721 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4723 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4725 // A will generate HTLC-Timeout from revoked commitment tx
4726 mine_transaction(&nodes[0], &revoked_local_txn[0]);
4727 check_closed_broadcast!(nodes[0], true);
4728 check_added_monitors!(nodes[0], 1);
4729 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4730 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4732 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4733 assert_eq!(revoked_htlc_txn.len(), 1);
4734 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4735 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4736 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4737 assert_ne!(revoked_htlc_txn[0].lock_time, LockTime::ZERO); // HTLC-Timeout
4739 // B will generate justice tx from A's revoked commitment/HTLC tx
4740 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4741 check_closed_broadcast!(nodes[1], true);
4742 check_added_monitors!(nodes[1], 1);
4743 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4745 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4746 assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4747 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4748 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4749 // transactions next...
4750 assert_eq!(node_txn[0].input.len(), 3);
4751 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4753 assert_eq!(node_txn[1].input.len(), 2);
4754 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4755 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4756 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4758 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4759 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4762 mine_transaction(&nodes[1], &node_txn[1]);
4763 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4765 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4766 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4767 assert_eq!(spend_txn.len(), 1);
4768 assert_eq!(spend_txn[0].input.len(), 1);
4769 check_spends!(spend_txn[0], node_txn[1]);
4773 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4774 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4775 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4776 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4777 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4778 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4780 // Create some initial channels
4781 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4783 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4784 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4785 assert_eq!(revoked_local_txn[0].input.len(), 1);
4786 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4788 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4789 assert_eq!(revoked_local_txn[0].output.len(), 2);
4791 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4793 // B will generate HTLC-Success from revoked commitment tx
4794 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4795 check_closed_broadcast!(nodes[1], true);
4796 check_added_monitors!(nodes[1], 1);
4797 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4798 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4800 assert_eq!(revoked_htlc_txn.len(), 1);
4801 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4802 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4803 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4805 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4806 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4807 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4809 // A will generate justice tx from B's revoked commitment/HTLC tx
4810 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4811 check_closed_broadcast!(nodes[0], true);
4812 check_added_monitors!(nodes[0], 1);
4813 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4815 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4816 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4818 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4819 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4820 // transactions next...
4821 assert_eq!(node_txn[0].input.len(), 2);
4822 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4823 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4824 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4826 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4827 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4830 assert_eq!(node_txn[1].input.len(), 1);
4831 check_spends!(node_txn[1], revoked_htlc_txn[0]);
4833 mine_transaction(&nodes[0], &node_txn[1]);
4834 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4836 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4837 // didn't try to generate any new transactions.
4839 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4840 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4841 assert_eq!(spend_txn.len(), 3);
4842 assert_eq!(spend_txn[0].input.len(), 1);
4843 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4844 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4845 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4846 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4850 fn test_onchain_to_onchain_claim() {
4851 // Test that in case of channel closure, we detect the state of output and claim HTLC
4852 // on downstream peer's remote commitment tx.
4853 // First, have C claim an HTLC against its own latest commitment transaction.
4854 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4856 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4859 let chanmon_cfgs = create_chanmon_cfgs(3);
4860 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4861 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4862 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4864 // Create some initial channels
4865 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4866 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4868 // Ensure all nodes are at the same height
4869 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4870 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4871 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4872 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4874 // Rebalance the network a bit by relaying one payment through all the channels ...
4875 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4876 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4878 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4879 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4880 check_spends!(commitment_tx[0], chan_2.3);
4881 nodes[2].node.claim_funds(payment_preimage);
4882 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4883 check_added_monitors!(nodes[2], 1);
4884 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4885 assert!(updates.update_add_htlcs.is_empty());
4886 assert!(updates.update_fail_htlcs.is_empty());
4887 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4888 assert!(updates.update_fail_malformed_htlcs.is_empty());
4890 mine_transaction(&nodes[2], &commitment_tx[0]);
4891 check_closed_broadcast!(nodes[2], true);
4892 check_added_monitors!(nodes[2], 1);
4893 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4895 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4896 assert_eq!(c_txn.len(), 1);
4897 check_spends!(c_txn[0], commitment_tx[0]);
4898 assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4899 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4900 assert_eq!(c_txn[0].lock_time, LockTime::ZERO); // Success tx
4902 // 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
4903 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![commitment_tx[0].clone(), c_txn[0].clone()]));
4904 check_added_monitors!(nodes[1], 1);
4905 let events = nodes[1].node.get_and_clear_pending_events();
4906 assert_eq!(events.len(), 2);
4908 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4909 _ => panic!("Unexpected event"),
4912 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
4913 assert_eq!(fee_earned_msat, Some(1000));
4914 assert_eq!(prev_channel_id, Some(chan_1.2));
4915 assert_eq!(claim_from_onchain_tx, true);
4916 assert_eq!(next_channel_id, Some(chan_2.2));
4917 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
4919 _ => panic!("Unexpected event"),
4921 check_added_monitors!(nodes[1], 1);
4922 let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4923 assert_eq!(msg_events.len(), 3);
4924 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut msg_events);
4925 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut msg_events);
4927 match nodes_2_event {
4928 MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { .. }, node_id: _ } => {},
4929 _ => panic!("Unexpected event"),
4932 match nodes_0_event {
4933 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, .. } } => {
4934 assert!(update_add_htlcs.is_empty());
4935 assert!(update_fail_htlcs.is_empty());
4936 assert_eq!(update_fulfill_htlcs.len(), 1);
4937 assert!(update_fail_malformed_htlcs.is_empty());
4938 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4940 _ => panic!("Unexpected event"),
4943 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
4944 match msg_events[0] {
4945 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4946 _ => panic!("Unexpected event"),
4949 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4950 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4951 mine_transaction(&nodes[1], &commitment_tx[0]);
4952 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4953 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4954 // ChannelMonitor: HTLC-Success tx
4955 assert_eq!(b_txn.len(), 1);
4956 check_spends!(b_txn[0], commitment_tx[0]);
4957 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4958 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4959 assert_eq!(b_txn[0].lock_time.to_consensus_u32(), nodes[1].best_block_info().1); // Success tx
4961 check_closed_broadcast!(nodes[1], true);
4962 check_added_monitors!(nodes[1], 1);
4966 fn test_duplicate_payment_hash_one_failure_one_success() {
4967 // Topology : A --> B --> C --> D
4968 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4969 // Note that because C will refuse to generate two payment secrets for the same payment hash,
4970 // we forward one of the payments onwards to D.
4971 let chanmon_cfgs = create_chanmon_cfgs(4);
4972 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4973 // When this test was written, the default base fee floated based on the HTLC count.
4974 // It is now fixed, so we simply set the fee to the expected value here.
4975 let mut config = test_default_channel_config();
4976 config.channel_config.forwarding_fee_base_msat = 196;
4977 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4978 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4979 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4981 create_announced_chan_between_nodes(&nodes, 0, 1);
4982 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4983 create_announced_chan_between_nodes(&nodes, 2, 3);
4985 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4986 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4987 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4988 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4989 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4991 let (our_payment_preimage, duplicate_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
4993 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
4994 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4995 // script push size limit so that the below script length checks match
4996 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
4997 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV - 40)
4998 .with_bolt11_features(nodes[3].node.bolt11_invoice_features()).unwrap();
4999 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000);
5000 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
5002 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5003 assert_eq!(commitment_txn[0].input.len(), 1);
5004 check_spends!(commitment_txn[0], chan_2.3);
5006 mine_transaction(&nodes[1], &commitment_txn[0]);
5007 check_closed_broadcast!(nodes[1], true);
5008 check_added_monitors!(nodes[1], 1);
5009 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
5010 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
5012 let htlc_timeout_tx;
5013 { // Extract one of the two HTLC-Timeout transaction
5014 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5015 // ChannelMonitor: timeout tx * 2-or-3
5016 assert!(node_txn.len() == 2 || node_txn.len() == 3);
5018 check_spends!(node_txn[0], commitment_txn[0]);
5019 assert_eq!(node_txn[0].input.len(), 1);
5020 assert_eq!(node_txn[0].output.len(), 1);
5022 if node_txn.len() > 2 {
5023 check_spends!(node_txn[1], commitment_txn[0]);
5024 assert_eq!(node_txn[1].input.len(), 1);
5025 assert_eq!(node_txn[1].output.len(), 1);
5026 assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
5028 check_spends!(node_txn[2], commitment_txn[0]);
5029 assert_eq!(node_txn[2].input.len(), 1);
5030 assert_eq!(node_txn[2].output.len(), 1);
5031 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
5033 check_spends!(node_txn[1], commitment_txn[0]);
5034 assert_eq!(node_txn[1].input.len(), 1);
5035 assert_eq!(node_txn[1].output.len(), 1);
5036 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
5039 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5040 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5041 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
5042 // (with value 900 sats) will be claimed in the below `claim_funds` call.
5043 if node_txn.len() > 2 {
5044 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5045 htlc_timeout_tx = if node_txn[2].output[0].value < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
5047 htlc_timeout_tx = if node_txn[0].output[0].value < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
5051 nodes[2].node.claim_funds(our_payment_preimage);
5052 expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
5054 mine_transaction(&nodes[2], &commitment_txn[0]);
5055 check_added_monitors!(nodes[2], 2);
5056 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5057 let events = nodes[2].node.get_and_clear_pending_msg_events();
5059 MessageSendEvent::UpdateHTLCs { .. } => {},
5060 _ => panic!("Unexpected event"),
5063 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5064 _ => panic!("Unexepected event"),
5066 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5067 assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
5068 check_spends!(htlc_success_txn[0], commitment_txn[0]);
5069 check_spends!(htlc_success_txn[1], commitment_txn[0]);
5070 assert_eq!(htlc_success_txn[0].input.len(), 1);
5071 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5072 assert_eq!(htlc_success_txn[1].input.len(), 1);
5073 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5074 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5075 assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5077 mine_transaction(&nodes[1], &htlc_timeout_tx);
5078 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5079 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 }]);
5080 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5081 assert!(htlc_updates.update_add_htlcs.is_empty());
5082 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5083 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5084 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5085 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5086 check_added_monitors!(nodes[1], 1);
5088 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5089 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5091 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5093 expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5095 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5096 mine_transaction(&nodes[1], &htlc_success_txn[1]);
5097 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
5098 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5099 assert!(updates.update_add_htlcs.is_empty());
5100 assert!(updates.update_fail_htlcs.is_empty());
5101 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5102 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5103 assert!(updates.update_fail_malformed_htlcs.is_empty());
5104 check_added_monitors!(nodes[1], 1);
5106 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5107 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5108 expect_payment_sent(&nodes[0], our_payment_preimage, None, true, true);
5112 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5113 let chanmon_cfgs = create_chanmon_cfgs(2);
5114 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5115 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5116 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5118 // Create some initial channels
5119 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5121 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
5122 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5123 assert_eq!(local_txn.len(), 1);
5124 assert_eq!(local_txn[0].input.len(), 1);
5125 check_spends!(local_txn[0], chan_1.3);
5127 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5128 nodes[1].node.claim_funds(payment_preimage);
5129 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
5130 check_added_monitors!(nodes[1], 1);
5132 mine_transaction(&nodes[1], &local_txn[0]);
5133 check_added_monitors!(nodes[1], 1);
5134 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
5135 let events = nodes[1].node.get_and_clear_pending_msg_events();
5137 MessageSendEvent::UpdateHTLCs { .. } => {},
5138 _ => panic!("Unexpected event"),
5141 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5142 _ => panic!("Unexepected event"),
5145 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5146 assert_eq!(node_txn.len(), 1);
5147 assert_eq!(node_txn[0].input.len(), 1);
5148 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5149 check_spends!(node_txn[0], local_txn[0]);
5153 mine_transaction(&nodes[1], &node_tx);
5154 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5156 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5157 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5158 assert_eq!(spend_txn.len(), 1);
5159 assert_eq!(spend_txn[0].input.len(), 1);
5160 check_spends!(spend_txn[0], node_tx);
5161 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5164 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5165 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5166 // unrevoked commitment transaction.
5167 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5168 // a remote RAA before they could be failed backwards (and combinations thereof).
5169 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5170 // use the same payment hashes.
5171 // Thus, we use a six-node network:
5176 // And test where C fails back to A/B when D announces its latest commitment transaction
5177 let chanmon_cfgs = create_chanmon_cfgs(6);
5178 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5179 // When this test was written, the default base fee floated based on the HTLC count.
5180 // It is now fixed, so we simply set the fee to the expected value here.
5181 let mut config = test_default_channel_config();
5182 config.channel_config.forwarding_fee_base_msat = 196;
5183 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5184 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5185 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5187 let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2);
5188 let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5189 let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5190 let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
5191 let chan_3_5 = create_announced_chan_between_nodes(&nodes, 3, 5);
5193 // Rebalance and check output sanity...
5194 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5195 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5196 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
5198 let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
5199 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().context().holder_dust_limit_satoshis;
5201 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
5203 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
5204 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5206 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
5208 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
5210 let (_, payment_hash_3, ..) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5212 let (_, payment_hash_4, ..) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5213 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5215 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());
5217 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());
5220 let (_, payment_hash_5, ..) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5222 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5223 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
5226 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
5228 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5229 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());
5231 // Double-check that six of the new HTLC were added
5232 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5233 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5234 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5235 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5237 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5238 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5239 nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5240 nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5241 nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5242 nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5243 check_added_monitors!(nodes[4], 0);
5245 let failed_destinations = vec![
5246 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5247 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5248 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5249 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5251 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5252 check_added_monitors!(nodes[4], 1);
5254 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5255 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5256 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5257 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5258 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5259 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5261 // Fail 3rd below-dust and 7th above-dust HTLCs
5262 nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5263 nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5264 check_added_monitors!(nodes[5], 0);
5266 let failed_destinations_2 = vec![
5267 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5268 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5270 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5271 check_added_monitors!(nodes[5], 1);
5273 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5274 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5275 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5276 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5278 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5280 // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5281 let failed_destinations_3 = vec![
5282 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5283 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5284 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5285 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5286 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5287 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5289 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5290 check_added_monitors!(nodes[3], 1);
5291 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5292 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5293 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5294 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5295 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5296 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5297 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5298 if deliver_last_raa {
5299 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5301 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5304 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5305 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5306 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5307 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5309 // We now broadcast the latest commitment transaction, which *should* result in failures for
5310 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5311 // the non-broadcast above-dust HTLCs.
5313 // Alternatively, we may broadcast the previous commitment transaction, which should only
5314 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5315 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5317 if announce_latest {
5318 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5320 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5322 let events = nodes[2].node.get_and_clear_pending_events();
5323 let close_event = if deliver_last_raa {
5324 assert_eq!(events.len(), 2 + 6);
5325 events.last().clone().unwrap()
5327 assert_eq!(events.len(), 1);
5328 events.last().clone().unwrap()
5331 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5332 _ => panic!("Unexpected event"),
5335 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5336 check_closed_broadcast!(nodes[2], true);
5337 if deliver_last_raa {
5338 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5340 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();
5341 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5343 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5344 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5346 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5349 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5351 check_added_monitors!(nodes[2], 3);
5353 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5354 assert_eq!(cs_msgs.len(), 2);
5355 let mut a_done = false;
5356 for msg in cs_msgs {
5358 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5359 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5360 // should be failed-backwards here.
5361 let target = if *node_id == nodes[0].node.get_our_node_id() {
5362 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5363 for htlc in &updates.update_fail_htlcs {
5364 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 });
5366 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5371 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5372 for htlc in &updates.update_fail_htlcs {
5373 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5375 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5376 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5379 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5380 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5381 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5382 if announce_latest {
5383 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5384 if *node_id == nodes[0].node.get_our_node_id() {
5385 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5388 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5390 _ => panic!("Unexpected event"),
5394 let as_events = nodes[0].node.get_and_clear_pending_events();
5395 assert_eq!(as_events.len(), if announce_latest { 10 } else { 6 });
5396 let mut as_failds = HashSet::new();
5397 let mut as_updates = 0;
5398 for event in as_events.iter() {
5399 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5400 assert!(as_failds.insert(*payment_hash));
5401 if *payment_hash != payment_hash_2 {
5402 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5404 assert!(!payment_failed_permanently);
5406 if let PathFailure::OnPath { network_update: Some(_) } = failure {
5409 } else if let &Event::PaymentFailed { .. } = event {
5410 } else { panic!("Unexpected event"); }
5412 assert!(as_failds.contains(&payment_hash_1));
5413 assert!(as_failds.contains(&payment_hash_2));
5414 if announce_latest {
5415 assert!(as_failds.contains(&payment_hash_3));
5416 assert!(as_failds.contains(&payment_hash_5));
5418 assert!(as_failds.contains(&payment_hash_6));
5420 let bs_events = nodes[1].node.get_and_clear_pending_events();
5421 assert_eq!(bs_events.len(), if announce_latest { 8 } else { 6 });
5422 let mut bs_failds = HashSet::new();
5423 let mut bs_updates = 0;
5424 for event in bs_events.iter() {
5425 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5426 assert!(bs_failds.insert(*payment_hash));
5427 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5428 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5430 assert!(!payment_failed_permanently);
5432 if let PathFailure::OnPath { network_update: Some(_) } = failure {
5435 } else if let &Event::PaymentFailed { .. } = event {
5436 } else { panic!("Unexpected event"); }
5438 assert!(bs_failds.contains(&payment_hash_1));
5439 assert!(bs_failds.contains(&payment_hash_2));
5440 if announce_latest {
5441 assert!(bs_failds.contains(&payment_hash_4));
5443 assert!(bs_failds.contains(&payment_hash_5));
5445 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5446 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5447 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5448 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5449 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5450 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5454 fn test_fail_backwards_latest_remote_announce_a() {
5455 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5459 fn test_fail_backwards_latest_remote_announce_b() {
5460 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5464 fn test_fail_backwards_previous_remote_announce() {
5465 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5466 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5467 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5471 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5472 let chanmon_cfgs = create_chanmon_cfgs(2);
5473 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5474 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5475 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5477 // Create some initial channels
5478 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5480 let (_, our_payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5481 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5482 assert_eq!(local_txn[0].input.len(), 1);
5483 check_spends!(local_txn[0], chan_1.3);
5485 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5486 mine_transaction(&nodes[0], &local_txn[0]);
5487 check_closed_broadcast!(nodes[0], true);
5488 check_added_monitors!(nodes[0], 1);
5489 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5490 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5492 let htlc_timeout = {
5493 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5494 assert_eq!(node_txn.len(), 1);
5495 assert_eq!(node_txn[0].input.len(), 1);
5496 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5497 check_spends!(node_txn[0], local_txn[0]);
5501 mine_transaction(&nodes[0], &htlc_timeout);
5502 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5503 expect_payment_failed!(nodes[0], our_payment_hash, false);
5505 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5506 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5507 assert_eq!(spend_txn.len(), 3);
5508 check_spends!(spend_txn[0], local_txn[0]);
5509 assert_eq!(spend_txn[1].input.len(), 1);
5510 check_spends!(spend_txn[1], htlc_timeout);
5511 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5512 assert_eq!(spend_txn[2].input.len(), 2);
5513 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5514 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5515 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5519 fn test_key_derivation_params() {
5520 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5521 // manager rotation to test that `channel_keys_id` returned in
5522 // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5523 // then derive a `delayed_payment_key`.
5525 let chanmon_cfgs = create_chanmon_cfgs(3);
5527 // We manually create the node configuration to backup the seed.
5528 let seed = [42; 32];
5529 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5530 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);
5531 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[0].logger));
5532 let scorer = RwLock::new(test_utils::TestScorer::new());
5533 let router = test_utils::TestRouter::new(network_graph.clone(), &scorer);
5534 let node = NodeCfg { chain_source: &chanmon_cfgs[0].chain_source, logger: &chanmon_cfgs[0].logger, tx_broadcaster: &chanmon_cfgs[0].tx_broadcaster, fee_estimator: &chanmon_cfgs[0].fee_estimator, router, chain_monitor, keys_manager: &keys_manager, network_graph, node_seed: seed, override_init_features: alloc::rc::Rc::new(core::cell::RefCell::new(None)) };
5535 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5536 node_cfgs.remove(0);
5537 node_cfgs.insert(0, node);
5539 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5540 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5542 // Create some initial channels
5543 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5545 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2);
5546 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5547 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5549 // Ensure all nodes are at the same height
5550 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5551 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5552 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5553 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5555 let (_, our_payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5556 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5557 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5558 assert_eq!(local_txn_1[0].input.len(), 1);
5559 check_spends!(local_txn_1[0], chan_1.3);
5561 // We check funding pubkey are unique
5562 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]));
5563 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]));
5564 if from_0_funding_key_0 == from_1_funding_key_0
5565 || from_0_funding_key_0 == from_1_funding_key_1
5566 || from_0_funding_key_1 == from_1_funding_key_0
5567 || from_0_funding_key_1 == from_1_funding_key_1 {
5568 panic!("Funding pubkeys aren't unique");
5571 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5572 mine_transaction(&nodes[0], &local_txn_1[0]);
5573 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5574 check_closed_broadcast!(nodes[0], true);
5575 check_added_monitors!(nodes[0], 1);
5576 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5578 let htlc_timeout = {
5579 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5580 assert_eq!(node_txn.len(), 1);
5581 assert_eq!(node_txn[0].input.len(), 1);
5582 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5583 check_spends!(node_txn[0], local_txn_1[0]);
5587 mine_transaction(&nodes[0], &htlc_timeout);
5588 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5589 expect_payment_failed!(nodes[0], our_payment_hash, false);
5591 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5592 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5593 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5594 assert_eq!(spend_txn.len(), 3);
5595 check_spends!(spend_txn[0], local_txn_1[0]);
5596 assert_eq!(spend_txn[1].input.len(), 1);
5597 check_spends!(spend_txn[1], htlc_timeout);
5598 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5599 assert_eq!(spend_txn[2].input.len(), 2);
5600 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5601 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5602 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5606 fn test_static_output_closing_tx() {
5607 let chanmon_cfgs = create_chanmon_cfgs(2);
5608 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5609 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5610 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5612 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5614 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5615 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5617 mine_transaction(&nodes[0], &closing_tx);
5618 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
5619 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5621 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5622 assert_eq!(spend_txn.len(), 1);
5623 check_spends!(spend_txn[0], closing_tx);
5625 mine_transaction(&nodes[1], &closing_tx);
5626 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
5627 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5629 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5630 assert_eq!(spend_txn.len(), 1);
5631 check_spends!(spend_txn[0], closing_tx);
5634 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5635 let chanmon_cfgs = create_chanmon_cfgs(2);
5636 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5637 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5638 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5639 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5641 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5643 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5644 // present in B's local commitment transaction, but none of A's commitment transactions.
5645 nodes[1].node.claim_funds(payment_preimage);
5646 check_added_monitors!(nodes[1], 1);
5647 expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5649 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5650 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5651 expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
5653 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5654 check_added_monitors!(nodes[0], 1);
5655 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5656 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5657 check_added_monitors!(nodes[1], 1);
5659 let starting_block = nodes[1].best_block_info();
5660 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5661 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5662 connect_block(&nodes[1], &block);
5663 block.header.prev_blockhash = block.block_hash();
5665 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5666 check_closed_broadcast!(nodes[1], true);
5667 check_added_monitors!(nodes[1], 1);
5668 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[0].node.get_our_node_id()], 100000);
5671 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5672 let chanmon_cfgs = create_chanmon_cfgs(2);
5673 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5674 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5675 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5676 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5678 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5679 nodes[0].node.send_payment_with_route(&route, payment_hash,
5680 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
5681 check_added_monitors!(nodes[0], 1);
5683 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5685 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5686 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5687 // to "time out" the HTLC.
5689 let starting_block = nodes[1].best_block_info();
5690 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5692 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5693 connect_block(&nodes[0], &block);
5694 block.header.prev_blockhash = block.block_hash();
5696 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5697 check_closed_broadcast!(nodes[0], true);
5698 check_added_monitors!(nodes[0], 1);
5699 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
5702 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5703 let chanmon_cfgs = create_chanmon_cfgs(3);
5704 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5705 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5706 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5707 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5709 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5710 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5711 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5712 // actually revoked.
5713 let htlc_value = if use_dust { 50000 } else { 3000000 };
5714 let (_, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5715 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5716 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5717 check_added_monitors!(nodes[1], 1);
5719 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5720 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5721 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5722 check_added_monitors!(nodes[0], 1);
5723 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5724 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5725 check_added_monitors!(nodes[1], 1);
5726 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5727 check_added_monitors!(nodes[1], 1);
5728 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5730 if check_revoke_no_close {
5731 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5732 check_added_monitors!(nodes[0], 1);
5735 let starting_block = nodes[1].best_block_info();
5736 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5737 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5738 connect_block(&nodes[0], &block);
5739 block.header.prev_blockhash = block.block_hash();
5741 if !check_revoke_no_close {
5742 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5743 check_closed_broadcast!(nodes[0], true);
5744 check_added_monitors!(nodes[0], 1);
5745 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
5747 expect_payment_failed!(nodes[0], our_payment_hash, true);
5751 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5752 // There are only a few cases to test here:
5753 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5754 // broadcastable commitment transactions result in channel closure,
5755 // * its included in an unrevoked-but-previous remote commitment transaction,
5756 // * its included in the latest remote or local commitment transactions.
5757 // We test each of the three possible commitment transactions individually and use both dust and
5759 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5760 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5761 // tested for at least one of the cases in other tests.
5763 fn htlc_claim_single_commitment_only_a() {
5764 do_htlc_claim_local_commitment_only(true);
5765 do_htlc_claim_local_commitment_only(false);
5767 do_htlc_claim_current_remote_commitment_only(true);
5768 do_htlc_claim_current_remote_commitment_only(false);
5772 fn htlc_claim_single_commitment_only_b() {
5773 do_htlc_claim_previous_remote_commitment_only(true, false);
5774 do_htlc_claim_previous_remote_commitment_only(false, false);
5775 do_htlc_claim_previous_remote_commitment_only(true, true);
5776 do_htlc_claim_previous_remote_commitment_only(false, true);
5781 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5782 let chanmon_cfgs = create_chanmon_cfgs(2);
5783 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5784 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5785 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5786 // Force duplicate randomness for every get-random call
5787 for node in nodes.iter() {
5788 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5791 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5792 let channel_value_satoshis=10000;
5793 let push_msat=10001;
5794 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).unwrap();
5795 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5796 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5797 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5799 // Create a second channel with the same random values. This used to panic due to a colliding
5800 // channel_id, but now panics due to a colliding outbound SCID alias.
5801 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).is_err());
5805 fn bolt2_open_channel_sending_node_checks_part2() {
5806 let chanmon_cfgs = create_chanmon_cfgs(2);
5807 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5808 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5809 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5811 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5812 let channel_value_satoshis=2^24;
5813 let push_msat=10001;
5814 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).is_err());
5816 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5817 let channel_value_satoshis=10000;
5818 // Test when push_msat is equal to 1000 * funding_satoshis.
5819 let push_msat=1000*channel_value_satoshis+1;
5820 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).is_err());
5822 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5823 let channel_value_satoshis=10000;
5824 let push_msat=10001;
5825 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).is_ok()); //Create a valid channel
5826 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5827 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5829 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5830 // 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
5831 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5833 // 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.
5834 assert!(BREAKDOWN_TIMEOUT>0);
5835 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5837 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5838 let chain_hash = ChainHash::using_genesis_block(Network::Testnet);
5839 assert_eq!(node0_to_1_send_open_channel.chain_hash, chain_hash);
5841 // 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.
5842 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5843 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5844 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5845 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5846 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5850 fn bolt2_open_channel_sane_dust_limit() {
5851 let chanmon_cfgs = create_chanmon_cfgs(2);
5852 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5853 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5854 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5856 let channel_value_satoshis=1000000;
5857 let push_msat=10001;
5858 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).unwrap();
5859 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5860 node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5861 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5863 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5864 let events = nodes[1].node.get_and_clear_pending_msg_events();
5865 let err_msg = match events[0] {
5866 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5869 _ => panic!("Unexpected event"),
5871 assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5874 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5875 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5876 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5877 // is no longer affordable once it's freed.
5879 fn test_fail_holding_cell_htlc_upon_free() {
5880 let chanmon_cfgs = create_chanmon_cfgs(2);
5881 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5882 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5883 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5884 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5886 // First nodes[0] generates an update_fee, setting the channel's
5887 // pending_update_fee.
5889 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5890 *feerate_lock += 20;
5892 nodes[0].node.timer_tick_occurred();
5893 check_added_monitors!(nodes[0], 1);
5895 let events = nodes[0].node.get_and_clear_pending_msg_events();
5896 assert_eq!(events.len(), 1);
5897 let (update_msg, commitment_signed) = match events[0] {
5898 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5899 (update_fee.as_ref(), commitment_signed)
5901 _ => panic!("Unexpected event"),
5904 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5906 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5907 let channel_reserve = chan_stat.channel_reserve_msat;
5908 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5909 let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
5911 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5912 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
5913 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5915 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5916 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5917 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5918 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5919 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5921 // Flush the pending fee update.
5922 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5923 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5924 check_added_monitors!(nodes[1], 1);
5925 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5926 check_added_monitors!(nodes[0], 1);
5928 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5929 // HTLC, but now that the fee has been raised the payment will now fail, causing
5930 // us to surface its failure to the user.
5931 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5932 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5933 nodes[0].logger.assert_log("lightning::ln::channel", format!("Freeing holding cell with 1 HTLC updates in channel {}", chan.2), 1);
5935 // Check that the payment failed to be sent out.
5936 let events = nodes[0].node.get_and_clear_pending_events();
5937 assert_eq!(events.len(), 2);
5939 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5940 assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5941 assert_eq!(our_payment_hash.clone(), *payment_hash);
5942 assert_eq!(*payment_failed_permanently, false);
5943 assert_eq!(*short_channel_id, Some(route.paths[0].hops[0].short_channel_id));
5945 _ => panic!("Unexpected event"),
5948 &Event::PaymentFailed { ref payment_hash, .. } => {
5949 assert_eq!(our_payment_hash.clone(), *payment_hash);
5951 _ => panic!("Unexpected event"),
5955 // Test that if multiple HTLCs are released from the holding cell and one is
5956 // valid but the other is no longer valid upon release, the valid HTLC can be
5957 // successfully completed while the other one fails as expected.
5959 fn test_free_and_fail_holding_cell_htlcs() {
5960 let chanmon_cfgs = create_chanmon_cfgs(2);
5961 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5962 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5963 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5964 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5966 // First nodes[0] generates an update_fee, setting the channel's
5967 // pending_update_fee.
5969 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5970 *feerate_lock += 200;
5972 nodes[0].node.timer_tick_occurred();
5973 check_added_monitors!(nodes[0], 1);
5975 let events = nodes[0].node.get_and_clear_pending_msg_events();
5976 assert_eq!(events.len(), 1);
5977 let (update_msg, commitment_signed) = match events[0] {
5978 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5979 (update_fee.as_ref(), commitment_signed)
5981 _ => panic!("Unexpected event"),
5984 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5986 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5987 let channel_reserve = chan_stat.channel_reserve_msat;
5988 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5989 let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
5991 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5993 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features) - amt_1;
5994 let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5995 let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5997 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5998 nodes[0].node.send_payment_with_route(&route_1, payment_hash_1,
5999 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
6000 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6001 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6002 let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
6003 nodes[0].node.send_payment_with_route(&route_2, payment_hash_2,
6004 RecipientOnionFields::secret_only(payment_secret_2), payment_id_2).unwrap();
6005 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6006 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6008 // Flush the pending fee update.
6009 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6010 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6011 check_added_monitors!(nodes[1], 1);
6012 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6013 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6014 check_added_monitors!(nodes[0], 2);
6016 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6017 // but now that the fee has been raised the second payment will now fail, causing us
6018 // to surface its failure to the user. The first payment should succeed.
6019 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6020 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6021 nodes[0].logger.assert_log("lightning::ln::channel", format!("Freeing holding cell with 2 HTLC updates in channel {}", chan.2), 1);
6023 // Check that the second payment failed to be sent out.
6024 let events = nodes[0].node.get_and_clear_pending_events();
6025 assert_eq!(events.len(), 2);
6027 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
6028 assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6029 assert_eq!(payment_hash_2.clone(), *payment_hash);
6030 assert_eq!(*payment_failed_permanently, false);
6031 assert_eq!(*short_channel_id, Some(route_2.paths[0].hops[0].short_channel_id));
6033 _ => panic!("Unexpected event"),
6036 &Event::PaymentFailed { ref payment_hash, .. } => {
6037 assert_eq!(payment_hash_2.clone(), *payment_hash);
6039 _ => panic!("Unexpected event"),
6042 // Complete the first payment and the RAA from the fee update.
6043 let (payment_event, send_raa_event) = {
6044 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6045 assert_eq!(msgs.len(), 2);
6046 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6048 let raa = match send_raa_event {
6049 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6050 _ => panic!("Unexpected event"),
6052 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6053 check_added_monitors!(nodes[1], 1);
6054 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6055 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6056 let events = nodes[1].node.get_and_clear_pending_events();
6057 assert_eq!(events.len(), 1);
6059 Event::PendingHTLCsForwardable { .. } => {},
6060 _ => panic!("Unexpected event"),
6062 nodes[1].node.process_pending_htlc_forwards();
6063 let events = nodes[1].node.get_and_clear_pending_events();
6064 assert_eq!(events.len(), 1);
6066 Event::PaymentClaimable { .. } => {},
6067 _ => panic!("Unexpected event"),
6069 nodes[1].node.claim_funds(payment_preimage_1);
6070 check_added_monitors!(nodes[1], 1);
6071 expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
6073 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6074 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6075 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6076 expect_payment_sent!(nodes[0], payment_preimage_1);
6079 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6080 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6081 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6084 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6085 let chanmon_cfgs = create_chanmon_cfgs(3);
6086 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6087 // Avoid having to include routing fees in calculations
6088 let mut config = test_default_channel_config();
6089 config.channel_config.forwarding_fee_base_msat = 0;
6090 config.channel_config.forwarding_fee_proportional_millionths = 0;
6091 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6092 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6093 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6094 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
6096 // First nodes[1] generates an update_fee, setting the channel's
6097 // pending_update_fee.
6099 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6100 *feerate_lock += 20;
6102 nodes[1].node.timer_tick_occurred();
6103 check_added_monitors!(nodes[1], 1);
6105 let events = nodes[1].node.get_and_clear_pending_msg_events();
6106 assert_eq!(events.len(), 1);
6107 let (update_msg, commitment_signed) = match events[0] {
6108 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6109 (update_fee.as_ref(), commitment_signed)
6111 _ => panic!("Unexpected event"),
6114 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6116 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan_0_1.2);
6117 let channel_reserve = chan_stat.channel_reserve_msat;
6118 let feerate = get_feerate!(nodes[0], nodes[1], chan_0_1.2);
6119 let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_0_1.2);
6121 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6122 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
6123 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6124 let payment_event = {
6125 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6126 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6127 check_added_monitors!(nodes[0], 1);
6129 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6130 assert_eq!(events.len(), 1);
6132 SendEvent::from_event(events.remove(0))
6134 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6135 check_added_monitors!(nodes[1], 0);
6136 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6137 expect_pending_htlcs_forwardable!(nodes[1]);
6139 chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
6140 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6142 // Flush the pending fee update.
6143 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6144 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6145 check_added_monitors!(nodes[2], 1);
6146 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6147 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6148 check_added_monitors!(nodes[1], 2);
6150 // A final RAA message is generated to finalize the fee update.
6151 let events = nodes[1].node.get_and_clear_pending_msg_events();
6152 assert_eq!(events.len(), 1);
6154 let raa_msg = match &events[0] {
6155 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6158 _ => panic!("Unexpected event"),
6161 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6162 check_added_monitors!(nodes[2], 1);
6163 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6165 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6166 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6167 assert_eq!(process_htlc_forwards_event.len(), 2);
6168 match &process_htlc_forwards_event[0] {
6169 &Event::PendingHTLCsForwardable { .. } => {},
6170 _ => panic!("Unexpected event"),
6173 // In response, we call ChannelManager's process_pending_htlc_forwards
6174 nodes[1].node.process_pending_htlc_forwards();
6175 check_added_monitors!(nodes[1], 1);
6177 // This causes the HTLC to be failed backwards.
6178 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6179 assert_eq!(fail_event.len(), 1);
6180 let (fail_msg, commitment_signed) = match &fail_event[0] {
6181 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6182 assert_eq!(updates.update_add_htlcs.len(), 0);
6183 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6184 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6185 assert_eq!(updates.update_fail_htlcs.len(), 1);
6186 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6188 _ => panic!("Unexpected event"),
6191 // Pass the failure messages back to nodes[0].
6192 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6193 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6195 // Complete the HTLC failure+removal process.
6196 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6197 check_added_monitors!(nodes[0], 1);
6198 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6199 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6200 check_added_monitors!(nodes[1], 2);
6201 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6202 assert_eq!(final_raa_event.len(), 1);
6203 let raa = match &final_raa_event[0] {
6204 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6205 _ => panic!("Unexpected event"),
6207 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6208 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6209 check_added_monitors!(nodes[0], 1);
6213 fn test_payment_route_reaching_same_channel_twice() {
6214 //A route should not go through the same channel twice
6215 //It is enforced when constructing a route.
6216 let chanmon_cfgs = create_chanmon_cfgs(2);
6217 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6218 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6219 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6220 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6222 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6223 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
6224 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);
6226 // Extend the path by itself, essentially simulating route going through same channel twice
6227 let cloned_hops = route.paths[0].hops.clone();
6228 route.paths[0].hops.extend_from_slice(&cloned_hops);
6230 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6231 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6232 ), false, APIError::InvalidRoute { ref err },
6233 assert_eq!(err, &"Path went through the same channel twice"));
6236 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6237 // 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.
6238 //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.
6241 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6242 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6243 let chanmon_cfgs = create_chanmon_cfgs(2);
6244 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6245 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6246 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6247 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6249 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6250 route.paths[0].hops[0].fee_msat = 100;
6252 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6253 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6254 ), true, APIError::ChannelUnavailable { .. }, {});
6255 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6259 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6260 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6261 let chanmon_cfgs = create_chanmon_cfgs(2);
6262 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6263 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6264 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6265 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6267 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6268 route.paths[0].hops[0].fee_msat = 0;
6269 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6270 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)),
6271 true, APIError::ChannelUnavailable { ref err },
6272 assert_eq!(err, "Cannot send 0-msat HTLC"));
6274 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6275 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send 0-msat HTLC", 1);
6279 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6280 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6281 let chanmon_cfgs = create_chanmon_cfgs(2);
6282 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6283 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6284 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6285 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6287 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6288 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6289 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6290 check_added_monitors!(nodes[0], 1);
6291 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6292 updates.update_add_htlcs[0].amount_msat = 0;
6294 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6295 nodes[1].logger.assert_log("lightning::ln::channelmanager", "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6296 check_closed_broadcast!(nodes[1], true).unwrap();
6297 check_added_monitors!(nodes[1], 1);
6298 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() },
6299 [nodes[0].node.get_our_node_id()], 100000);
6303 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6304 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6305 //It is enforced when constructing a route.
6306 let chanmon_cfgs = create_chanmon_cfgs(2);
6307 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6308 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6309 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6310 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6312 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6313 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
6314 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);
6315 route.paths[0].hops.last_mut().unwrap().cltv_expiry_delta = 500000001;
6316 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6317 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6318 ), true, APIError::InvalidRoute { ref err },
6319 assert_eq!(err, &"Channel CLTV overflowed?"));
6323 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6324 //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.
6325 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6326 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6327 let chanmon_cfgs = create_chanmon_cfgs(2);
6328 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6329 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6330 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6331 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6332 let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6333 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context().counterparty_max_accepted_htlcs as u64;
6335 // Fetch a route in advance as we will be unable to once we're unable to send.
6336 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6337 for i in 0..max_accepted_htlcs {
6338 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6339 let payment_event = {
6340 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6341 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6342 check_added_monitors!(nodes[0], 1);
6344 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6345 assert_eq!(events.len(), 1);
6346 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6347 assert_eq!(htlcs[0].htlc_id, i);
6351 SendEvent::from_event(events.remove(0))
6353 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6354 check_added_monitors!(nodes[1], 0);
6355 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6357 expect_pending_htlcs_forwardable!(nodes[1]);
6358 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6360 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6361 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6362 ), true, APIError::ChannelUnavailable { .. }, {});
6364 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6368 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6369 //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.
6370 let chanmon_cfgs = create_chanmon_cfgs(2);
6371 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6372 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6373 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6374 let channel_value = 100000;
6375 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6376 let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6378 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6380 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6381 // Manually create a route over our max in flight (which our router normally automatically
6383 route.paths[0].hops[0].fee_msat = max_in_flight + 1;
6384 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6385 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6386 ), true, APIError::ChannelUnavailable { .. }, {});
6387 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6389 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6392 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6394 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6395 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6396 let chanmon_cfgs = create_chanmon_cfgs(2);
6397 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6398 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6399 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6400 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6401 let htlc_minimum_msat: u64;
6403 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6404 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6405 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6406 htlc_minimum_msat = channel.context().get_holder_htlc_minimum_msat();
6409 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6410 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6411 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6412 check_added_monitors!(nodes[0], 1);
6413 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6414 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6415 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6416 assert!(nodes[1].node.list_channels().is_empty());
6417 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6418 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()));
6419 check_added_monitors!(nodes[1], 1);
6420 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6424 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6425 //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
6426 let chanmon_cfgs = create_chanmon_cfgs(2);
6427 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6428 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6429 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6430 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6432 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6433 let channel_reserve = chan_stat.channel_reserve_msat;
6434 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6435 let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
6436 // The 2* and +1 are for the fee spike reserve.
6437 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
6439 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6440 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6441 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6442 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6443 check_added_monitors!(nodes[0], 1);
6444 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6446 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6447 // at this time channel-initiatee receivers are not required to enforce that senders
6448 // respect the fee_spike_reserve.
6449 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6450 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6452 assert!(nodes[1].node.list_channels().is_empty());
6453 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6454 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6455 check_added_monitors!(nodes[1], 1);
6456 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6460 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6461 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6462 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6463 let chanmon_cfgs = create_chanmon_cfgs(2);
6464 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6465 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6466 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6467 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6469 let send_amt = 3999999;
6470 let (mut route, our_payment_hash, _, our_payment_secret) =
6471 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
6472 route.paths[0].hops[0].fee_msat = send_amt;
6473 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6474 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6475 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6476 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
6477 &route.paths[0], send_amt, RecipientOnionFields::secret_only(our_payment_secret), cur_height, &None).unwrap();
6478 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
6480 let mut msg = msgs::UpdateAddHTLC {
6484 payment_hash: our_payment_hash,
6485 cltv_expiry: htlc_cltv,
6486 onion_routing_packet: onion_packet.clone(),
6487 skimmed_fee_msat: None,
6488 blinding_point: None,
6492 msg.htlc_id = i as u64;
6493 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6495 msg.htlc_id = (50) as u64;
6496 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6498 assert!(nodes[1].node.list_channels().is_empty());
6499 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6500 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6501 check_added_monitors!(nodes[1], 1);
6502 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6506 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6507 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6508 let chanmon_cfgs = create_chanmon_cfgs(2);
6509 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6510 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6511 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6512 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6514 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6515 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6516 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6517 check_added_monitors!(nodes[0], 1);
6518 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6519 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;
6520 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6522 assert!(nodes[1].node.list_channels().is_empty());
6523 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6524 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6525 check_added_monitors!(nodes[1], 1);
6526 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 1000000);
6530 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6531 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6532 let chanmon_cfgs = create_chanmon_cfgs(2);
6533 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6534 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6535 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6537 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6538 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6539 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6540 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6541 check_added_monitors!(nodes[0], 1);
6542 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6543 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6544 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6546 assert!(nodes[1].node.list_channels().is_empty());
6547 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6548 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6549 check_added_monitors!(nodes[1], 1);
6550 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6554 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6555 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6556 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6557 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6558 let chanmon_cfgs = create_chanmon_cfgs(2);
6559 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6560 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6561 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6563 create_announced_chan_between_nodes(&nodes, 0, 1);
6564 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6565 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6566 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6567 check_added_monitors!(nodes[0], 1);
6568 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6569 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6571 //Disconnect and Reconnect
6572 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
6573 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
6574 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
6575 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
6577 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6578 assert_eq!(reestablish_1.len(), 1);
6579 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
6580 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
6582 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6583 assert_eq!(reestablish_2.len(), 1);
6584 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6585 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6586 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6587 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6590 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6591 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6592 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6593 check_added_monitors!(nodes[1], 1);
6594 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6596 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6598 assert!(nodes[1].node.list_channels().is_empty());
6599 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6600 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6601 check_added_monitors!(nodes[1], 1);
6602 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6606 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6607 //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.
6609 let chanmon_cfgs = create_chanmon_cfgs(2);
6610 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6611 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6612 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6613 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6614 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6615 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6616 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6618 check_added_monitors!(nodes[0], 1);
6619 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6620 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6622 let update_msg = msgs::UpdateFulfillHTLC{
6625 payment_preimage: our_payment_preimage,
6628 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6630 assert!(nodes[0].node.list_channels().is_empty());
6631 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6632 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()));
6633 check_added_monitors!(nodes[0], 1);
6634 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6638 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6639 //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.
6641 let chanmon_cfgs = create_chanmon_cfgs(2);
6642 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6643 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6644 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6645 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6647 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6648 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6649 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6650 check_added_monitors!(nodes[0], 1);
6651 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6652 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6654 let update_msg = msgs::UpdateFailHTLC{
6657 reason: msgs::OnionErrorPacket { data: Vec::new()},
6660 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6662 assert!(nodes[0].node.list_channels().is_empty());
6663 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6664 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()));
6665 check_added_monitors!(nodes[0], 1);
6666 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6670 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6671 //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.
6673 let chanmon_cfgs = create_chanmon_cfgs(2);
6674 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6675 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6676 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6677 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6679 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6680 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6681 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6682 check_added_monitors!(nodes[0], 1);
6683 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6684 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6685 let update_msg = msgs::UpdateFailMalformedHTLC{
6688 sha256_of_onion: [1; 32],
6689 failure_code: 0x8000,
6692 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6694 assert!(nodes[0].node.list_channels().is_empty());
6695 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6696 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()));
6697 check_added_monitors!(nodes[0], 1);
6698 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6702 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6703 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6705 let chanmon_cfgs = create_chanmon_cfgs(2);
6706 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6707 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6708 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6709 create_announced_chan_between_nodes(&nodes, 0, 1);
6711 let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6713 nodes[1].node.claim_funds(our_payment_preimage);
6714 check_added_monitors!(nodes[1], 1);
6715 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6717 let events = nodes[1].node.get_and_clear_pending_msg_events();
6718 assert_eq!(events.len(), 1);
6719 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6721 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, .. } } => {
6722 assert!(update_add_htlcs.is_empty());
6723 assert_eq!(update_fulfill_htlcs.len(), 1);
6724 assert!(update_fail_htlcs.is_empty());
6725 assert!(update_fail_malformed_htlcs.is_empty());
6726 assert!(update_fee.is_none());
6727 update_fulfill_htlcs[0].clone()
6729 _ => panic!("Unexpected event"),
6733 update_fulfill_msg.htlc_id = 1;
6735 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6737 assert!(nodes[0].node.list_channels().is_empty());
6738 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6739 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6740 check_added_monitors!(nodes[0], 1);
6741 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6745 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6746 //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.
6748 let chanmon_cfgs = create_chanmon_cfgs(2);
6749 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6750 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6751 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6752 create_announced_chan_between_nodes(&nodes, 0, 1);
6754 let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6756 nodes[1].node.claim_funds(our_payment_preimage);
6757 check_added_monitors!(nodes[1], 1);
6758 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6760 let events = nodes[1].node.get_and_clear_pending_msg_events();
6761 assert_eq!(events.len(), 1);
6762 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6764 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, .. } } => {
6765 assert!(update_add_htlcs.is_empty());
6766 assert_eq!(update_fulfill_htlcs.len(), 1);
6767 assert!(update_fail_htlcs.is_empty());
6768 assert!(update_fail_malformed_htlcs.is_empty());
6769 assert!(update_fee.is_none());
6770 update_fulfill_htlcs[0].clone()
6772 _ => panic!("Unexpected event"),
6776 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6778 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6780 assert!(nodes[0].node.list_channels().is_empty());
6781 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6782 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6783 check_added_monitors!(nodes[0], 1);
6784 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6788 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6789 //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.
6791 let chanmon_cfgs = create_chanmon_cfgs(2);
6792 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6793 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6794 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6795 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6797 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6798 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6799 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6800 check_added_monitors!(nodes[0], 1);
6802 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6803 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6805 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6806 check_added_monitors!(nodes[1], 0);
6807 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6809 let events = nodes[1].node.get_and_clear_pending_msg_events();
6811 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6813 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, .. } } => {
6814 assert!(update_add_htlcs.is_empty());
6815 assert!(update_fulfill_htlcs.is_empty());
6816 assert!(update_fail_htlcs.is_empty());
6817 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6818 assert!(update_fee.is_none());
6819 update_fail_malformed_htlcs[0].clone()
6821 _ => panic!("Unexpected event"),
6824 update_msg.failure_code &= !0x8000;
6825 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6827 assert!(nodes[0].node.list_channels().is_empty());
6828 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6829 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6830 check_added_monitors!(nodes[0], 1);
6831 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 1000000);
6835 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6836 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6837 // * 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.
6839 let chanmon_cfgs = create_chanmon_cfgs(3);
6840 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6841 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6842 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6843 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6844 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000);
6846 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6849 let mut payment_event = {
6850 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6851 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6852 check_added_monitors!(nodes[0], 1);
6853 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6854 assert_eq!(events.len(), 1);
6855 SendEvent::from_event(events.remove(0))
6857 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6858 check_added_monitors!(nodes[1], 0);
6859 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6860 expect_pending_htlcs_forwardable!(nodes[1]);
6861 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6862 assert_eq!(events_2.len(), 1);
6863 check_added_monitors!(nodes[1], 1);
6864 payment_event = SendEvent::from_event(events_2.remove(0));
6865 assert_eq!(payment_event.msgs.len(), 1);
6868 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6869 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6870 check_added_monitors!(nodes[2], 0);
6871 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6873 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6874 assert_eq!(events_3.len(), 1);
6875 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6877 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 } } => {
6878 assert!(update_add_htlcs.is_empty());
6879 assert!(update_fulfill_htlcs.is_empty());
6880 assert!(update_fail_htlcs.is_empty());
6881 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6882 assert!(update_fee.is_none());
6883 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6885 _ => panic!("Unexpected event"),
6889 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6891 check_added_monitors!(nodes[1], 0);
6892 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6893 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 }]);
6894 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6895 assert_eq!(events_4.len(), 1);
6897 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6899 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, .. } } => {
6900 assert!(update_add_htlcs.is_empty());
6901 assert!(update_fulfill_htlcs.is_empty());
6902 assert_eq!(update_fail_htlcs.len(), 1);
6903 assert!(update_fail_malformed_htlcs.is_empty());
6904 assert!(update_fee.is_none());
6906 _ => panic!("Unexpected event"),
6909 check_added_monitors!(nodes[1], 1);
6913 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6914 let chanmon_cfgs = create_chanmon_cfgs(3);
6915 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6916 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6917 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6918 create_announced_chan_between_nodes(&nodes, 0, 1);
6919 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6921 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6924 let mut payment_event = {
6925 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6926 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6927 check_added_monitors!(nodes[0], 1);
6928 SendEvent::from_node(&nodes[0])
6931 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6932 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6933 expect_pending_htlcs_forwardable!(nodes[1]);
6934 check_added_monitors!(nodes[1], 1);
6935 payment_event = SendEvent::from_node(&nodes[1]);
6936 assert_eq!(payment_event.msgs.len(), 1);
6939 payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6940 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6941 check_added_monitors!(nodes[2], 0);
6942 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6944 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6945 assert_eq!(events_3.len(), 1);
6947 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6948 let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6949 // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6950 update_msg.failure_code |= 0x2000;
6952 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6953 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6955 _ => panic!("Unexpected event"),
6958 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6959 vec![HTLCDestination::NextHopChannel {
6960 node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6961 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6962 assert_eq!(events_4.len(), 1);
6963 check_added_monitors!(nodes[1], 1);
6966 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6967 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6968 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6970 _ => panic!("Unexpected event"),
6973 let events_5 = nodes[0].node.get_and_clear_pending_events();
6974 assert_eq!(events_5.len(), 2);
6976 // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6977 // the node originating the error to its next hop.
6979 Event::PaymentPathFailed { error_code, failure: PathFailure::OnPath { network_update: Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }) }, ..
6981 assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6982 assert!(is_permanent);
6983 assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
6985 _ => panic!("Unexpected event"),
6988 Event::PaymentFailed { payment_hash, .. } => {
6989 assert_eq!(payment_hash, our_payment_hash);
6991 _ => panic!("Unexpected event"),
6994 // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
6997 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6998 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6999 // 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
7000 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7002 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7003 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7004 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7005 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7006 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7007 let chan =create_announced_chan_between_nodes(&nodes, 0, 1);
7009 let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
7010 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context().holder_dust_limit_satoshis;
7012 // We route 2 dust-HTLCs between A and B
7013 let (_, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7014 let (_, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7015 route_payment(&nodes[0], &[&nodes[1]], 1000000);
7017 // Cache one local commitment tx as previous
7018 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7020 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7021 nodes[1].node.fail_htlc_backwards(&payment_hash_2);
7022 check_added_monitors!(nodes[1], 0);
7023 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7024 check_added_monitors!(nodes[1], 1);
7026 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7027 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7028 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7029 check_added_monitors!(nodes[0], 1);
7031 // Cache one local commitment tx as lastest
7032 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7034 let events = nodes[0].node.get_and_clear_pending_msg_events();
7036 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7037 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7039 _ => panic!("Unexpected event"),
7042 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7043 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7045 _ => panic!("Unexpected event"),
7048 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7049 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7050 if announce_latest {
7051 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7053 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7056 check_closed_broadcast!(nodes[0], true);
7057 check_added_monitors!(nodes[0], 1);
7058 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7060 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7061 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7062 let events = nodes[0].node.get_and_clear_pending_events();
7063 // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7064 assert_eq!(events.len(), 4);
7065 let mut first_failed = false;
7066 for event in events {
7068 Event::PaymentPathFailed { payment_hash, .. } => {
7069 if payment_hash == payment_hash_1 {
7070 assert!(!first_failed);
7071 first_failed = true;
7073 assert_eq!(payment_hash, payment_hash_2);
7076 Event::PaymentFailed { .. } => {}
7077 _ => panic!("Unexpected event"),
7083 fn test_failure_delay_dust_htlc_local_commitment() {
7084 do_test_failure_delay_dust_htlc_local_commitment(true);
7085 do_test_failure_delay_dust_htlc_local_commitment(false);
7088 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7089 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7090 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7091 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7092 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7093 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7094 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7096 let chanmon_cfgs = create_chanmon_cfgs(3);
7097 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7098 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7099 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7100 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
7102 let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
7103 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context().holder_dust_limit_satoshis;
7105 let (_payment_preimage_1, dust_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7106 let (_payment_preimage_2, non_dust_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7108 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7109 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7111 // We revoked bs_commitment_tx
7113 let (payment_preimage_3, ..) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7114 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7117 let mut timeout_tx = Vec::new();
7119 // We fail dust-HTLC 1 by broadcast of local commitment tx
7120 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7121 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7122 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7123 expect_payment_failed!(nodes[0], dust_hash, false);
7125 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7126 check_closed_broadcast!(nodes[0], true);
7127 check_added_monitors!(nodes[0], 1);
7128 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7129 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7130 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7131 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7132 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7133 mine_transaction(&nodes[0], &timeout_tx[0]);
7134 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7135 expect_payment_failed!(nodes[0], non_dust_hash, false);
7137 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7138 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7139 check_closed_broadcast!(nodes[0], true);
7140 check_added_monitors!(nodes[0], 1);
7141 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7142 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7144 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7145 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
7146 .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
7147 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
7148 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
7149 // dust HTLC should have been failed.
7150 expect_payment_failed!(nodes[0], dust_hash, false);
7153 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7155 assert_eq!(timeout_tx[0].lock_time.to_consensus_u32(), 11);
7157 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
7158 mine_transaction(&nodes[0], &timeout_tx[0]);
7159 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7160 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7161 expect_payment_failed!(nodes[0], non_dust_hash, false);
7166 fn test_sweep_outbound_htlc_failure_update() {
7167 do_test_sweep_outbound_htlc_failure_update(false, true);
7168 do_test_sweep_outbound_htlc_failure_update(false, false);
7169 do_test_sweep_outbound_htlc_failure_update(true, false);
7173 fn test_user_configurable_csv_delay() {
7174 // We test our channel constructors yield errors when we pass them absurd csv delay
7176 let mut low_our_to_self_config = UserConfig::default();
7177 low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
7178 let mut high_their_to_self_config = UserConfig::default();
7179 high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
7180 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7181 let chanmon_cfgs = create_chanmon_cfgs(2);
7182 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7183 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7184 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7186 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in OutboundV1Channel::new()
7187 if let Err(error) = OutboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7188 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[1].node.init_features(), 1000000, 1000000, 0,
7189 &low_our_to_self_config, 0, 42, None)
7192 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())); },
7193 _ => panic!("Unexpected event"),
7195 } else { assert!(false) }
7197 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in InboundV1Channel::new()
7198 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None, None).unwrap();
7199 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7200 open_channel.to_self_delay = 200;
7201 if let Err(error) = InboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7202 &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,
7203 &low_our_to_self_config, 0, &nodes[0].logger, /*is_0conf=*/false)
7206 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())); },
7207 _ => panic!("Unexpected event"),
7209 } else { assert!(false); }
7211 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7212 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None, None).unwrap();
7213 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()));
7214 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7215 accept_channel.to_self_delay = 200;
7216 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
7218 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7220 &ErrorAction::SendErrorMessage { ref msg } => {
7221 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()));
7222 reason_msg = msg.data.clone();
7226 } else { panic!(); }
7227 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg }, [nodes[1].node.get_our_node_id()], 1000000);
7229 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in InboundV1Channel::new()
7230 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None, None).unwrap();
7231 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7232 open_channel.to_self_delay = 200;
7233 if let Err(error) = InboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7234 &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,
7235 &high_their_to_self_config, 0, &nodes[0].logger, /*is_0conf=*/false)
7238 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())); },
7239 _ => panic!("Unexpected event"),
7241 } else { assert!(false); }
7245 fn test_check_htlc_underpaying() {
7246 // Send payment through A -> B but A is maliciously
7247 // sending a probe payment (i.e less than expected value0
7248 // to B, B should refuse payment.
7250 let chanmon_cfgs = create_chanmon_cfgs(2);
7251 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7252 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7253 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7255 // Create some initial channels
7256 create_announced_chan_between_nodes(&nodes, 0, 1);
7258 let scorer = test_utils::TestScorer::new();
7259 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7260 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
7261 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
7262 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 10_000);
7263 let route = get_route(&nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph.read_only(),
7264 None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes).unwrap();
7265 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7266 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, None).unwrap();
7267 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
7268 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
7269 check_added_monitors!(nodes[0], 1);
7271 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7272 assert_eq!(events.len(), 1);
7273 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7274 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7275 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7277 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7278 // and then will wait a second random delay before failing the HTLC back:
7279 expect_pending_htlcs_forwardable!(nodes[1]);
7280 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7282 // Node 3 is expecting payment of 100_000 but received 10_000,
7283 // it should fail htlc like we didn't know the preimage.
7284 nodes[1].node.process_pending_htlc_forwards();
7286 let events = nodes[1].node.get_and_clear_pending_msg_events();
7287 assert_eq!(events.len(), 1);
7288 let (update_fail_htlc, commitment_signed) = match events[0] {
7289 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 } } => {
7290 assert!(update_add_htlcs.is_empty());
7291 assert!(update_fulfill_htlcs.is_empty());
7292 assert_eq!(update_fail_htlcs.len(), 1);
7293 assert!(update_fail_malformed_htlcs.is_empty());
7294 assert!(update_fee.is_none());
7295 (update_fail_htlcs[0].clone(), commitment_signed)
7297 _ => panic!("Unexpected event"),
7299 check_added_monitors!(nodes[1], 1);
7301 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7302 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7304 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7305 let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
7306 expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
7307 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7311 fn test_announce_disable_channels() {
7312 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7313 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7315 let chanmon_cfgs = create_chanmon_cfgs(2);
7316 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7317 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7318 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7320 create_announced_chan_between_nodes(&nodes, 0, 1);
7321 create_announced_chan_between_nodes(&nodes, 1, 0);
7322 create_announced_chan_between_nodes(&nodes, 0, 1);
7325 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
7326 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
7328 for _ in 0..DISABLE_GOSSIP_TICKS + 1 {
7329 nodes[0].node.timer_tick_occurred();
7331 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7332 assert_eq!(msg_events.len(), 3);
7333 let mut chans_disabled = HashMap::new();
7334 for e in msg_events {
7336 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7337 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7338 // Check that each channel gets updated exactly once
7339 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7340 panic!("Generated ChannelUpdate for wrong chan!");
7343 _ => panic!("Unexpected event"),
7347 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
7348 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
7350 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7351 assert_eq!(reestablish_1.len(), 3);
7352 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
7353 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
7355 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7356 assert_eq!(reestablish_2.len(), 3);
7358 // Reestablish chan_1
7359 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7360 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7361 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7362 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7363 // Reestablish chan_2
7364 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7365 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7366 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7367 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7368 // Reestablish chan_3
7369 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
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[2]);
7372 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7374 for _ in 0..ENABLE_GOSSIP_TICKS {
7375 nodes[0].node.timer_tick_occurred();
7377 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7378 nodes[0].node.timer_tick_occurred();
7379 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7380 assert_eq!(msg_events.len(), 3);
7381 for e in msg_events {
7383 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7384 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7385 match chans_disabled.remove(&msg.contents.short_channel_id) {
7386 // Each update should have a higher timestamp than the previous one, replacing
7388 Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7389 None => panic!("Generated ChannelUpdate for wrong chan!"),
7392 _ => panic!("Unexpected event"),
7395 // Check that each channel gets updated exactly once
7396 assert!(chans_disabled.is_empty());
7400 fn test_bump_penalty_txn_on_revoked_commitment() {
7401 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7402 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7404 let chanmon_cfgs = create_chanmon_cfgs(2);
7405 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7406 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7407 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7409 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7411 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7412 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7413 .with_bolt11_features(nodes[0].node.bolt11_invoice_features()).unwrap();
7414 let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000);
7415 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7417 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7418 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7419 assert_eq!(revoked_txn[0].output.len(), 4);
7420 assert_eq!(revoked_txn[0].input.len(), 1);
7421 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7422 let revoked_txid = revoked_txn[0].txid();
7424 let mut penalty_sum = 0;
7425 for outp in revoked_txn[0].output.iter() {
7426 if outp.script_pubkey.is_v0_p2wsh() {
7427 penalty_sum += outp.value;
7431 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7432 let header_114 = connect_blocks(&nodes[1], 14);
7434 // Actually revoke tx by claiming a HTLC
7435 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7436 connect_block(&nodes[1], &create_dummy_block(header_114, 42, vec![revoked_txn[0].clone()]));
7437 check_added_monitors!(nodes[1], 1);
7439 // One or more justice tx should have been broadcast, check it
7443 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7444 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7445 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7446 assert_eq!(node_txn[0].output.len(), 1);
7447 check_spends!(node_txn[0], revoked_txn[0]);
7448 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7449 feerate_1 = fee_1 * 1000 / node_txn[0].weight().to_wu();
7450 penalty_1 = node_txn[0].txid();
7454 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7455 connect_blocks(&nodes[1], 15);
7456 let mut penalty_2 = penalty_1;
7457 let mut feerate_2 = 0;
7459 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7460 assert_eq!(node_txn.len(), 1);
7461 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7462 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7463 assert_eq!(node_txn[0].output.len(), 1);
7464 check_spends!(node_txn[0], revoked_txn[0]);
7465 penalty_2 = node_txn[0].txid();
7466 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7467 assert_ne!(penalty_2, penalty_1);
7468 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7469 feerate_2 = fee_2 * 1000 / node_txn[0].weight().to_wu();
7470 // Verify 25% bump heuristic
7471 assert!(feerate_2 * 100 >= feerate_1 * 125);
7475 assert_ne!(feerate_2, 0);
7477 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7478 connect_blocks(&nodes[1], 1);
7480 let mut feerate_3 = 0;
7482 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7483 assert_eq!(node_txn.len(), 1);
7484 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7485 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7486 assert_eq!(node_txn[0].output.len(), 1);
7487 check_spends!(node_txn[0], revoked_txn[0]);
7488 penalty_3 = node_txn[0].txid();
7489 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7490 assert_ne!(penalty_3, penalty_2);
7491 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7492 feerate_3 = fee_3 * 1000 / node_txn[0].weight().to_wu();
7493 // Verify 25% bump heuristic
7494 assert!(feerate_3 * 100 >= feerate_2 * 125);
7498 assert_ne!(feerate_3, 0);
7500 nodes[1].node.get_and_clear_pending_events();
7501 nodes[1].node.get_and_clear_pending_msg_events();
7505 fn test_bump_penalty_txn_on_revoked_htlcs() {
7506 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7507 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7509 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7510 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7511 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7512 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7513 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7515 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7516 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7517 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();
7518 let scorer = test_utils::TestScorer::new();
7519 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7520 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 3_000_000);
7521 let route = get_route(&nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph.read_only(), None,
7522 nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes).unwrap();
7523 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7524 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50)
7525 .with_bolt11_features(nodes[0].node.bolt11_invoice_features()).unwrap();
7526 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 3_000_000);
7527 let route = get_route(&nodes[1].node.get_our_node_id(), &route_params, &nodes[1].network_graph.read_only(), None,
7528 nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes).unwrap();
7529 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7531 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7532 assert_eq!(revoked_local_txn[0].input.len(), 1);
7533 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7535 // Revoke local commitment tx
7536 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7538 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7539 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone()]));
7540 check_closed_broadcast!(nodes[1], true);
7541 check_added_monitors!(nodes[1], 1);
7542 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 1000000);
7543 connect_blocks(&nodes[1], 50); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7545 let revoked_htlc_txn = {
7546 let txn = nodes[1].tx_broadcaster.unique_txn_broadcast();
7547 assert_eq!(txn.len(), 2);
7549 assert_eq!(txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7550 assert_eq!(txn[0].input.len(), 1);
7551 check_spends!(txn[0], revoked_local_txn[0]);
7553 assert_eq!(txn[1].input.len(), 1);
7554 assert_eq!(txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7555 assert_eq!(txn[1].output.len(), 1);
7556 check_spends!(txn[1], revoked_local_txn[0]);
7561 // Broadcast set of revoked txn on A
7562 let hash_128 = connect_blocks(&nodes[0], 40);
7563 let block_11 = create_dummy_block(hash_128, 42, vec![revoked_local_txn[0].clone()]);
7564 connect_block(&nodes[0], &block_11);
7565 let block_129 = create_dummy_block(block_11.block_hash(), 42, vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()]);
7566 connect_block(&nodes[0], &block_129);
7567 let events = nodes[0].node.get_and_clear_pending_events();
7568 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7569 match events.last().unwrap() {
7570 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7571 _ => panic!("Unexpected event"),
7577 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7578 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7579 // Verify claim tx are spending revoked HTLC txn
7581 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7582 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7583 // which are included in the same block (they are broadcasted because we scan the
7584 // transactions linearly and generate claims as we go, they likely should be removed in the
7586 assert_eq!(node_txn[0].input.len(), 1);
7587 check_spends!(node_txn[0], revoked_local_txn[0]);
7588 assert_eq!(node_txn[1].input.len(), 1);
7589 check_spends!(node_txn[1], revoked_local_txn[0]);
7590 assert_eq!(node_txn[2].input.len(), 1);
7591 check_spends!(node_txn[2], revoked_local_txn[0]);
7593 // Each of the three justice transactions claim a separate (single) output of the three
7594 // available, which we check here:
7595 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7596 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7597 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7599 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7600 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7602 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7603 // output, checked above).
7604 assert_eq!(node_txn[3].input.len(), 2);
7605 assert_eq!(node_txn[3].output.len(), 1);
7606 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7608 first = node_txn[3].txid();
7609 // Store both feerates for later comparison
7610 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7611 feerate_1 = fee_1 * 1000 / node_txn[3].weight().to_wu();
7612 penalty_txn = vec![node_txn[2].clone()];
7616 // Connect one more block to see if bumped penalty are issued for HTLC txn
7617 let block_130 = create_dummy_block(block_129.block_hash(), 42, penalty_txn);
7618 connect_block(&nodes[0], &block_130);
7619 let block_131 = create_dummy_block(block_130.block_hash(), 42, Vec::new());
7620 connect_block(&nodes[0], &block_131);
7622 // Few more blocks to confirm penalty txn
7623 connect_blocks(&nodes[0], 4);
7624 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7625 let header_144 = connect_blocks(&nodes[0], 9);
7627 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7628 assert_eq!(node_txn.len(), 1);
7630 assert_eq!(node_txn[0].input.len(), 2);
7631 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7632 // Verify bumped tx is different and 25% bump heuristic
7633 assert_ne!(first, node_txn[0].txid());
7634 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7635 let feerate_2 = fee_2 * 1000 / node_txn[0].weight().to_wu();
7636 assert!(feerate_2 * 100 > feerate_1 * 125);
7637 let txn = vec![node_txn[0].clone()];
7641 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7642 connect_block(&nodes[0], &create_dummy_block(header_144, 42, node_txn));
7643 connect_blocks(&nodes[0], 20);
7645 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7646 // We verify than no new transaction has been broadcast because previously
7647 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7648 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7649 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7650 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7651 // up bumped justice generation.
7652 assert_eq!(node_txn.len(), 0);
7655 check_closed_broadcast!(nodes[0], true);
7656 check_added_monitors!(nodes[0], 1);
7660 fn test_bump_penalty_txn_on_remote_commitment() {
7661 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7662 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7665 // Provide preimage for one
7666 // Check aggregation
7668 let chanmon_cfgs = create_chanmon_cfgs(2);
7669 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7670 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7671 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7673 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7674 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7675 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7677 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7678 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7679 assert_eq!(remote_txn[0].output.len(), 4);
7680 assert_eq!(remote_txn[0].input.len(), 1);
7681 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7683 // Claim a HTLC without revocation (provide B monitor with preimage)
7684 nodes[1].node.claim_funds(payment_preimage);
7685 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7686 mine_transaction(&nodes[1], &remote_txn[0]);
7687 check_added_monitors!(nodes[1], 2);
7688 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7690 // One or more claim tx should have been broadcast, check it
7694 let feerate_timeout;
7695 let feerate_preimage;
7697 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7698 // 3 transactions including:
7699 // preimage and timeout sweeps from remote commitment + preimage sweep bump
7700 assert_eq!(node_txn.len(), 3);
7701 assert_eq!(node_txn[0].input.len(), 1);
7702 assert_eq!(node_txn[1].input.len(), 1);
7703 assert_eq!(node_txn[2].input.len(), 1);
7704 check_spends!(node_txn[0], remote_txn[0]);
7705 check_spends!(node_txn[1], remote_txn[0]);
7706 check_spends!(node_txn[2], remote_txn[0]);
7708 preimage = node_txn[0].txid();
7709 let index = node_txn[0].input[0].previous_output.vout;
7710 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7711 feerate_preimage = fee * 1000 / node_txn[0].weight().to_wu();
7713 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7714 (node_txn[2].clone(), node_txn[1].clone())
7716 (node_txn[1].clone(), node_txn[2].clone())
7719 preimage_bump = preimage_bump_tx;
7720 check_spends!(preimage_bump, remote_txn[0]);
7721 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7723 timeout = timeout_tx.txid();
7724 let index = timeout_tx.input[0].previous_output.vout;
7725 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7726 feerate_timeout = fee * 1000 / timeout_tx.weight().to_wu();
7730 assert_ne!(feerate_timeout, 0);
7731 assert_ne!(feerate_preimage, 0);
7733 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7734 connect_blocks(&nodes[1], 1);
7736 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7737 assert_eq!(node_txn.len(), 1);
7738 assert_eq!(node_txn[0].input.len(), 1);
7739 assert_eq!(preimage_bump.input.len(), 1);
7740 check_spends!(node_txn[0], remote_txn[0]);
7741 check_spends!(preimage_bump, remote_txn[0]);
7743 let index = preimage_bump.input[0].previous_output.vout;
7744 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7745 let new_feerate = fee * 1000 / preimage_bump.weight().to_wu();
7746 assert!(new_feerate * 100 > feerate_timeout * 125);
7747 assert_ne!(timeout, preimage_bump.txid());
7749 let index = node_txn[0].input[0].previous_output.vout;
7750 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7751 let new_feerate = fee * 1000 / node_txn[0].weight().to_wu();
7752 assert!(new_feerate * 100 > feerate_preimage * 125);
7753 assert_ne!(preimage, node_txn[0].txid());
7758 nodes[1].node.get_and_clear_pending_events();
7759 nodes[1].node.get_and_clear_pending_msg_events();
7763 fn test_counterparty_raa_skip_no_crash() {
7764 // Previously, if our counterparty sent two RAAs in a row without us having provided a
7765 // commitment transaction, we would have happily carried on and provided them the next
7766 // commitment transaction based on one RAA forward. This would probably eventually have led to
7767 // channel closure, but it would not have resulted in funds loss. Still, our
7768 // TestChannelSigner would have panicked as it doesn't like jumps into the future. Here, we
7769 // check simply that the channel is closed in response to such an RAA, but don't check whether
7770 // we decide to punish our counterparty for revoking their funds (as we don't currently
7772 let chanmon_cfgs = create_chanmon_cfgs(2);
7773 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7774 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7775 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7776 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7778 let per_commitment_secret;
7779 let next_per_commitment_point;
7781 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7782 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7783 let keys = guard.channel_by_id.get_mut(&channel_id).map(
7784 |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
7785 ).flatten().unwrap().get_signer();
7787 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7789 // Make signer believe we got a counterparty signature, so that it allows the revocation
7790 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7791 per_commitment_secret = keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7793 // Must revoke without gaps
7794 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7795 keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7797 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7798 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7799 &SecretKey::from_slice(&keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7802 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7803 &msgs::RevokeAndACK {
7805 per_commitment_secret,
7806 next_per_commitment_point,
7808 next_local_nonce: None,
7810 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7811 check_added_monitors!(nodes[1], 1);
7812 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() }
7813 , [nodes[0].node.get_our_node_id()], 100000);
7817 fn test_bump_txn_sanitize_tracking_maps() {
7818 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7819 // verify we clean then right after expiration of ANTI_REORG_DELAY.
7821 let chanmon_cfgs = create_chanmon_cfgs(2);
7822 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7823 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7824 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7826 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7827 // Lock HTLC in both directions
7828 let (payment_preimage_1, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7829 let (_, payment_hash_2, ..) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7831 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7832 assert_eq!(revoked_local_txn[0].input.len(), 1);
7833 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7835 // Revoke local commitment tx
7836 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7838 // Broadcast set of revoked txn on A
7839 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7840 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7841 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7843 mine_transaction(&nodes[0], &revoked_local_txn[0]);
7844 check_closed_broadcast!(nodes[0], true);
7845 check_added_monitors!(nodes[0], 1);
7846 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 1000000);
7848 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7849 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7850 check_spends!(node_txn[0], revoked_local_txn[0]);
7851 check_spends!(node_txn[1], revoked_local_txn[0]);
7852 check_spends!(node_txn[2], revoked_local_txn[0]);
7853 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7857 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, penalty_txn));
7858 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7860 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7861 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7862 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7867 fn test_channel_conf_timeout() {
7868 // Tests that, for inbound channels, we give up on them if the funding transaction does not
7869 // confirm within 2016 blocks, as recommended by BOLT 2.
7870 let chanmon_cfgs = create_chanmon_cfgs(2);
7871 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7872 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7873 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7875 let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7877 // The outbound node should wait forever for confirmation:
7878 // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7879 // copied here instead of directly referencing the constant.
7880 connect_blocks(&nodes[0], 2016);
7881 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7883 // The inbound node should fail the channel after exactly 2016 blocks
7884 connect_blocks(&nodes[1], 2015);
7885 check_added_monitors!(nodes[1], 0);
7886 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7888 connect_blocks(&nodes[1], 1);
7889 check_added_monitors!(nodes[1], 1);
7890 check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut, [nodes[0].node.get_our_node_id()], 1000000);
7891 let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7892 assert_eq!(close_ev.len(), 1);
7894 MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { ref msg }, ref node_id } => {
7895 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7896 assert_eq!(msg.as_ref().unwrap().data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7898 _ => panic!("Unexpected event"),
7903 fn test_override_channel_config() {
7904 let chanmon_cfgs = create_chanmon_cfgs(2);
7905 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7906 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7907 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7909 // Node0 initiates a channel to node1 using the override config.
7910 let mut override_config = UserConfig::default();
7911 override_config.channel_handshake_config.our_to_self_delay = 200;
7913 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, None, Some(override_config)).unwrap();
7915 // Assert the channel created by node0 is using the override config.
7916 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7917 assert_eq!(res.channel_flags, 0);
7918 assert_eq!(res.to_self_delay, 200);
7922 fn test_override_0msat_htlc_minimum() {
7923 let mut zero_config = UserConfig::default();
7924 zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7925 let chanmon_cfgs = create_chanmon_cfgs(2);
7926 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7927 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7928 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7930 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, None, Some(zero_config)).unwrap();
7931 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7932 assert_eq!(res.htlc_minimum_msat, 1);
7934 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7935 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7936 assert_eq!(res.htlc_minimum_msat, 1);
7940 fn test_channel_update_has_correct_htlc_maximum_msat() {
7941 // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7942 // Bolt 7 specifies that if present `htlc_maximum_msat`:
7943 // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7944 // 90% of the `channel_value`.
7945 // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7947 let mut config_30_percent = UserConfig::default();
7948 config_30_percent.channel_handshake_config.announced_channel = true;
7949 config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7950 let mut config_50_percent = UserConfig::default();
7951 config_50_percent.channel_handshake_config.announced_channel = true;
7952 config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7953 let mut config_95_percent = UserConfig::default();
7954 config_95_percent.channel_handshake_config.announced_channel = true;
7955 config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7956 let mut config_100_percent = UserConfig::default();
7957 config_100_percent.channel_handshake_config.announced_channel = true;
7958 config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7960 let chanmon_cfgs = create_chanmon_cfgs(4);
7961 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7962 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)]);
7963 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7965 let channel_value_satoshis = 100000;
7966 let channel_value_msat = channel_value_satoshis * 1000;
7967 let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7968 let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7969 let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7971 let (node_0_chan_update, node_1_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
7972 let (node_2_chan_update, node_3_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
7974 // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7975 // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7976 assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7977 // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7978 // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7979 assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7981 // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7982 // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7984 assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7985 // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7986 // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7988 assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7992 fn test_manually_accept_inbound_channel_request() {
7993 let mut manually_accept_conf = UserConfig::default();
7994 manually_accept_conf.manually_accept_inbound_channels = true;
7995 let chanmon_cfgs = create_chanmon_cfgs(2);
7996 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7997 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7998 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8000 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();
8001 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8003 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
8005 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8006 // accepting the inbound channel request.
8007 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8009 let events = nodes[1].node.get_and_clear_pending_events();
8011 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8012 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
8014 _ => panic!("Unexpected event"),
8017 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8018 assert_eq!(accept_msg_ev.len(), 1);
8020 match accept_msg_ev[0] {
8021 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8022 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8024 _ => panic!("Unexpected event"),
8027 nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8029 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8030 assert_eq!(close_msg_ev.len(), 1);
8032 let events = nodes[1].node.get_and_clear_pending_events();
8034 Event::ChannelClosed { user_channel_id, .. } => {
8035 assert_eq!(user_channel_id, 23);
8037 _ => panic!("Unexpected event"),
8042 fn test_manually_reject_inbound_channel_request() {
8043 let mut manually_accept_conf = UserConfig::default();
8044 manually_accept_conf.manually_accept_inbound_channels = true;
8045 let chanmon_cfgs = create_chanmon_cfgs(2);
8046 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8047 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8048 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8050 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, Some(manually_accept_conf)).unwrap();
8051 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8053 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
8055 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8056 // rejecting the inbound channel request.
8057 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8059 let events = nodes[1].node.get_and_clear_pending_events();
8061 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8062 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8064 _ => panic!("Unexpected event"),
8067 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8068 assert_eq!(close_msg_ev.len(), 1);
8070 match close_msg_ev[0] {
8071 MessageSendEvent::HandleError { ref node_id, .. } => {
8072 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8074 _ => panic!("Unexpected event"),
8077 // There should be no more events to process, as the channel was never opened.
8078 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
8082 fn test_can_not_accept_inbound_channel_twice() {
8083 let mut manually_accept_conf = UserConfig::default();
8084 manually_accept_conf.manually_accept_inbound_channels = true;
8085 let chanmon_cfgs = create_chanmon_cfgs(2);
8086 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8087 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8088 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8090 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, Some(manually_accept_conf)).unwrap();
8091 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8093 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
8095 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8096 // accepting the inbound channel request.
8097 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8099 let events = nodes[1].node.get_and_clear_pending_events();
8101 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8102 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
8103 let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
8105 Err(APIError::APIMisuseError { err }) => {
8106 assert_eq!(err, "No such channel awaiting to be accepted.");
8108 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8109 Err(e) => panic!("Unexpected Error {:?}", e),
8112 _ => panic!("Unexpected event"),
8115 // Ensure that the channel wasn't closed after attempting to accept it twice.
8116 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8117 assert_eq!(accept_msg_ev.len(), 1);
8119 match accept_msg_ev[0] {
8120 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8121 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8123 _ => panic!("Unexpected event"),
8128 fn test_can_not_accept_unknown_inbound_channel() {
8129 let chanmon_cfg = create_chanmon_cfgs(2);
8130 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8131 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8132 let nodes = create_network(2, &node_cfg, &node_chanmgr);
8134 let unknown_channel_id = ChannelId::new_zero();
8135 let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
8137 Err(APIError::APIMisuseError { err }) => {
8138 assert_eq!(err, "No such channel awaiting to be accepted.");
8140 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8141 Err(e) => panic!("Unexpected Error: {:?}", e),
8146 fn test_onion_value_mpp_set_calculation() {
8147 // Test that we use the onion value `amt_to_forward` when
8148 // calculating whether we've reached the `total_msat` of an MPP
8149 // by having a routing node forward more than `amt_to_forward`
8150 // and checking that the receiving node doesn't generate
8151 // a PaymentClaimable event too early
8153 let chanmon_cfgs = create_chanmon_cfgs(node_count);
8154 let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8155 let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8156 let mut nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8158 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8159 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8160 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8161 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8163 let total_msat = 100_000;
8164 let expected_paths: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
8165 let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], total_msat);
8166 let sample_path = route.paths.pop().unwrap();
8168 let mut path_1 = sample_path.clone();
8169 path_1.hops[0].pubkey = nodes[1].node.get_our_node_id();
8170 path_1.hops[0].short_channel_id = chan_1_id;
8171 path_1.hops[1].pubkey = nodes[3].node.get_our_node_id();
8172 path_1.hops[1].short_channel_id = chan_3_id;
8173 path_1.hops[1].fee_msat = 100_000;
8174 route.paths.push(path_1);
8176 let mut path_2 = sample_path.clone();
8177 path_2.hops[0].pubkey = nodes[2].node.get_our_node_id();
8178 path_2.hops[0].short_channel_id = chan_2_id;
8179 path_2.hops[1].pubkey = nodes[3].node.get_our_node_id();
8180 path_2.hops[1].short_channel_id = chan_4_id;
8181 path_2.hops[1].fee_msat = 1_000;
8182 route.paths.push(path_2);
8185 let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
8186 let onion_session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
8187 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8188 nodes[0].node.test_send_payment_internal(&route, our_payment_hash,
8189 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8190 check_added_monitors!(nodes[0], expected_paths.len());
8192 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8193 assert_eq!(events.len(), expected_paths.len());
8196 let ev = remove_first_msg_event_to_node(&expected_paths[0][0].node.get_our_node_id(), &mut events);
8197 let mut payment_event = SendEvent::from_event(ev);
8198 let mut prev_node = &nodes[0];
8200 for (idx, &node) in expected_paths[0].iter().enumerate() {
8201 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
8203 if idx == 0 { // routing node
8204 let session_priv = [3; 32];
8205 let height = nodes[0].best_block_info().1;
8206 let session_priv = SecretKey::from_slice(&session_priv).unwrap();
8207 let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
8208 let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], 100_000,
8209 RecipientOnionFields::secret_only(our_payment_secret), height + 1, &None).unwrap();
8210 // Edit amt_to_forward to simulate the sender having set
8211 // the final amount and the routing node taking less fee
8212 if let msgs::OutboundOnionPayload::Receive { ref mut amt_msat, .. } = onion_payloads[1] {
8215 let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
8216 payment_event.msgs[0].onion_routing_packet = new_onion_packet;
8219 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
8220 check_added_monitors!(node, 0);
8221 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
8222 expect_pending_htlcs_forwardable!(node);
8225 let mut events_2 = node.node.get_and_clear_pending_msg_events();
8226 assert_eq!(events_2.len(), 1);
8227 check_added_monitors!(node, 1);
8228 payment_event = SendEvent::from_event(events_2.remove(0));
8229 assert_eq!(payment_event.msgs.len(), 1);
8231 let events_2 = node.node.get_and_clear_pending_events();
8232 assert!(events_2.is_empty());
8239 let ev = remove_first_msg_event_to_node(&expected_paths[1][0].node.get_our_node_id(), &mut events);
8240 pass_along_path(&nodes[0], expected_paths[1], 101_000, our_payment_hash.clone(), Some(our_payment_secret), ev, true, None);
8242 claim_payment_along_route(&nodes[0], expected_paths, false, our_payment_preimage);
8245 fn do_test_overshoot_mpp(msat_amounts: &[u64], total_msat: u64) {
8247 let routing_node_count = msat_amounts.len();
8248 let node_count = routing_node_count + 2;
8250 let chanmon_cfgs = create_chanmon_cfgs(node_count);
8251 let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8252 let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8253 let nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8258 // Create channels for each amount
8259 let mut expected_paths = Vec::with_capacity(routing_node_count);
8260 let mut src_chan_ids = Vec::with_capacity(routing_node_count);
8261 let mut dst_chan_ids = Vec::with_capacity(routing_node_count);
8262 for i in 0..routing_node_count {
8263 let routing_node = 2 + i;
8264 let src_chan_id = create_announced_chan_between_nodes(&nodes, src_idx, routing_node).0.contents.short_channel_id;
8265 src_chan_ids.push(src_chan_id);
8266 let dst_chan_id = create_announced_chan_between_nodes(&nodes, routing_node, dst_idx).0.contents.short_channel_id;
8267 dst_chan_ids.push(dst_chan_id);
8268 let path = vec![&nodes[routing_node], &nodes[dst_idx]];
8269 expected_paths.push(path);
8271 let expected_paths: Vec<&[&Node]> = expected_paths.iter().map(|route| route.as_slice()).collect();
8273 // Create a route for each amount
8274 let example_amount = 100000;
8275 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);
8276 let sample_path = route.paths.pop().unwrap();
8277 for i in 0..routing_node_count {
8278 let routing_node = 2 + i;
8279 let mut path = sample_path.clone();
8280 path.hops[0].pubkey = nodes[routing_node].node.get_our_node_id();
8281 path.hops[0].short_channel_id = src_chan_ids[i];
8282 path.hops[1].pubkey = nodes[dst_idx].node.get_our_node_id();
8283 path.hops[1].short_channel_id = dst_chan_ids[i];
8284 path.hops[1].fee_msat = msat_amounts[i];
8285 route.paths.push(path);
8288 // Send payment with manually set total_msat
8289 let payment_id = PaymentId(nodes[src_idx].keys_manager.backing.get_secure_random_bytes());
8290 let onion_session_privs = nodes[src_idx].node.test_add_new_pending_payment(our_payment_hash,
8291 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8292 nodes[src_idx].node.test_send_payment_internal(&route, our_payment_hash,
8293 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8294 check_added_monitors!(nodes[src_idx], expected_paths.len());
8296 let mut events = nodes[src_idx].node.get_and_clear_pending_msg_events();
8297 assert_eq!(events.len(), expected_paths.len());
8298 let mut amount_received = 0;
8299 for (path_idx, expected_path) in expected_paths.iter().enumerate() {
8300 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
8302 let current_path_amount = msat_amounts[path_idx];
8303 amount_received += current_path_amount;
8304 let became_claimable_now = amount_received >= total_msat && amount_received - current_path_amount < total_msat;
8305 pass_along_path(&nodes[src_idx], expected_path, amount_received, our_payment_hash.clone(), Some(our_payment_secret), ev, became_claimable_now, None);
8308 claim_payment_along_route(&nodes[src_idx], &expected_paths, false, our_payment_preimage);
8312 fn test_overshoot_mpp() {
8313 do_test_overshoot_mpp(&[100_000, 101_000], 200_000);
8314 do_test_overshoot_mpp(&[100_000, 10_000, 100_000], 200_000);
8318 fn test_simple_mpp() {
8319 // Simple test of sending a multi-path payment.
8320 let chanmon_cfgs = create_chanmon_cfgs(4);
8321 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8322 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8323 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8325 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8326 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8327 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8328 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8330 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8331 let path = route.paths[0].clone();
8332 route.paths.push(path);
8333 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
8334 route.paths[0].hops[0].short_channel_id = chan_1_id;
8335 route.paths[0].hops[1].short_channel_id = chan_3_id;
8336 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
8337 route.paths[1].hops[0].short_channel_id = chan_2_id;
8338 route.paths[1].hops[1].short_channel_id = chan_4_id;
8339 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8340 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8344 fn test_preimage_storage() {
8345 // Simple test of payment preimage storage allowing no client-side storage to claim payments
8346 let chanmon_cfgs = create_chanmon_cfgs(2);
8347 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8348 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8349 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8351 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8354 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
8355 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8356 nodes[0].node.send_payment_with_route(&route, payment_hash,
8357 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8358 check_added_monitors!(nodes[0], 1);
8359 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8360 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8361 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8362 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8364 // Note that after leaving the above scope we have no knowledge of any arguments or return
8365 // values from previous calls.
8366 expect_pending_htlcs_forwardable!(nodes[1]);
8367 let events = nodes[1].node.get_and_clear_pending_events();
8368 assert_eq!(events.len(), 1);
8370 Event::PaymentClaimable { ref purpose, .. } => {
8372 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8373 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8375 _ => panic!("expected PaymentPurpose::InvoicePayment")
8378 _ => panic!("Unexpected event"),
8383 fn test_bad_secret_hash() {
8384 // Simple test of unregistered payment hash/invalid payment secret handling
8385 let chanmon_cfgs = create_chanmon_cfgs(2);
8386 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8387 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8388 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8390 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8392 let random_payment_hash = PaymentHash([42; 32]);
8393 let random_payment_secret = PaymentSecret([43; 32]);
8394 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8395 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8397 // All the below cases should end up being handled exactly identically, so we macro the
8398 // resulting events.
8399 macro_rules! handle_unknown_invalid_payment_data {
8400 ($payment_hash: expr) => {
8401 check_added_monitors!(nodes[0], 1);
8402 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8403 let payment_event = SendEvent::from_event(events.pop().unwrap());
8404 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8405 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8407 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8408 // again to process the pending backwards-failure of the HTLC
8409 expect_pending_htlcs_forwardable!(nodes[1]);
8410 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8411 check_added_monitors!(nodes[1], 1);
8413 // We should fail the payment back
8414 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8415 match events.pop().unwrap() {
8416 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8417 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8418 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8420 _ => panic!("Unexpected event"),
8425 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8426 // Error data is the HTLC value (100,000) and current block height
8427 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8429 // Send a payment with the right payment hash but the wrong payment secret
8430 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
8431 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8432 handle_unknown_invalid_payment_data!(our_payment_hash);
8433 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8435 // Send a payment with a random payment hash, but the right payment secret
8436 nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8437 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8438 handle_unknown_invalid_payment_data!(random_payment_hash);
8439 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8441 // Send a payment with a random payment hash and random payment secret
8442 nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8443 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8444 handle_unknown_invalid_payment_data!(random_payment_hash);
8445 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8449 fn test_update_err_monitor_lockdown() {
8450 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8451 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8452 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8455 // This scenario may happen in a watchtower setup, where watchtower process a block height
8456 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8457 // commitment at same time.
8459 let chanmon_cfgs = create_chanmon_cfgs(2);
8460 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8461 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8462 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8464 // Create some initial channel
8465 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8466 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8468 // Rebalance the network to generate htlc in the two directions
8469 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8471 // Route a HTLC from node 0 to node 1 (but don't settle)
8472 let (preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8474 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8475 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8476 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8477 let persister = test_utils::TestPersister::new();
8480 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8481 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8482 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8483 assert!(new_monitor == *monitor);
8486 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);
8487 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), Ok(ChannelMonitorUpdateStatus::Completed));
8490 let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8491 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8492 // transaction lock time requirements here.
8493 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 200));
8494 watchtower.chain_monitor.block_connected(&block, 200);
8496 // Try to update ChannelMonitor
8497 nodes[1].node.claim_funds(preimage);
8498 check_added_monitors!(nodes[1], 1);
8499 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8501 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8502 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8503 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8505 let mut node_0_per_peer_lock;
8506 let mut node_0_peer_state_lock;
8507 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) {
8508 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8509 assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::InProgress);
8510 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8511 } else { assert!(false); }
8516 // Our local monitor is in-sync and hasn't processed yet timeout
8517 check_added_monitors!(nodes[0], 1);
8518 let events = nodes[0].node.get_and_clear_pending_events();
8519 assert_eq!(events.len(), 1);
8523 fn test_concurrent_monitor_claim() {
8524 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8525 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8526 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8527 // state N+1 confirms. Alice claims output from state N+1.
8529 let chanmon_cfgs = create_chanmon_cfgs(2);
8530 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8531 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8532 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8534 // Create some initial channel
8535 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8536 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8538 // Rebalance the network to generate htlc in the two directions
8539 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8541 // Route a HTLC from node 0 to node 1 (but don't settle)
8542 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8544 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8545 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8546 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8547 let persister = test_utils::TestPersister::new();
8548 let alice_broadcaster = test_utils::TestBroadcaster::with_blocks(
8549 Arc::new(Mutex::new(nodes[0].blocks.lock().unwrap().clone())),
8551 let watchtower_alice = {
8553 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8554 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8555 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8556 assert!(new_monitor == *monitor);
8559 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &alice_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8560 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), Ok(ChannelMonitorUpdateStatus::Completed));
8563 let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8564 // Make Alice aware of enough blocks that it doesn't think we're violating transaction lock time
8565 // requirements here.
8566 const HTLC_TIMEOUT_BROADCAST: u32 = CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS;
8567 alice_broadcaster.blocks.lock().unwrap().resize((HTLC_TIMEOUT_BROADCAST) as usize, (block.clone(), HTLC_TIMEOUT_BROADCAST));
8568 watchtower_alice.chain_monitor.block_connected(&block, HTLC_TIMEOUT_BROADCAST);
8570 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8572 let mut txn = alice_broadcaster.txn_broadcast();
8573 assert_eq!(txn.len(), 2);
8577 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8578 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8579 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8580 let persister = test_utils::TestPersister::new();
8581 let bob_broadcaster = test_utils::TestBroadcaster::with_blocks(Arc::clone(&alice_broadcaster.blocks));
8582 let watchtower_bob = {
8584 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8585 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8586 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8587 assert!(new_monitor == *monitor);
8590 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &bob_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8591 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), Ok(ChannelMonitorUpdateStatus::Completed));
8594 watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST - 1);
8596 // Route another payment to generate another update with still previous HTLC pending
8597 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8598 nodes[1].node.send_payment_with_route(&route, payment_hash,
8599 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8600 check_added_monitors!(nodes[1], 1);
8602 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8603 assert_eq!(updates.update_add_htlcs.len(), 1);
8604 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8606 let mut node_0_per_peer_lock;
8607 let mut node_0_peer_state_lock;
8608 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) {
8609 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8610 // Watchtower Alice should already have seen the block and reject the update
8611 assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::InProgress);
8612 assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8613 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8614 } else { assert!(false); }
8619 // Our local monitor is in-sync and hasn't processed yet timeout
8620 check_added_monitors!(nodes[0], 1);
8622 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8623 watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST);
8625 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8628 let mut txn = bob_broadcaster.txn_broadcast();
8629 assert_eq!(txn.len(), 2);
8630 bob_state_y = txn.remove(0);
8633 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8634 let height = HTLC_TIMEOUT_BROADCAST + 1;
8635 connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
8636 check_closed_broadcast(&nodes[0], 1, true);
8637 check_closed_event!(&nodes[0], 1, ClosureReason::HolderForceClosed, false,
8638 [nodes[1].node.get_our_node_id()], 100000);
8639 watchtower_alice.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, vec![bob_state_y.clone()]), height);
8640 check_added_monitors(&nodes[0], 1);
8642 let htlc_txn = alice_broadcaster.txn_broadcast();
8643 assert_eq!(htlc_txn.len(), 2);
8644 check_spends!(htlc_txn[0], bob_state_y);
8645 // Alice doesn't clean up the old HTLC claim since it hasn't seen a conflicting spend for
8646 // it. However, she should, because it now has an invalid parent.
8647 check_spends!(htlc_txn[1], alice_state);
8652 fn test_pre_lockin_no_chan_closed_update() {
8653 // Test that if a peer closes a channel in response to a funding_created message we don't
8654 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8657 // Doing so would imply a channel monitor update before the initial channel monitor
8658 // registration, violating our API guarantees.
8660 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8661 // then opening a second channel with the same funding output as the first (which is not
8662 // rejected because the first channel does not exist in the ChannelManager) and closing it
8663 // before receiving funding_signed.
8664 let chanmon_cfgs = create_chanmon_cfgs(2);
8665 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8666 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8667 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8669 // Create an initial channel
8670 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
8671 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8672 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8673 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8674 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8676 // Move the first channel through the funding flow...
8677 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8679 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8680 check_added_monitors!(nodes[0], 0);
8682 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8683 let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8684 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8685 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8686 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("Hi".to_string()) }, true,
8687 [nodes[1].node.get_our_node_id()], 100000);
8691 fn test_htlc_no_detection() {
8692 // This test is a mutation to underscore the detection logic bug we had
8693 // before #653. HTLC value routed is above the remaining balance, thus
8694 // inverting HTLC and `to_remote` output. HTLC will come second and
8695 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8696 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8697 // outputs order detection for correct spending children filtring.
8699 let chanmon_cfgs = create_chanmon_cfgs(2);
8700 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8701 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8702 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8704 // Create some initial channels
8705 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8707 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8708 let (_, our_payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8709 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8710 assert_eq!(local_txn[0].input.len(), 1);
8711 assert_eq!(local_txn[0].output.len(), 3);
8712 check_spends!(local_txn[0], chan_1.3);
8714 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8715 let block = create_dummy_block(nodes[0].best_block_hash(), 42, vec![local_txn[0].clone()]);
8716 connect_block(&nodes[0], &block);
8717 // We deliberately connect the local tx twice as this should provoke a failure calling
8718 // this test before #653 fix.
8719 chain::Listen::block_connected(&nodes[0].chain_monitor.chain_monitor, &block, nodes[0].best_block_info().1 + 1);
8720 check_closed_broadcast!(nodes[0], true);
8721 check_added_monitors!(nodes[0], 1);
8722 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
8723 connect_blocks(&nodes[0], TEST_FINAL_CLTV);
8725 let htlc_timeout = {
8726 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8727 assert_eq!(node_txn.len(), 1);
8728 assert_eq!(node_txn[0].input.len(), 1);
8729 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8730 check_spends!(node_txn[0], local_txn[0]);
8734 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![htlc_timeout.clone()]));
8735 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8736 expect_payment_failed!(nodes[0], our_payment_hash, false);
8739 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8740 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8741 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8742 // Carol, Alice would be the upstream node, and Carol the downstream.)
8744 // Steps of the test:
8745 // 1) Alice sends a HTLC to Carol through Bob.
8746 // 2) Carol doesn't settle the HTLC.
8747 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8748 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8749 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8750 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8751 // 5) Carol release the preimage to Bob off-chain.
8752 // 6) Bob claims the offered output on the broadcasted commitment.
8753 let chanmon_cfgs = create_chanmon_cfgs(3);
8754 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8755 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8756 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8758 // Create some initial channels
8759 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8760 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8762 // Steps (1) and (2):
8763 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8764 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8766 // Check that Alice's commitment transaction now contains an output for this HTLC.
8767 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8768 check_spends!(alice_txn[0], chan_ab.3);
8769 assert_eq!(alice_txn[0].output.len(), 2);
8770 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8771 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8772 assert_eq!(alice_txn.len(), 2);
8774 // Steps (3) and (4):
8775 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8776 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8777 let mut force_closing_node = 0; // Alice force-closes
8778 let mut counterparty_node = 1; // Bob if Alice force-closes
8781 if !broadcast_alice {
8782 force_closing_node = 1;
8783 counterparty_node = 0;
8785 nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8786 check_closed_broadcast!(nodes[force_closing_node], true);
8787 check_added_monitors!(nodes[force_closing_node], 1);
8788 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed, [nodes[counterparty_node].node.get_our_node_id()], 100000);
8789 if go_onchain_before_fulfill {
8790 let txn_to_broadcast = match broadcast_alice {
8791 true => alice_txn.clone(),
8792 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8794 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8795 if broadcast_alice {
8796 check_closed_broadcast!(nodes[1], true);
8797 check_added_monitors!(nodes[1], 1);
8798 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
8803 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8804 // process of removing the HTLC from their commitment transactions.
8805 nodes[2].node.claim_funds(payment_preimage);
8806 check_added_monitors!(nodes[2], 1);
8807 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8809 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8810 assert!(carol_updates.update_add_htlcs.is_empty());
8811 assert!(carol_updates.update_fail_htlcs.is_empty());
8812 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8813 assert!(carol_updates.update_fee.is_none());
8814 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8816 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8817 let went_onchain = go_onchain_before_fulfill || force_closing_node == 1;
8818 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if went_onchain { None } else { Some(1000) }, went_onchain, false);
8819 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8820 if !go_onchain_before_fulfill && broadcast_alice {
8821 let events = nodes[1].node.get_and_clear_pending_msg_events();
8822 assert_eq!(events.len(), 1);
8824 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8825 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8827 _ => panic!("Unexpected event"),
8830 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8831 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8832 // Carol<->Bob's updated commitment transaction info.
8833 check_added_monitors!(nodes[1], 2);
8835 let events = nodes[1].node.get_and_clear_pending_msg_events();
8836 assert_eq!(events.len(), 2);
8837 let bob_revocation = match events[0] {
8838 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8839 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8842 _ => panic!("Unexpected event"),
8844 let bob_updates = match events[1] {
8845 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8846 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8849 _ => panic!("Unexpected event"),
8852 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8853 check_added_monitors!(nodes[2], 1);
8854 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8855 check_added_monitors!(nodes[2], 1);
8857 let events = nodes[2].node.get_and_clear_pending_msg_events();
8858 assert_eq!(events.len(), 1);
8859 let carol_revocation = match events[0] {
8860 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8861 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8864 _ => panic!("Unexpected event"),
8866 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8867 check_added_monitors!(nodes[1], 1);
8869 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8870 // here's where we put said channel's commitment tx on-chain.
8871 let mut txn_to_broadcast = alice_txn.clone();
8872 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8873 if !go_onchain_before_fulfill {
8874 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8875 // If Bob was the one to force-close, he will have already passed these checks earlier.
8876 if broadcast_alice {
8877 check_closed_broadcast!(nodes[1], true);
8878 check_added_monitors!(nodes[1], 1);
8879 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
8881 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8882 if broadcast_alice {
8883 assert_eq!(bob_txn.len(), 1);
8884 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8886 assert_eq!(bob_txn.len(), 2);
8887 check_spends!(bob_txn[0], chan_ab.3);
8892 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8893 // broadcasted commitment transaction.
8895 let script_weight = match broadcast_alice {
8896 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8897 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8899 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8900 // Bob force-closed and broadcasts the commitment transaction along with a
8901 // HTLC-output-claiming transaction.
8902 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8903 if broadcast_alice {
8904 assert_eq!(bob_txn.len(), 1);
8905 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8906 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8908 assert_eq!(bob_txn.len(), 2);
8909 check_spends!(bob_txn[1], txn_to_broadcast[0]);
8910 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8916 fn test_onchain_htlc_settlement_after_close() {
8917 do_test_onchain_htlc_settlement_after_close(true, true);
8918 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8919 do_test_onchain_htlc_settlement_after_close(true, false);
8920 do_test_onchain_htlc_settlement_after_close(false, false);
8924 fn test_duplicate_temporary_channel_id_from_different_peers() {
8925 // Tests that we can accept two different `OpenChannel` requests with the same
8926 // `temporary_channel_id`, as long as they are from different peers.
8927 let chanmon_cfgs = create_chanmon_cfgs(3);
8928 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8929 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8930 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8932 // Create an first channel channel
8933 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
8934 let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8936 // Create an second channel
8937 nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None, None).unwrap();
8938 let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8940 // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8941 // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8942 open_chan_msg_chan_2_0.temporary_channel_id = open_chan_msg_chan_1_0.temporary_channel_id;
8944 // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8945 // `temporary_channel_id` as they are from different peers.
8946 nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
8948 let events = nodes[0].node.get_and_clear_pending_msg_events();
8949 assert_eq!(events.len(), 1);
8951 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8952 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8953 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8955 _ => panic!("Unexpected event"),
8959 nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
8961 let events = nodes[0].node.get_and_clear_pending_msg_events();
8962 assert_eq!(events.len(), 1);
8964 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8965 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
8966 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8968 _ => panic!("Unexpected event"),
8974 fn test_duplicate_chan_id() {
8975 // Test that if a given peer tries to open a channel with the same channel_id as one that is
8976 // already open we reject it and keep the old channel.
8978 // Previously, full_stack_target managed to figure out that if you tried to open two channels
8979 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8980 // the existing channel when we detect the duplicate new channel, screwing up our monitor
8981 // updating logic for the existing channel.
8982 let chanmon_cfgs = create_chanmon_cfgs(2);
8983 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8984 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8985 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8987 // Create an initial channel
8988 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
8989 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8990 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8991 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()));
8993 // Try to create a second channel with the same temporary_channel_id as the first and check
8994 // that it is rejected.
8995 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8997 let events = nodes[1].node.get_and_clear_pending_msg_events();
8998 assert_eq!(events.len(), 1);
9000 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9001 // Technically, at this point, nodes[1] would be justified in thinking both the
9002 // first (valid) and second (invalid) channels are closed, given they both have
9003 // the same non-temporary channel_id. However, currently we do not, so we just
9004 // move forward with it.
9005 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9006 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9008 _ => panic!("Unexpected event"),
9012 // Move the first channel through the funding flow...
9013 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9015 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9016 check_added_monitors!(nodes[0], 0);
9018 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9019 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9021 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9022 assert_eq!(added_monitors.len(), 1);
9023 assert_eq!(added_monitors[0].0, funding_output);
9024 added_monitors.clear();
9026 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9028 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9030 let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
9031 let channel_id = funding_outpoint.to_channel_id();
9033 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
9036 // First try to open a second channel with a temporary channel id equal to the txid-based one.
9037 // Technically this is allowed by the spec, but we don't support it and there's little reason
9038 // to. Still, it shouldn't cause any other issues.
9039 open_chan_msg.temporary_channel_id = channel_id;
9040 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
9042 let events = nodes[1].node.get_and_clear_pending_msg_events();
9043 assert_eq!(events.len(), 1);
9045 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9046 // Technically, at this point, nodes[1] would be justified in thinking both
9047 // channels are closed, but currently we do not, so we just move forward with it.
9048 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9049 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9051 _ => panic!("Unexpected event"),
9055 // Now try to create a second channel which has a duplicate funding output.
9056 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
9057 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9058 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
9059 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()));
9060 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
9062 let funding_created = {
9063 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9064 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9065 // Once we call `get_funding_created` the channel has a duplicate channel_id as
9066 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
9067 // try to create another channel. Instead, we drop the channel entirely here (leaving the
9068 // channelmanager in a possibly nonsense state instead).
9069 match a_peer_state.channel_by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap() {
9070 ChannelPhase::UnfundedOutboundV1(mut chan) => {
9071 let logger = test_utils::TestLogger::new();
9072 chan.get_funding_created(tx.clone(), funding_outpoint, false, &&logger).map_err(|_| ()).unwrap()
9074 _ => panic!("Unexpected ChannelPhase variant"),
9077 check_added_monitors!(nodes[0], 0);
9078 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created.unwrap());
9079 // At this point we'll look up if the channel_id is present and immediately fail the channel
9080 // without trying to persist the `ChannelMonitor`.
9081 check_added_monitors!(nodes[1], 0);
9083 // ...still, nodes[1] will reject the duplicate channel.
9085 let events = nodes[1].node.get_and_clear_pending_msg_events();
9086 assert_eq!(events.len(), 1);
9088 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9089 // Technically, at this point, nodes[1] would be justified in thinking both
9090 // channels are closed, but currently we do not, so we just move forward with it.
9091 assert_eq!(msg.channel_id, channel_id);
9092 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9094 _ => panic!("Unexpected event"),
9098 // finally, finish creating the original channel and send a payment over it to make sure
9099 // everything is functional.
9100 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9102 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9103 assert_eq!(added_monitors.len(), 1);
9104 assert_eq!(added_monitors[0].0, funding_output);
9105 added_monitors.clear();
9107 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9109 let events_4 = nodes[0].node.get_and_clear_pending_events();
9110 assert_eq!(events_4.len(), 0);
9111 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9112 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9114 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9115 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9116 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9118 send_payment(&nodes[0], &[&nodes[1]], 8000000);
9122 fn test_error_chans_closed() {
9123 // Test that we properly handle error messages, closing appropriate channels.
9125 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9126 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9127 // we can test various edge cases around it to ensure we don't regress.
9128 let chanmon_cfgs = create_chanmon_cfgs(3);
9129 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9130 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9131 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9133 // Create some initial channels
9134 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9135 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9136 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
9138 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9139 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9140 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9142 // Closing a channel from a different peer has no effect
9143 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9144 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9146 // Closing one channel doesn't impact others
9147 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9148 check_added_monitors!(nodes[0], 1);
9149 check_closed_broadcast!(nodes[0], false);
9150 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) },
9151 [nodes[1].node.get_our_node_id()], 100000);
9152 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9153 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9154 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);
9155 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);
9157 // A null channel ID should close all channels
9158 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9159 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: ChannelId::new_zero(), data: "ERR".to_owned() });
9160 check_added_monitors!(nodes[0], 2);
9161 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) },
9162 [nodes[1].node.get_our_node_id(); 2], 100000);
9163 let events = nodes[0].node.get_and_clear_pending_msg_events();
9164 assert_eq!(events.len(), 2);
9166 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9167 assert_eq!(msg.contents.flags & 2, 2);
9169 _ => panic!("Unexpected event"),
9172 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9173 assert_eq!(msg.contents.flags & 2, 2);
9175 _ => panic!("Unexpected event"),
9177 // Note that at this point users of a standard PeerHandler will end up calling
9178 // peer_disconnected.
9179 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9180 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9182 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9183 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9184 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9188 fn test_invalid_funding_tx() {
9189 // Test that we properly handle invalid funding transactions sent to us from a peer.
9191 // Previously, all other major lightning implementations had failed to properly sanitize
9192 // funding transactions from their counterparties, leading to a multi-implementation critical
9193 // security vulnerability (though we always sanitized properly, we've previously had
9194 // un-released crashes in the sanitization process).
9196 // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9197 // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9198 // gave up on it. We test this here by generating such a transaction.
9199 let chanmon_cfgs = create_chanmon_cfgs(2);
9200 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9201 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9202 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9204 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None, None).unwrap();
9205 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()));
9206 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()));
9208 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9210 // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9211 // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9212 // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9214 let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9215 let wit_program_script: ScriptBuf = wit_program.into();
9216 for output in tx.output.iter_mut() {
9217 // Make the confirmed funding transaction have a bogus script_pubkey
9218 output.script_pubkey = ScriptBuf::new_v0_p2wsh(&wit_program_script.wscript_hash());
9221 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9222 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()));
9223 check_added_monitors!(nodes[1], 1);
9224 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9226 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()));
9227 check_added_monitors!(nodes[0], 1);
9228 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9230 let events_1 = nodes[0].node.get_and_clear_pending_events();
9231 assert_eq!(events_1.len(), 0);
9233 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9234 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9235 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9237 let expected_err = "funding tx had wrong script/value or output index";
9238 confirm_transaction_at(&nodes[1], &tx, 1);
9239 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() },
9240 [nodes[0].node.get_our_node_id()], 100000);
9241 check_added_monitors!(nodes[1], 1);
9242 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9243 assert_eq!(events_2.len(), 1);
9244 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9245 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9246 if let msgs::ErrorAction::DisconnectPeer { msg } = action {
9247 assert_eq!(msg.as_ref().unwrap().data, "Channel closed because of an exception: ".to_owned() + expected_err);
9248 } else { panic!(); }
9249 } else { panic!(); }
9250 assert_eq!(nodes[1].node.list_channels().len(), 0);
9252 // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9253 // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9254 // as its not 32 bytes long.
9255 let mut spend_tx = Transaction {
9256 version: 2i32, lock_time: LockTime::ZERO,
9257 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9258 previous_output: BitcoinOutPoint {
9262 script_sig: ScriptBuf::new(),
9263 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9264 witness: Witness::from_slice(&channelmonitor::deliberately_bogus_accepted_htlc_witness())
9266 output: vec![TxOut {
9268 script_pubkey: ScriptBuf::new(),
9271 check_spends!(spend_tx, tx);
9272 mine_transaction(&nodes[1], &spend_tx);
9276 fn test_coinbase_funding_tx() {
9277 // Miners are able to fund channels directly from coinbase transactions, however
9278 // by consensus rules, outputs of a coinbase transaction are encumbered by a 100
9279 // block maturity timelock. To ensure that a (non-0conf) channel like this is enforceable
9280 // on-chain, the minimum depth is updated to 100 blocks for coinbase funding transactions.
9282 // Note that 0conf channels with coinbase funding transactions are unaffected and are
9283 // immediately operational after opening.
9284 let chanmon_cfgs = create_chanmon_cfgs(2);
9285 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9286 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9287 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9289 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
9290 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9292 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9293 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9295 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9297 // Create the coinbase funding transaction.
9298 let (temporary_channel_id, tx, _) = create_coinbase_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9300 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9301 check_added_monitors!(nodes[0], 0);
9302 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9304 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9305 check_added_monitors!(nodes[1], 1);
9306 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9308 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9310 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
9311 check_added_monitors!(nodes[0], 1);
9313 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9314 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
9316 // Starting at height 0, we "confirm" the coinbase at height 1.
9317 confirm_transaction_at(&nodes[0], &tx, 1);
9318 // We connect 98 more blocks to have 99 confirmations for the coinbase transaction.
9319 connect_blocks(&nodes[0], COINBASE_MATURITY - 2);
9320 // Check that we have no pending message events (we have not queued a `channel_ready` yet).
9321 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
9322 // Now connect one more block which results in 100 confirmations of the coinbase transaction.
9323 connect_blocks(&nodes[0], 1);
9324 // There should now be a `channel_ready` which can be handled.
9325 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()));
9327 confirm_transaction_at(&nodes[1], &tx, 1);
9328 connect_blocks(&nodes[1], COINBASE_MATURITY - 2);
9329 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9330 connect_blocks(&nodes[1], 1);
9331 expect_channel_ready_event(&nodes[1], &nodes[0].node.get_our_node_id());
9332 create_chan_between_nodes_with_value_confirm_second(&nodes[0], &nodes[1]);
9335 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9336 // In the first version of the chain::Confirm interface, after a refactor was made to not
9337 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9338 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9339 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9340 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9341 // spending transaction until height N+1 (or greater). This was due to the way
9342 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9343 // spending transaction at the height the input transaction was confirmed at, not whether we
9344 // should broadcast a spending transaction at the current height.
9345 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9346 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9347 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9348 // until we learned about an additional block.
9350 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9351 // aren't broadcasting transactions too early (ie not broadcasting them at all).
9352 let chanmon_cfgs = create_chanmon_cfgs(3);
9353 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9354 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9355 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9356 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9358 create_announced_chan_between_nodes(&nodes, 0, 1);
9359 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
9360 let (_, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9361 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
9362 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9364 nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9365 check_closed_broadcast!(nodes[1], true);
9366 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[2].node.get_our_node_id()], 100000);
9367 check_added_monitors!(nodes[1], 1);
9368 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9369 assert_eq!(node_txn.len(), 1);
9371 let conf_height = nodes[1].best_block_info().1;
9372 if !test_height_before_timelock {
9373 connect_blocks(&nodes[1], 24 * 6);
9375 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9376 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9377 if test_height_before_timelock {
9378 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9379 // generate any events or broadcast any transactions
9380 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9381 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9383 // We should broadcast an HTLC transaction spending our funding transaction first
9384 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9385 assert_eq!(spending_txn.len(), 2);
9386 assert_eq!(spending_txn[0].txid(), node_txn[0].txid());
9387 check_spends!(spending_txn[1], node_txn[0]);
9388 // We should also generate a SpendableOutputs event with the to_self output (as its
9390 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9391 assert_eq!(descriptor_spend_txn.len(), 1);
9393 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9394 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9395 // additional block built on top of the current chain.
9396 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9397 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9398 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 }]);
9399 check_added_monitors!(nodes[1], 1);
9401 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9402 assert!(updates.update_add_htlcs.is_empty());
9403 assert!(updates.update_fulfill_htlcs.is_empty());
9404 assert_eq!(updates.update_fail_htlcs.len(), 1);
9405 assert!(updates.update_fail_malformed_htlcs.is_empty());
9406 assert!(updates.update_fee.is_none());
9407 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9408 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9409 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9414 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9415 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9416 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9419 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9420 let chanmon_cfgs = create_chanmon_cfgs(2);
9421 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9422 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9423 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9425 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9427 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9428 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
9429 let route = get_route!(nodes[0], payment_params, 10_000).unwrap();
9431 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9434 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9435 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9436 check_added_monitors!(nodes[0], 1);
9437 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9438 assert_eq!(events.len(), 1);
9439 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9440 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9441 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9443 expect_pending_htlcs_forwardable!(nodes[1]);
9444 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9447 // Note that we use a different PaymentId here to allow us to duplicativly pay
9448 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9449 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9450 check_added_monitors!(nodes[0], 1);
9451 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9452 assert_eq!(events.len(), 1);
9453 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9454 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9455 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9456 // At this point, nodes[1] would notice it has too much value for the payment. It will
9457 // assume the second is a privacy attack (no longer particularly relevant
9458 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9459 // the first HTLC delivered above.
9462 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9463 nodes[1].node.process_pending_htlc_forwards();
9465 if test_for_second_fail_panic {
9466 // Now we go fail back the first HTLC from the user end.
9467 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9469 let expected_destinations = vec![
9470 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9471 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9473 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], expected_destinations);
9474 nodes[1].node.process_pending_htlc_forwards();
9476 check_added_monitors!(nodes[1], 1);
9477 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9478 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9480 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9481 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9482 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9484 let failure_events = nodes[0].node.get_and_clear_pending_events();
9485 assert_eq!(failure_events.len(), 4);
9486 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9487 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9488 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9489 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9491 // Let the second HTLC fail and claim the first
9492 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9493 nodes[1].node.process_pending_htlc_forwards();
9495 check_added_monitors!(nodes[1], 1);
9496 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9497 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9498 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9500 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9502 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9507 fn test_dup_htlc_second_fail_panic() {
9508 // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9509 // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9510 // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9511 // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9512 do_test_dup_htlc_second_rejected(true);
9516 fn test_dup_htlc_second_rejected() {
9517 // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9518 // simply reject the second HTLC but are still able to claim the first HTLC.
9519 do_test_dup_htlc_second_rejected(false);
9523 fn test_inconsistent_mpp_params() {
9524 // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9525 // such HTLC and allow the second to stay.
9526 let chanmon_cfgs = create_chanmon_cfgs(4);
9527 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9528 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9529 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9531 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9532 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9533 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9534 let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9536 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9537 .with_bolt11_features(nodes[3].node.bolt11_invoice_features()).unwrap();
9538 let mut route = get_route!(nodes[0], payment_params, 15_000_000).unwrap();
9539 assert_eq!(route.paths.len(), 2);
9540 route.paths.sort_by(|path_a, _| {
9541 // Sort the path so that the path through nodes[1] comes first
9542 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9543 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9546 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9548 let cur_height = nodes[0].best_block_info().1;
9549 let payment_id = PaymentId([42; 32]);
9551 let session_privs = {
9552 // We create a fake route here so that we start with three pending HTLCs, which we'll
9553 // ultimately have, just not right away.
9554 let mut dup_route = route.clone();
9555 dup_route.paths.push(route.paths[1].clone());
9556 nodes[0].node.test_add_new_pending_payment(our_payment_hash,
9557 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &dup_route).unwrap()
9559 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
9560 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9561 &None, session_privs[0]).unwrap();
9562 check_added_monitors!(nodes[0], 1);
9565 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9566 assert_eq!(events.len(), 1);
9567 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9569 assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9571 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9572 RecipientOnionFields::secret_only(our_payment_secret), 14_000_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9573 check_added_monitors!(nodes[0], 1);
9576 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9577 assert_eq!(events.len(), 1);
9578 let payment_event = SendEvent::from_event(events.pop().unwrap());
9580 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9581 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9583 expect_pending_htlcs_forwardable!(nodes[2]);
9584 check_added_monitors!(nodes[2], 1);
9586 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9587 assert_eq!(events.len(), 1);
9588 let payment_event = SendEvent::from_event(events.pop().unwrap());
9590 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9591 check_added_monitors!(nodes[3], 0);
9592 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9594 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9595 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9596 // post-payment_secrets) and fail back the new HTLC.
9598 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9599 nodes[3].node.process_pending_htlc_forwards();
9600 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9601 nodes[3].node.process_pending_htlc_forwards();
9603 check_added_monitors!(nodes[3], 1);
9605 let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9606 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9607 commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9609 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 }]);
9610 check_added_monitors!(nodes[2], 1);
9612 let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9613 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9614 commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9616 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9618 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9619 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9620 &None, session_privs[2]).unwrap();
9621 check_added_monitors!(nodes[0], 1);
9623 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9624 assert_eq!(events.len(), 1);
9625 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9627 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9628 expect_payment_sent(&nodes[0], our_payment_preimage, Some(None), true, true);
9632 fn test_double_partial_claim() {
9633 // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9634 // time out, the sender resends only some of the MPP parts, then the user processes the
9635 // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9637 let chanmon_cfgs = create_chanmon_cfgs(4);
9638 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9639 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9640 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9642 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9643 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9644 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9645 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9647 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9648 assert_eq!(route.paths.len(), 2);
9649 route.paths.sort_by(|path_a, _| {
9650 // Sort the path so that the path through nodes[1] comes first
9651 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9652 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9655 send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9656 // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9657 // amount of time to respond to.
9659 // Connect some blocks to time out the payment
9660 connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9661 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9663 let failed_destinations = vec![
9664 HTLCDestination::FailedPayment { payment_hash },
9665 HTLCDestination::FailedPayment { payment_hash },
9667 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9669 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
9671 // nodes[1] now retries one of the two paths...
9672 nodes[0].node.send_payment_with_route(&route, payment_hash,
9673 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9674 check_added_monitors!(nodes[0], 2);
9676 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9677 assert_eq!(events.len(), 2);
9678 let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
9679 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9681 // At this point nodes[3] has received one half of the payment, and the user goes to handle
9682 // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9683 nodes[3].node.claim_funds(payment_preimage);
9684 check_added_monitors!(nodes[3], 0);
9685 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9688 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9689 #[derive(Clone, Copy, PartialEq)]
9690 enum ExposureEvent {
9691 /// Breach occurs at HTLC forwarding (see `send_htlc`)
9693 /// Breach occurs at HTLC reception (see `update_add_htlc`)
9695 /// Breach occurs at outbound update_fee (see `send_update_fee`)
9696 AtUpdateFeeOutbound,
9699 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool, multiplier_dust_limit: bool) {
9700 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9703 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9704 // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9705 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9706 // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9707 // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9708 // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9709 // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9710 // might be available again for HTLC processing once the dust bandwidth has cleared up.
9712 let chanmon_cfgs = create_chanmon_cfgs(2);
9713 let mut config = test_default_channel_config();
9714 config.channel_config.max_dust_htlc_exposure = if multiplier_dust_limit {
9715 // Default test fee estimator rate is 253 sat/kw, so we set the multiplier to 5_000_000 / 253
9716 // to get roughly the same initial value as the default setting when this test was
9717 // originally written.
9718 MaxDustHTLCExposure::FeeRateMultiplier(5_000_000 / 253)
9719 } else { MaxDustHTLCExposure::FixedLimitMsat(5_000_000) }; // initial default setting value
9720 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9721 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9722 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9724 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None, None).unwrap();
9725 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9726 open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9727 open_channel.max_accepted_htlcs = 60;
9729 open_channel.dust_limit_satoshis = 546;
9731 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9732 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9733 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9735 let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
9737 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9740 let mut node_0_per_peer_lock;
9741 let mut node_0_peer_state_lock;
9742 match get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, temporary_channel_id) {
9743 ChannelPhase::UnfundedOutboundV1(chan) => {
9744 chan.context.holder_dust_limit_satoshis = 546;
9746 _ => panic!("Unexpected ChannelPhase variant"),
9750 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9751 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()));
9752 check_added_monitors!(nodes[1], 1);
9753 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9755 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()));
9756 check_added_monitors!(nodes[0], 1);
9757 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9759 let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9760 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9761 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9763 // Fetch a route in advance as we will be unable to once we're unable to send.
9764 let (mut route, payment_hash, _, payment_secret) =
9765 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
9767 let (dust_buffer_feerate, max_dust_htlc_exposure_msat) = {
9768 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9769 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9770 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
9771 (chan.context().get_dust_buffer_feerate(None) as u64,
9772 chan.context().get_max_dust_htlc_exposure_msat(&LowerBoundedFeeEstimator(nodes[0].fee_estimator)))
9774 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;
9775 let dust_outbound_htlc_on_holder_tx: u64 = max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9777 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;
9778 let dust_inbound_htlc_on_holder_tx: u64 = max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9780 let dust_htlc_on_counterparty_tx: u64 = 4;
9781 let dust_htlc_on_counterparty_tx_msat: u64 = max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9784 if dust_outbound_balance {
9785 // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9786 // Outbound dust balance: 4372 sats
9787 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9788 for _ in 0..dust_outbound_htlc_on_holder_tx {
9789 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9790 nodes[0].node.send_payment_with_route(&route, payment_hash,
9791 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9794 // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9795 // Inbound dust balance: 4372 sats
9796 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9797 for _ in 0..dust_inbound_htlc_on_holder_tx {
9798 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9802 if dust_outbound_balance {
9803 // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9804 // Outbound dust balance: 5000 sats
9805 for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9806 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9807 nodes[0].node.send_payment_with_route(&route, payment_hash,
9808 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9811 // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9812 // Inbound dust balance: 5000 sats
9813 for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9814 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9819 if exposure_breach_event == ExposureEvent::AtHTLCForward {
9820 route.paths[0].hops.last_mut().unwrap().fee_msat =
9821 if on_holder_tx { dust_outbound_htlc_on_holder_tx_msat } else { dust_htlc_on_counterparty_tx_msat + 1 };
9822 // With default dust exposure: 5000 sats
9824 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9825 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9826 ), true, APIError::ChannelUnavailable { .. }, {});
9828 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9829 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9830 ), true, APIError::ChannelUnavailable { .. }, {});
9832 } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9833 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 });
9834 nodes[1].node.send_payment_with_route(&route, payment_hash,
9835 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9836 check_added_monitors!(nodes[1], 1);
9837 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9838 assert_eq!(events.len(), 1);
9839 let payment_event = SendEvent::from_event(events.remove(0));
9840 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9841 // With default dust exposure: 5000 sats
9843 // Outbound dust balance: 6399 sats
9844 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9845 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9846 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);
9848 // Outbound dust balance: 5200 sats
9849 nodes[0].logger.assert_log("lightning::ln::channel",
9850 format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx",
9851 dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx - 1) + dust_htlc_on_counterparty_tx_msat + 4,
9852 max_dust_htlc_exposure_msat), 1);
9854 } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9855 route.paths[0].hops.last_mut().unwrap().fee_msat = 2_500_000;
9856 // For the multiplier dust exposure limit, since it scales with feerate,
9857 // we need to add a lot of HTLCs that will become dust at the new feerate
9858 // to cross the threshold.
9860 let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[1], Some(1_000), None);
9861 nodes[0].node.send_payment_with_route(&route, payment_hash,
9862 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9865 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9866 *feerate_lock = *feerate_lock * 10;
9868 nodes[0].node.timer_tick_occurred();
9869 check_added_monitors!(nodes[0], 1);
9870 nodes[0].logger.assert_log_contains("lightning::ln::channel", "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure", 1);
9873 let _ = nodes[0].node.get_and_clear_pending_msg_events();
9874 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9875 added_monitors.clear();
9878 fn do_test_max_dust_htlc_exposure_by_threshold_type(multiplier_dust_limit: bool) {
9879 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true, multiplier_dust_limit);
9880 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true, multiplier_dust_limit);
9881 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true, multiplier_dust_limit);
9882 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false, multiplier_dust_limit);
9883 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false, multiplier_dust_limit);
9884 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false, multiplier_dust_limit);
9885 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true, multiplier_dust_limit);
9886 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false, multiplier_dust_limit);
9887 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true, multiplier_dust_limit);
9888 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false, multiplier_dust_limit);
9889 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false, multiplier_dust_limit);
9890 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true, multiplier_dust_limit);
9894 fn test_max_dust_htlc_exposure() {
9895 do_test_max_dust_htlc_exposure_by_threshold_type(false);
9896 do_test_max_dust_htlc_exposure_by_threshold_type(true);
9900 fn test_non_final_funding_tx() {
9901 let chanmon_cfgs = create_chanmon_cfgs(2);
9902 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9903 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9904 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9906 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
9907 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9908 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9909 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9910 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
9912 let best_height = nodes[0].node.best_block.read().unwrap().height();
9914 let chan_id = *nodes[0].network_chan_count.borrow();
9915 let events = nodes[0].node.get_and_clear_pending_events();
9916 let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::ScriptBuf::new(), sequence: Sequence(1), witness: Witness::from_slice(&[&[1]]) };
9917 assert_eq!(events.len(), 1);
9918 let mut tx = match events[0] {
9919 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9920 // Timelock the transaction _beyond_ the best client height + 1.
9921 Transaction { version: chan_id as i32, lock_time: LockTime::from_height(best_height + 2).unwrap(), input: vec![input], output: vec![TxOut {
9922 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9925 _ => panic!("Unexpected event"),
9927 // Transaction should fail as it's evaluated as non-final for propagation.
9928 match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
9929 Err(APIError::APIMisuseError { err }) => {
9930 assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
9934 let events = nodes[0].node.get_and_clear_pending_events();
9935 assert_eq!(events.len(), 1);
9937 Event::ChannelClosed { channel_id, .. } => {
9938 assert_eq!(channel_id, temp_channel_id);
9940 _ => panic!("Unexpected event"),
9945 fn test_non_final_funding_tx_within_headroom() {
9946 let chanmon_cfgs = create_chanmon_cfgs(2);
9947 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9948 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9949 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9951 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
9952 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9953 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9954 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9955 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
9957 let best_height = nodes[0].node.best_block.read().unwrap().height();
9959 let chan_id = *nodes[0].network_chan_count.borrow();
9960 let events = nodes[0].node.get_and_clear_pending_events();
9961 let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::ScriptBuf::new(), sequence: Sequence(1), witness: Witness::from_slice(&[[1]]) };
9962 assert_eq!(events.len(), 1);
9963 let mut tx = match events[0] {
9964 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9965 // Timelock the transaction within a +1 headroom from the best block.
9966 Transaction { version: chan_id as i32, lock_time: LockTime::from_consensus(best_height + 1), input: vec![input], output: vec![TxOut {
9967 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9970 _ => panic!("Unexpected event"),
9973 // Transaction should be accepted if it's in a +1 headroom from best block.
9974 assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
9975 get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9979 fn accept_busted_but_better_fee() {
9980 // If a peer sends us a fee update that is too low, but higher than our previous channel
9981 // feerate, we should accept it. In the future we may want to consider closing the channel
9982 // later, but for now we only accept the update.
9983 let mut chanmon_cfgs = create_chanmon_cfgs(2);
9984 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9985 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9986 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9988 create_chan_between_nodes(&nodes[0], &nodes[1]);
9990 // Set nodes[1] to expect 5,000 sat/kW.
9992 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
9993 *feerate_lock = 5000;
9996 // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
9998 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9999 *feerate_lock = 1000;
10001 nodes[0].node.timer_tick_occurred();
10002 check_added_monitors!(nodes[0], 1);
10004 let events = nodes[0].node.get_and_clear_pending_msg_events();
10005 assert_eq!(events.len(), 1);
10007 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
10008 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
10009 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
10011 _ => panic!("Unexpected event"),
10014 // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
10017 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10018 *feerate_lock = 2000;
10020 nodes[0].node.timer_tick_occurred();
10021 check_added_monitors!(nodes[0], 1);
10023 let events = nodes[0].node.get_and_clear_pending_msg_events();
10024 assert_eq!(events.len(), 1);
10026 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
10027 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
10028 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
10030 _ => panic!("Unexpected event"),
10033 // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
10036 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10037 *feerate_lock = 1000;
10039 nodes[0].node.timer_tick_occurred();
10040 check_added_monitors!(nodes[0], 1);
10042 let events = nodes[0].node.get_and_clear_pending_msg_events();
10043 assert_eq!(events.len(), 1);
10045 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
10046 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
10047 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
10048 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000".to_owned() },
10049 [nodes[0].node.get_our_node_id()], 100000);
10050 check_closed_broadcast!(nodes[1], true);
10051 check_added_monitors!(nodes[1], 1);
10053 _ => panic!("Unexpected event"),
10057 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
10058 let mut chanmon_cfgs = create_chanmon_cfgs(2);
10059 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10060 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10061 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10062 let min_final_cltv_expiry_delta = 120;
10063 let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
10064 min_final_cltv_expiry_delta - 2 };
10065 let recv_value = 100_000;
10067 create_chan_between_nodes(&nodes[0], &nodes[1]);
10069 let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), final_cltv_expiry_delta as u32);
10070 let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
10071 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
10072 Some(recv_value), Some(min_final_cltv_expiry_delta));
10073 (payment_hash, payment_preimage, payment_secret)
10075 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
10076 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
10078 let route = get_route!(nodes[0], payment_parameters, recv_value).unwrap();
10079 nodes[0].node.send_payment_with_route(&route, payment_hash,
10080 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
10081 check_added_monitors!(nodes[0], 1);
10082 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10083 assert_eq!(events.len(), 1);
10084 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
10085 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
10086 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
10087 expect_pending_htlcs_forwardable!(nodes[1]);
10090 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
10091 None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
10093 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
10095 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
10097 check_added_monitors!(nodes[1], 1);
10099 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
10100 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
10101 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
10103 expect_payment_failed!(nodes[0], payment_hash, true);
10108 fn test_payment_with_custom_min_cltv_expiry_delta() {
10109 do_payment_with_custom_min_final_cltv_expiry(false, false);
10110 do_payment_with_custom_min_final_cltv_expiry(false, true);
10111 do_payment_with_custom_min_final_cltv_expiry(true, false);
10112 do_payment_with_custom_min_final_cltv_expiry(true, true);
10116 fn test_disconnects_peer_awaiting_response_ticks() {
10117 // Tests that nodes which are awaiting on a response critical for channel responsiveness
10118 // disconnect their counterparty after `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10119 let mut chanmon_cfgs = create_chanmon_cfgs(2);
10120 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10121 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10122 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10124 // Asserts a disconnect event is queued to the user.
10125 let check_disconnect_event = |node: &Node, should_disconnect: bool| {
10126 let disconnect_event = node.node.get_and_clear_pending_msg_events().iter().find_map(|event|
10127 if let MessageSendEvent::HandleError { action, .. } = event {
10128 if let msgs::ErrorAction::DisconnectPeerWithWarning { .. } = action {
10137 assert_eq!(disconnect_event.is_some(), should_disconnect);
10140 // Fires timer ticks ensuring we only attempt to disconnect peers after reaching
10141 // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10142 let check_disconnect = |node: &Node| {
10143 // No disconnect without any timer ticks.
10144 check_disconnect_event(node, false);
10146 // No disconnect with 1 timer tick less than required.
10147 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS - 1 {
10148 node.node.timer_tick_occurred();
10149 check_disconnect_event(node, false);
10152 // Disconnect after reaching the required ticks.
10153 node.node.timer_tick_occurred();
10154 check_disconnect_event(node, true);
10156 // Disconnect again on the next tick if the peer hasn't been disconnected yet.
10157 node.node.timer_tick_occurred();
10158 check_disconnect_event(node, true);
10161 create_chan_between_nodes(&nodes[0], &nodes[1]);
10163 // We'll start by performing a fee update with Alice (nodes[0]) on the channel.
10164 *nodes[0].fee_estimator.sat_per_kw.lock().unwrap() *= 2;
10165 nodes[0].node.timer_tick_occurred();
10166 check_added_monitors!(&nodes[0], 1);
10167 let alice_fee_update = get_htlc_update_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
10168 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), alice_fee_update.update_fee.as_ref().unwrap());
10169 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &alice_fee_update.commitment_signed);
10170 check_added_monitors!(&nodes[1], 1);
10172 // This will prompt Bob (nodes[1]) to respond with his `CommitmentSigned` and `RevokeAndACK`.
10173 let (bob_revoke_and_ack, bob_commitment_signed) = get_revoke_commit_msgs!(&nodes[1], nodes[0].node.get_our_node_id());
10174 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revoke_and_ack);
10175 check_added_monitors!(&nodes[0], 1);
10176 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_commitment_signed);
10177 check_added_monitors(&nodes[0], 1);
10179 // Alice then needs to send her final `RevokeAndACK` to complete the commitment dance. We
10180 // pretend Bob hasn't received the message and check whether he'll disconnect Alice after
10181 // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10182 let alice_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
10183 check_disconnect(&nodes[1]);
10185 // Now, we'll reconnect them to test awaiting a `ChannelReestablish` message.
10187 // Note that since the commitment dance didn't complete above, Alice is expected to resend her
10188 // final `RevokeAndACK` to Bob to complete it.
10189 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
10190 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10191 let bob_init = msgs::Init {
10192 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
10194 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &bob_init, true).unwrap();
10195 let alice_init = msgs::Init {
10196 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
10198 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &alice_init, true).unwrap();
10200 // Upon reconnection, Alice sends her `ChannelReestablish` to Bob. Alice, however, hasn't
10201 // received Bob's yet, so she should disconnect him after reaching
10202 // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10203 let alice_channel_reestablish = get_event_msg!(
10204 nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id()
10206 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &alice_channel_reestablish);
10207 check_disconnect(&nodes[0]);
10209 // Bob now sends his `ChannelReestablish` to Alice to resume the channel and consider it "live".
10210 let bob_channel_reestablish = nodes[1].node.get_and_clear_pending_msg_events().iter().find_map(|event|
10211 if let MessageSendEvent::SendChannelReestablish { node_id, msg } = event {
10212 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
10218 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bob_channel_reestablish);
10220 // Sanity check that Alice won't disconnect Bob since she's no longer waiting for any messages.
10221 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
10222 nodes[0].node.timer_tick_occurred();
10223 check_disconnect_event(&nodes[0], false);
10226 // However, Bob is still waiting on Alice's `RevokeAndACK`, so he should disconnect her after
10227 // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10228 check_disconnect(&nodes[1]);
10230 // Finally, have Bob process the last message.
10231 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &alice_revoke_and_ack);
10232 check_added_monitors(&nodes[1], 1);
10234 // At this point, neither node should attempt to disconnect each other, since they aren't
10235 // waiting on any messages.
10236 for node in &nodes {
10237 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
10238 node.node.timer_tick_occurred();
10239 check_disconnect_event(node, false);
10245 fn test_remove_expired_outbound_unfunded_channels() {
10246 let chanmon_cfgs = create_chanmon_cfgs(2);
10247 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10248 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10249 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10251 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
10252 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10253 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10254 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10255 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10257 let events = nodes[0].node.get_and_clear_pending_events();
10258 assert_eq!(events.len(), 1);
10260 Event::FundingGenerationReady { .. } => (),
10261 _ => panic!("Unexpected event"),
10264 // Asserts the outbound channel has been removed from a nodes[0]'s peer state map.
10265 let check_outbound_channel_existence = |should_exist: bool| {
10266 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
10267 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
10268 assert_eq!(chan_lock.channel_by_id.contains_key(&temp_channel_id), should_exist);
10271 // Channel should exist without any timer ticks.
10272 check_outbound_channel_existence(true);
10274 // Channel should exist with 1 timer tick less than required.
10275 for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS - 1 {
10276 nodes[0].node.timer_tick_occurred();
10277 check_outbound_channel_existence(true)
10280 // Remove channel after reaching the required ticks.
10281 nodes[0].node.timer_tick_occurred();
10282 check_outbound_channel_existence(false);
10284 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
10285 assert_eq!(msg_events.len(), 1);
10286 match msg_events[0] {
10287 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
10288 assert_eq!(msg.data, "Force-closing pending channel due to timeout awaiting establishment handshake");
10290 _ => panic!("Unexpected event"),
10292 check_closed_event(&nodes[0], 1, ClosureReason::HolderForceClosed, false, &[nodes[1].node.get_our_node_id()], 100000);
10296 fn test_remove_expired_inbound_unfunded_channels() {
10297 let chanmon_cfgs = create_chanmon_cfgs(2);
10298 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10299 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10300 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10302 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
10303 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10304 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10305 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10306 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10308 let events = nodes[0].node.get_and_clear_pending_events();
10309 assert_eq!(events.len(), 1);
10311 Event::FundingGenerationReady { .. } => (),
10312 _ => panic!("Unexpected event"),
10315 // Asserts the inbound channel has been removed from a nodes[1]'s peer state map.
10316 let check_inbound_channel_existence = |should_exist: bool| {
10317 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
10318 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
10319 assert_eq!(chan_lock.channel_by_id.contains_key(&temp_channel_id), should_exist);
10322 // Channel should exist without any timer ticks.
10323 check_inbound_channel_existence(true);
10325 // Channel should exist with 1 timer tick less than required.
10326 for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS - 1 {
10327 nodes[1].node.timer_tick_occurred();
10328 check_inbound_channel_existence(true)
10331 // Remove channel after reaching the required ticks.
10332 nodes[1].node.timer_tick_occurred();
10333 check_inbound_channel_existence(false);
10335 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
10336 assert_eq!(msg_events.len(), 1);
10337 match msg_events[0] {
10338 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
10339 assert_eq!(msg.data, "Force-closing pending channel due to timeout awaiting establishment handshake");
10341 _ => panic!("Unexpected event"),
10343 check_closed_event(&nodes[1], 1, ClosureReason::HolderForceClosed, false, &[nodes[0].node.get_our_node_id()], 100000);
10346 fn do_test_multi_post_event_actions(do_reload: bool) {
10347 // Tests handling multiple post-Event actions at once.
10348 // There is specific code in ChannelManager to handle channels where multiple post-Event
10349 // `ChannelMonitorUpdates` are pending at once. This test exercises that code.
10351 // Specifically, we test calling `get_and_clear_pending_events` while there are two
10352 // PaymentSents from different channels and one channel has two pending `ChannelMonitorUpdate`s
10353 // - one from an RAA and one from an inbound commitment_signed.
10354 let chanmon_cfgs = create_chanmon_cfgs(3);
10355 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10356 let (persister, chain_monitor);
10357 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10358 let nodes_0_deserialized;
10359 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10361 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
10362 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 0, 2).2;
10364 send_payment(&nodes[0], &[&nodes[1]], 1_000_000);
10365 send_payment(&nodes[0], &[&nodes[2]], 1_000_000);
10367 let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
10368 let (payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[2]], 1_000_000);
10370 nodes[1].node.claim_funds(our_payment_preimage);
10371 check_added_monitors!(nodes[1], 1);
10372 expect_payment_claimed!(nodes[1], our_payment_hash, 1_000_000);
10374 nodes[2].node.claim_funds(payment_preimage_2);
10375 check_added_monitors!(nodes[2], 1);
10376 expect_payment_claimed!(nodes[2], payment_hash_2, 1_000_000);
10378 for dest in &[1, 2] {
10379 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[*dest], nodes[0].node.get_our_node_id());
10380 nodes[0].node.handle_update_fulfill_htlc(&nodes[*dest].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
10381 commitment_signed_dance!(nodes[0], nodes[*dest], htlc_fulfill_updates.commitment_signed, false);
10382 check_added_monitors(&nodes[0], 0);
10385 let (route, payment_hash_3, _, payment_secret_3) =
10386 get_route_and_payment_hash!(nodes[1], nodes[0], 100_000);
10387 let payment_id = PaymentId(payment_hash_3.0);
10388 nodes[1].node.send_payment_with_route(&route, payment_hash_3,
10389 RecipientOnionFields::secret_only(payment_secret_3), payment_id).unwrap();
10390 check_added_monitors(&nodes[1], 1);
10392 let send_event = SendEvent::from_node(&nodes[1]);
10393 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event.msgs[0]);
10394 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_event.commitment_msg);
10395 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
10398 let nodes_0_serialized = nodes[0].node.encode();
10399 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
10400 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_2).encode();
10401 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);
10403 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10404 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10406 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
10407 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[2]));
10410 let events = nodes[0].node.get_and_clear_pending_events();
10411 assert_eq!(events.len(), 4);
10412 if let Event::PaymentSent { payment_preimage, .. } = events[0] {
10413 assert!(payment_preimage == our_payment_preimage || payment_preimage == payment_preimage_2);
10414 } else { panic!(); }
10415 if let Event::PaymentSent { payment_preimage, .. } = events[1] {
10416 assert!(payment_preimage == our_payment_preimage || payment_preimage == payment_preimage_2);
10417 } else { panic!(); }
10418 if let Event::PaymentPathSuccessful { .. } = events[2] {} else { panic!(); }
10419 if let Event::PaymentPathSuccessful { .. } = events[3] {} else { panic!(); }
10421 // After the events are processed, the ChannelMonitorUpdates will be released and, upon their
10422 // completion, we'll respond to nodes[1] with an RAA + CS.
10423 get_revoke_commit_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
10424 check_added_monitors(&nodes[0], 3);
10428 fn test_multi_post_event_actions() {
10429 do_test_multi_post_event_actions(true);
10430 do_test_multi_post_event_actions(false);
10434 fn test_batch_channel_open() {
10435 let chanmon_cfgs = create_chanmon_cfgs(3);
10436 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10437 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10438 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10440 // Initiate channel opening and create the batch channel funding transaction.
10441 let (tx, funding_created_msgs) = create_batch_channel_funding(&nodes[0], &[
10442 (&nodes[1], 100_000, 0, 42, None),
10443 (&nodes[2], 200_000, 0, 43, None),
10446 // Go through the funding_created and funding_signed flow with node 1.
10447 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[0]);
10448 check_added_monitors(&nodes[1], 1);
10449 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
10451 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10452 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
10453 check_added_monitors(&nodes[0], 1);
10455 // The transaction should not have been broadcast before all channels are ready.
10456 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
10458 // Go through the funding_created and funding_signed flow with node 2.
10459 nodes[2].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[1]);
10460 check_added_monitors(&nodes[2], 1);
10461 expect_channel_pending_event(&nodes[2], &nodes[0].node.get_our_node_id());
10463 let funding_signed_msg = get_event_msg!(nodes[2], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10464 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
10465 nodes[0].node.handle_funding_signed(&nodes[2].node.get_our_node_id(), &funding_signed_msg);
10466 check_added_monitors(&nodes[0], 1);
10468 // The transaction should not have been broadcast before persisting all monitors has been
10470 assert_eq!(nodes[0].tx_broadcaster.txn_broadcast().len(), 0);
10471 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
10473 // Complete the persistence of the monitor.
10474 nodes[0].chain_monitor.complete_sole_pending_chan_update(
10475 &OutPoint { txid: tx.txid(), index: 1 }.to_channel_id()
10477 let events = nodes[0].node.get_and_clear_pending_events();
10479 // The transaction should only have been broadcast now.
10480 let broadcasted_txs = nodes[0].tx_broadcaster.txn_broadcast();
10481 assert_eq!(broadcasted_txs.len(), 1);
10482 assert_eq!(broadcasted_txs[0], tx);
10484 assert_eq!(events.len(), 2);
10485 assert!(events.iter().any(|e| matches!(
10487 crate::events::Event::ChannelPending {
10488 ref counterparty_node_id,
10490 } if counterparty_node_id == &nodes[1].node.get_our_node_id(),
10492 assert!(events.iter().any(|e| matches!(
10494 crate::events::Event::ChannelPending {
10495 ref counterparty_node_id,
10497 } if counterparty_node_id == &nodes[2].node.get_our_node_id(),
10502 fn test_disconnect_in_funding_batch() {
10503 let chanmon_cfgs = create_chanmon_cfgs(3);
10504 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10505 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10506 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10508 // Initiate channel opening and create the batch channel funding transaction.
10509 let (tx, funding_created_msgs) = create_batch_channel_funding(&nodes[0], &[
10510 (&nodes[1], 100_000, 0, 42, None),
10511 (&nodes[2], 200_000, 0, 43, None),
10514 // Go through the funding_created and funding_signed flow with node 1.
10515 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[0]);
10516 check_added_monitors(&nodes[1], 1);
10517 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
10519 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10520 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
10521 check_added_monitors(&nodes[0], 1);
10523 // The transaction should not have been broadcast before all channels are ready.
10524 assert_eq!(nodes[0].tx_broadcaster.txn_broadcast().len(), 0);
10526 // The remaining peer in the batch disconnects.
10527 nodes[0].node.peer_disconnected(&nodes[2].node.get_our_node_id());
10529 // The channels in the batch will close immediately.
10530 let channel_id_1 = OutPoint { txid: tx.txid(), index: 0 }.to_channel_id();
10531 let channel_id_2 = OutPoint { txid: tx.txid(), index: 1 }.to_channel_id();
10532 check_closed_events(&nodes[0], &[
10533 ExpectedCloseEvent {
10534 channel_id: Some(channel_id_1),
10535 discard_funding: true,
10536 ..Default::default()
10538 ExpectedCloseEvent {
10539 channel_id: Some(channel_id_2),
10540 discard_funding: true,
10541 ..Default::default()
10545 // The monitor should become closed.
10546 check_added_monitors(&nodes[0], 1);
10548 let mut monitor_updates = nodes[0].chain_monitor.monitor_updates.lock().unwrap();
10549 let monitor_updates_1 = monitor_updates.get(&channel_id_1).unwrap();
10550 assert_eq!(monitor_updates_1.len(), 1);
10551 assert_eq!(monitor_updates_1[0].update_id, CLOSED_CHANNEL_UPDATE_ID);
10554 // The funding transaction should not have been broadcast, and therefore, we don't need
10555 // to broadcast a force-close transaction for the closed monitor.
10556 assert_eq!(nodes[0].tx_broadcaster.txn_broadcast().len(), 0);
10558 // Ensure the channels don't exist anymore.
10559 assert!(nodes[0].node.list_channels().is_empty());
10563 fn test_batch_funding_close_after_funding_signed() {
10564 let chanmon_cfgs = create_chanmon_cfgs(3);
10565 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10566 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10567 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10569 // Initiate channel opening and create the batch channel funding transaction.
10570 let (tx, funding_created_msgs) = create_batch_channel_funding(&nodes[0], &[
10571 (&nodes[1], 100_000, 0, 42, None),
10572 (&nodes[2], 200_000, 0, 43, None),
10575 // Go through the funding_created and funding_signed flow with node 1.
10576 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[0]);
10577 check_added_monitors(&nodes[1], 1);
10578 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
10580 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10581 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
10582 check_added_monitors(&nodes[0], 1);
10584 // Go through the funding_created and funding_signed flow with node 2.
10585 nodes[2].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[1]);
10586 check_added_monitors(&nodes[2], 1);
10587 expect_channel_pending_event(&nodes[2], &nodes[0].node.get_our_node_id());
10589 let funding_signed_msg = get_event_msg!(nodes[2], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10590 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
10591 nodes[0].node.handle_funding_signed(&nodes[2].node.get_our_node_id(), &funding_signed_msg);
10592 check_added_monitors(&nodes[0], 1);
10594 // The transaction should not have been broadcast before all channels are ready.
10595 assert_eq!(nodes[0].tx_broadcaster.txn_broadcast().len(), 0);
10597 // Force-close the channel for which we've completed the initial monitor.
10598 let channel_id_1 = OutPoint { txid: tx.txid(), index: 0 }.to_channel_id();
10599 let channel_id_2 = OutPoint { txid: tx.txid(), index: 1 }.to_channel_id();
10600 nodes[0].node.force_close_broadcasting_latest_txn(&channel_id_1, &nodes[1].node.get_our_node_id()).unwrap();
10601 check_added_monitors(&nodes[0], 2);
10603 let mut monitor_updates = nodes[0].chain_monitor.monitor_updates.lock().unwrap();
10604 let monitor_updates_1 = monitor_updates.get(&channel_id_1).unwrap();
10605 assert_eq!(monitor_updates_1.len(), 1);
10606 assert_eq!(monitor_updates_1[0].update_id, CLOSED_CHANNEL_UPDATE_ID);
10607 let monitor_updates_2 = monitor_updates.get(&channel_id_2).unwrap();
10608 assert_eq!(monitor_updates_2.len(), 1);
10609 assert_eq!(monitor_updates_2[0].update_id, CLOSED_CHANNEL_UPDATE_ID);
10611 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
10612 match msg_events[0] {
10613 MessageSendEvent::HandleError { .. } => (),
10614 _ => panic!("Unexpected message."),
10617 // We broadcast the commitment transaction as part of the force-close.
10619 let broadcasted_txs = nodes[0].tx_broadcaster.txn_broadcast();
10620 assert_eq!(broadcasted_txs.len(), 1);
10621 assert!(broadcasted_txs[0].txid() != tx.txid());
10622 assert_eq!(broadcasted_txs[0].input.len(), 1);
10623 assert_eq!(broadcasted_txs[0].input[0].previous_output.txid, tx.txid());
10626 // All channels in the batch should close immediately.
10627 check_closed_events(&nodes[0], &[
10628 ExpectedCloseEvent {
10629 channel_id: Some(channel_id_1),
10630 discard_funding: true,
10631 ..Default::default()
10633 ExpectedCloseEvent {
10634 channel_id: Some(channel_id_2),
10635 discard_funding: true,
10636 ..Default::default()
10640 // Ensure the channels don't exist anymore.
10641 assert!(nodes[0].node.list_channels().is_empty());
10644 fn do_test_funding_and_commitment_tx_confirm_same_block(confirm_remote_commitment: bool) {
10645 // Tests that a node will forget the channel (when it only requires 1 confirmation) if the
10646 // funding and commitment transaction confirm in the same block.
10647 let chanmon_cfgs = create_chanmon_cfgs(2);
10648 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10649 let mut min_depth_1_block_cfg = test_default_channel_config();
10650 min_depth_1_block_cfg.channel_handshake_config.minimum_depth = 1;
10651 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(min_depth_1_block_cfg), Some(min_depth_1_block_cfg)]);
10652 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10654 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
10655 let chan_id = chain::transaction::OutPoint { txid: funding_tx.txid(), index: 0 }.to_channel_id();
10657 assert_eq!(nodes[0].node.list_channels().len(), 1);
10658 assert_eq!(nodes[1].node.list_channels().len(), 1);
10660 let (closing_node, other_node) = if confirm_remote_commitment {
10661 (&nodes[1], &nodes[0])
10663 (&nodes[0], &nodes[1])
10666 closing_node.node.force_close_broadcasting_latest_txn(&chan_id, &other_node.node.get_our_node_id()).unwrap();
10667 let mut msg_events = closing_node.node.get_and_clear_pending_msg_events();
10668 assert_eq!(msg_events.len(), 1);
10669 match msg_events.pop().unwrap() {
10670 MessageSendEvent::HandleError { action: msgs::ErrorAction::DisconnectPeer { .. }, .. } => {},
10671 _ => panic!("Unexpected event"),
10673 check_added_monitors(closing_node, 1);
10674 check_closed_event(closing_node, 1, ClosureReason::HolderForceClosed, false, &[other_node.node.get_our_node_id()], 1_000_000);
10676 let commitment_tx = {
10677 let mut txn = closing_node.tx_broadcaster.txn_broadcast();
10678 assert_eq!(txn.len(), 1);
10679 let commitment_tx = txn.pop().unwrap();
10680 check_spends!(commitment_tx, funding_tx);
10684 mine_transactions(&nodes[0], &[&funding_tx, &commitment_tx]);
10685 mine_transactions(&nodes[1], &[&funding_tx, &commitment_tx]);
10687 check_closed_broadcast(other_node, 1, true);
10688 check_added_monitors(other_node, 1);
10689 check_closed_event(other_node, 1, ClosureReason::CommitmentTxConfirmed, false, &[closing_node.node.get_our_node_id()], 1_000_000);
10691 assert!(nodes[0].node.list_channels().is_empty());
10692 assert!(nodes[1].node.list_channels().is_empty());
10696 fn test_funding_and_commitment_tx_confirm_same_block() {
10697 do_test_funding_and_commitment_tx_confirm_same_block(false);
10698 do_test_funding_and_commitment_tx_confirm_same_block(true);