1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
15 use crate::chain::{ChannelMonitorUpdateStatus, Confirm, Listen, Watch};
16 use crate::chain::chaininterface::LowerBoundedFeeEstimator;
17 use crate::chain::channelmonitor;
18 use crate::chain::channelmonitor::{CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
19 use crate::chain::transaction::OutPoint;
20 use crate::sign::{ChannelSigner, EcdsaChannelSigner, EntropySource, 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::script::{Builder, Script};
42 use bitcoin::blockdata::opcodes;
43 use bitcoin::blockdata::constants::genesis_block;
44 use bitcoin::network::constants::Network;
45 use bitcoin::{PackedLockTime, Sequence, Transaction, TxIn, TxOut, Witness};
46 use bitcoin::OutPoint as BitcoinOutPoint;
48 use bitcoin::secp256k1::Secp256k1;
49 use bitcoin::secp256k1::{PublicKey,SecretKey};
54 use crate::prelude::*;
55 use alloc::collections::BTreeSet;
56 use core::default::Default;
57 use core::iter::repeat;
58 use bitcoin::hashes::Hash;
59 use crate::sync::{Arc, Mutex, RwLock};
61 use crate::ln::functional_test_utils::*;
62 use crate::ln::chan_utils::CommitmentTransaction;
64 use super::channel::UNFUNDED_CHANNEL_AGE_LIMIT_TICKS;
67 fn test_insane_channel_opens() {
68 // Stand up a network of 2 nodes
69 use crate::ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
70 let mut cfg = UserConfig::default();
71 cfg.channel_handshake_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
72 let chanmon_cfgs = create_chanmon_cfgs(2);
73 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
74 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
75 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
77 // Instantiate channel parameters where we push the maximum msats given our
79 let channel_value_sat = 31337; // same as funding satoshis
80 let channel_reserve_satoshis = get_holder_selected_channel_reserve_satoshis(channel_value_sat, &cfg);
81 let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
83 // Have node0 initiate a channel to node1 with aforementioned parameters
84 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
86 // Extract the channel open message from node0 to node1
87 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
89 // Test helper that asserts we get the correct error string given a mutator
90 // that supposedly makes the channel open message insane
91 let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
92 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &message_mutator(open_channel_message.clone()));
93 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
94 assert_eq!(msg_events.len(), 1);
95 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
96 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
98 &ErrorAction::SendErrorMessage { .. } => {
99 nodes[1].logger.assert_log_regex("lightning::ln::channelmanager", expected_regex, 1);
101 _ => panic!("unexpected event!"),
103 } else { assert!(false); }
106 use crate::ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
108 // Test all mutations that would make the channel open message insane
109 insane_open_helper(format!("Per our config, funding must be at most {}. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1, TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2; msg });
110 insane_open_helper(format!("Funding must be smaller than the total bitcoin supply. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS; msg });
112 insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
114 insane_open_helper(r"push_msat \d+ was larger than channel amount minus reserve \(\d+\)", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
116 insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
118 insane_open_helper(r"Minimum htlc value \(\d+\) was larger than full channel value \(\d+\)", |mut msg| { msg.htlc_minimum_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000; msg });
120 insane_open_helper("They wanted our payments to be delayed by a needlessly long period", |mut msg| { msg.to_self_delay = MAX_LOCAL_BREAKDOWN_TIMEOUT + 1; msg });
122 insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
124 insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
128 fn test_funding_exceeds_no_wumbo_limit() {
129 // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
131 use crate::ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
132 let chanmon_cfgs = create_chanmon_cfgs(2);
133 let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
134 *node_cfgs[1].override_init_features.borrow_mut() = Some(channelmanager::provided_init_features(&test_default_channel_config()).clear_wumbo());
135 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
136 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
138 match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None) {
139 Err(APIError::APIMisuseError { err }) => {
140 assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
146 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
147 // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
148 // but only for them. Because some LSPs do it with some level of trust of the clients (for a
149 // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
150 // in normal testing, we test it explicitly here.
151 let chanmon_cfgs = create_chanmon_cfgs(2);
152 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
153 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
154 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
155 let default_config = UserConfig::default();
157 // Have node0 initiate a channel to node1 with aforementioned parameters
158 let mut push_amt = 100_000_000;
159 let feerate_per_kw = 253;
160 let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
161 push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(&channel_type_features) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
162 push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
164 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, if send_from_initiator { 0 } else { push_amt }, 42, None).unwrap();
165 let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
166 if !send_from_initiator {
167 open_channel_message.channel_reserve_satoshis = 0;
168 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
170 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
172 // Extract the channel accept message from node1 to node0
173 let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
174 if send_from_initiator {
175 accept_channel_message.channel_reserve_satoshis = 0;
176 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
178 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
180 let sender_node = if send_from_initiator { &nodes[1] } else { &nodes[0] };
181 let counterparty_node = if send_from_initiator { &nodes[0] } else { &nodes[1] };
182 let mut sender_node_per_peer_lock;
183 let mut sender_node_peer_state_lock;
185 let channel_phase = get_channel_ref!(sender_node, counterparty_node, sender_node_per_peer_lock, sender_node_peer_state_lock, temp_channel_id);
186 match channel_phase {
187 ChannelPhase::UnfundedInboundV1(_) | ChannelPhase::UnfundedOutboundV1(_) => {
188 let chan_context = channel_phase.context_mut();
189 chan_context.holder_selected_channel_reserve_satoshis = 0;
190 chan_context.holder_max_htlc_value_in_flight_msat = 100_000_000;
192 ChannelPhase::Funded(_) => assert!(false),
196 let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
197 let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
198 create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
200 // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
201 // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
202 if send_from_initiator {
203 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
204 // Note that for outbound channels we have to consider the commitment tx fee and the
205 // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
206 // well as an additional HTLC.
207 - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, &channel_type_features));
209 send_payment(&nodes[1], &[&nodes[0]], push_amt);
214 fn test_counterparty_no_reserve() {
215 do_test_counterparty_no_reserve(true);
216 do_test_counterparty_no_reserve(false);
220 fn test_async_inbound_update_fee() {
221 let chanmon_cfgs = create_chanmon_cfgs(2);
222 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
223 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
224 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
225 create_announced_chan_between_nodes(&nodes, 0, 1);
228 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
232 // send (1) commitment_signed -.
233 // <- update_add_htlc/commitment_signed
234 // send (2) RAA (awaiting remote revoke) -.
235 // (1) commitment_signed is delivered ->
236 // .- send (3) RAA (awaiting remote revoke)
237 // (2) RAA is delivered ->
238 // .- send (4) commitment_signed
239 // <- (3) RAA is delivered
240 // send (5) commitment_signed -.
241 // <- (4) commitment_signed is delivered
243 // (5) commitment_signed is delivered ->
245 // (6) RAA is delivered ->
247 // First nodes[0] generates an update_fee
249 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
252 nodes[0].node.timer_tick_occurred();
253 check_added_monitors!(nodes[0], 1);
255 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
256 assert_eq!(events_0.len(), 1);
257 let (update_msg, commitment_signed) = match events_0[0] { // (1)
258 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
259 (update_fee.as_ref(), commitment_signed)
261 _ => panic!("Unexpected event"),
264 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
266 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
267 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
268 nodes[1].node.send_payment_with_route(&route, our_payment_hash,
269 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
270 check_added_monitors!(nodes[1], 1);
272 let payment_event = {
273 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
274 assert_eq!(events_1.len(), 1);
275 SendEvent::from_event(events_1.remove(0))
277 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
278 assert_eq!(payment_event.msgs.len(), 1);
280 // ...now when the messages get delivered everyone should be happy
281 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
282 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
283 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
284 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
285 check_added_monitors!(nodes[0], 1);
287 // deliver(1), generate (3):
288 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
289 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
290 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
291 check_added_monitors!(nodes[1], 1);
293 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
294 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
295 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
296 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
297 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
298 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
299 assert!(bs_update.update_fee.is_none()); // (4)
300 check_added_monitors!(nodes[1], 1);
302 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
303 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
304 assert!(as_update.update_add_htlcs.is_empty()); // (5)
305 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
306 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
307 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
308 assert!(as_update.update_fee.is_none()); // (5)
309 check_added_monitors!(nodes[0], 1);
311 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
312 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
313 // only (6) so get_event_msg's assert(len == 1) passes
314 check_added_monitors!(nodes[0], 1);
316 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
317 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
318 check_added_monitors!(nodes[1], 1);
320 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
321 check_added_monitors!(nodes[0], 1);
323 let events_2 = nodes[0].node.get_and_clear_pending_events();
324 assert_eq!(events_2.len(), 1);
326 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
327 _ => panic!("Unexpected event"),
330 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
331 check_added_monitors!(nodes[1], 1);
335 fn test_update_fee_unordered_raa() {
336 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
337 // crash in an earlier version of the update_fee patch)
338 let chanmon_cfgs = create_chanmon_cfgs(2);
339 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
340 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
341 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
342 create_announced_chan_between_nodes(&nodes, 0, 1);
345 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
347 // First nodes[0] generates an update_fee
349 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
352 nodes[0].node.timer_tick_occurred();
353 check_added_monitors!(nodes[0], 1);
355 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
356 assert_eq!(events_0.len(), 1);
357 let update_msg = match events_0[0] { // (1)
358 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
361 _ => panic!("Unexpected event"),
364 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
366 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
367 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
368 nodes[1].node.send_payment_with_route(&route, our_payment_hash,
369 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
370 check_added_monitors!(nodes[1], 1);
372 let payment_event = {
373 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
374 assert_eq!(events_1.len(), 1);
375 SendEvent::from_event(events_1.remove(0))
377 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
378 assert_eq!(payment_event.msgs.len(), 1);
380 // ...now when the messages get delivered everyone should be happy
381 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
382 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
383 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
384 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
385 check_added_monitors!(nodes[0], 1);
387 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
388 check_added_monitors!(nodes[1], 1);
390 // We can't continue, sadly, because our (1) now has a bogus signature
394 fn test_multi_flight_update_fee() {
395 let chanmon_cfgs = create_chanmon_cfgs(2);
396 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
397 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
398 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
399 create_announced_chan_between_nodes(&nodes, 0, 1);
402 // update_fee/commitment_signed ->
403 // .- send (1) RAA and (2) commitment_signed
404 // update_fee (never committed) ->
406 // We have to manually generate the above update_fee, it is allowed by the protocol but we
407 // don't track which updates correspond to which revoke_and_ack responses so we're in
408 // AwaitingRAA mode and will not generate the update_fee yet.
409 // <- (1) RAA delivered
410 // (3) is generated and send (4) CS -.
411 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
412 // know the per_commitment_point to use for it.
413 // <- (2) commitment_signed delivered
415 // B should send no response here
416 // (4) commitment_signed delivered ->
417 // <- RAA/commitment_signed delivered
420 // First nodes[0] generates an update_fee
423 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
424 initial_feerate = *feerate_lock;
425 *feerate_lock = initial_feerate + 20;
427 nodes[0].node.timer_tick_occurred();
428 check_added_monitors!(nodes[0], 1);
430 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
431 assert_eq!(events_0.len(), 1);
432 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
433 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
434 (update_fee.as_ref().unwrap(), commitment_signed)
436 _ => panic!("Unexpected event"),
439 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
440 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
441 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
442 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
443 check_added_monitors!(nodes[1], 1);
445 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
448 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
449 *feerate_lock = initial_feerate + 40;
451 nodes[0].node.timer_tick_occurred();
452 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
453 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
455 // Create the (3) update_fee message that nodes[0] will generate before it does...
456 let mut update_msg_2 = msgs::UpdateFee {
457 channel_id: update_msg_1.channel_id.clone(),
458 feerate_per_kw: (initial_feerate + 30) as u32,
461 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
463 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
465 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
467 // Deliver (1), generating (3) and (4)
468 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
469 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
470 check_added_monitors!(nodes[0], 1);
471 assert!(as_second_update.update_add_htlcs.is_empty());
472 assert!(as_second_update.update_fulfill_htlcs.is_empty());
473 assert!(as_second_update.update_fail_htlcs.is_empty());
474 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
475 // Check that the update_fee newly generated matches what we delivered:
476 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
477 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
479 // Deliver (2) commitment_signed
480 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
481 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
482 check_added_monitors!(nodes[0], 1);
483 // No commitment_signed so get_event_msg's assert(len == 1) passes
485 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
486 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
487 check_added_monitors!(nodes[1], 1);
490 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
491 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
492 check_added_monitors!(nodes[1], 1);
494 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
495 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
496 check_added_monitors!(nodes[0], 1);
498 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
499 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
500 // No commitment_signed so get_event_msg's assert(len == 1) passes
501 check_added_monitors!(nodes[0], 1);
503 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
504 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
505 check_added_monitors!(nodes[1], 1);
508 fn do_test_sanity_on_in_flight_opens(steps: u8) {
509 // Previously, we had issues deserializing channels when we hadn't connected the first block
510 // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
511 // serialization round-trips and simply do steps towards opening a channel and then drop the
514 let chanmon_cfgs = create_chanmon_cfgs(2);
515 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
516 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
517 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
519 if steps & 0b1000_0000 != 0{
520 let block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
521 connect_block(&nodes[0], &block);
522 connect_block(&nodes[1], &block);
525 if steps & 0x0f == 0 { return; }
526 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
527 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
529 if steps & 0x0f == 1 { return; }
530 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
531 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
533 if steps & 0x0f == 2 { return; }
534 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
536 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
538 if steps & 0x0f == 3 { return; }
539 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
540 check_added_monitors!(nodes[0], 0);
541 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
543 if steps & 0x0f == 4 { return; }
544 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
546 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
547 assert_eq!(added_monitors.len(), 1);
548 assert_eq!(added_monitors[0].0, funding_output);
549 added_monitors.clear();
551 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
553 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
555 if steps & 0x0f == 5 { return; }
556 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
558 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
559 assert_eq!(added_monitors.len(), 1);
560 assert_eq!(added_monitors[0].0, funding_output);
561 added_monitors.clear();
564 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
565 let events_4 = nodes[0].node.get_and_clear_pending_events();
566 assert_eq!(events_4.len(), 0);
568 if steps & 0x0f == 6 { return; }
569 create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
571 if steps & 0x0f == 7 { return; }
572 confirm_transaction_at(&nodes[0], &tx, 2);
573 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
574 create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
575 expect_channel_ready_event(&nodes[0], &nodes[1].node.get_our_node_id());
579 fn test_sanity_on_in_flight_opens() {
580 do_test_sanity_on_in_flight_opens(0);
581 do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
582 do_test_sanity_on_in_flight_opens(1);
583 do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
584 do_test_sanity_on_in_flight_opens(2);
585 do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
586 do_test_sanity_on_in_flight_opens(3);
587 do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
588 do_test_sanity_on_in_flight_opens(4);
589 do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
590 do_test_sanity_on_in_flight_opens(5);
591 do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
592 do_test_sanity_on_in_flight_opens(6);
593 do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
594 do_test_sanity_on_in_flight_opens(7);
595 do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
596 do_test_sanity_on_in_flight_opens(8);
597 do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
601 fn test_update_fee_vanilla() {
602 let chanmon_cfgs = create_chanmon_cfgs(2);
603 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
604 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
605 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
606 create_announced_chan_between_nodes(&nodes, 0, 1);
609 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
612 nodes[0].node.timer_tick_occurred();
613 check_added_monitors!(nodes[0], 1);
615 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
616 assert_eq!(events_0.len(), 1);
617 let (update_msg, commitment_signed) = match events_0[0] {
618 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 } } => {
619 (update_fee.as_ref(), commitment_signed)
621 _ => panic!("Unexpected event"),
623 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
625 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
626 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
627 check_added_monitors!(nodes[1], 1);
629 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
630 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
631 check_added_monitors!(nodes[0], 1);
633 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
634 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
635 // No commitment_signed so get_event_msg's assert(len == 1) passes
636 check_added_monitors!(nodes[0], 1);
638 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
639 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
640 check_added_monitors!(nodes[1], 1);
644 fn test_update_fee_that_funder_cannot_afford() {
645 let chanmon_cfgs = create_chanmon_cfgs(2);
646 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
647 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
648 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
649 let channel_value = 5000;
651 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000);
652 let channel_id = chan.2;
653 let secp_ctx = Secp256k1::new();
654 let default_config = UserConfig::default();
655 let bs_channel_reserve_sats = get_holder_selected_channel_reserve_satoshis(channel_value, &default_config);
657 let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
659 // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
660 // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
661 // calculate two different feerates here - the expected local limit as well as the expected
663 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;
664 let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(&channel_type_features)) as u32;
666 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
667 *feerate_lock = feerate;
669 nodes[0].node.timer_tick_occurred();
670 check_added_monitors!(nodes[0], 1);
671 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
673 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
675 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
677 // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
679 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
681 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
682 assert_eq!(commitment_tx.output.len(), 2);
683 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, &channel_type_features) / 1000;
684 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
685 actual_fee = channel_value - actual_fee;
686 assert_eq!(total_fee, actual_fee);
690 // Increment the feerate by a small constant, accounting for rounding errors
691 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
694 nodes[0].node.timer_tick_occurred();
695 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
696 check_added_monitors!(nodes[0], 0);
698 const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
700 // Get the TestChannelSigner for each channel, which will be used to (1) get the keys
701 // needed to sign the new commitment tx and (2) sign the new commitment tx.
702 let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
703 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
704 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
705 let local_chan = chan_lock.channel_by_id.get(&chan.2).map(
706 |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
707 ).flatten().unwrap();
708 let chan_signer = local_chan.get_signer();
709 let pubkeys = chan_signer.as_ref().pubkeys();
710 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
711 pubkeys.funding_pubkey)
713 let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
714 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
715 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
716 let remote_chan = chan_lock.channel_by_id.get(&chan.2).map(
717 |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
718 ).flatten().unwrap();
719 let chan_signer = remote_chan.get_signer();
720 let pubkeys = chan_signer.as_ref().pubkeys();
721 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
722 chan_signer.as_ref().get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
723 pubkeys.funding_pubkey)
726 // Assemble the set of keys we can use for signatures for our commitment_signed message.
727 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
728 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
731 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
732 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
733 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).map(
734 |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
735 ).flatten().unwrap();
736 let local_chan_signer = local_chan.get_signer();
737 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
738 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
739 INITIAL_COMMITMENT_NUMBER - 1,
741 channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, &channel_type_features) / 1000,
742 local_funding, remote_funding,
743 commit_tx_keys.clone(),
744 non_buffer_feerate + 4,
746 &local_chan.context.channel_transaction_parameters.as_counterparty_broadcastable()
748 local_chan_signer.as_ecdsa().unwrap().sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
751 let commit_signed_msg = msgs::CommitmentSigned {
754 htlc_signatures: res.1,
756 partial_signature_with_nonce: None,
759 let update_fee = msgs::UpdateFee {
761 feerate_per_kw: non_buffer_feerate + 4,
764 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
766 //While producing the commitment_signed response after handling a received update_fee request the
767 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
768 //Should produce and error.
769 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
770 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
771 check_added_monitors!(nodes[1], 1);
772 check_closed_broadcast!(nodes[1], true);
773 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") },
774 [nodes[0].node.get_our_node_id()], channel_value);
778 fn test_update_fee_with_fundee_update_add_htlc() {
779 let chanmon_cfgs = create_chanmon_cfgs(2);
780 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
781 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
782 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
783 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
786 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
789 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
792 nodes[0].node.timer_tick_occurred();
793 check_added_monitors!(nodes[0], 1);
795 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
796 assert_eq!(events_0.len(), 1);
797 let (update_msg, commitment_signed) = match events_0[0] {
798 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 } } => {
799 (update_fee.as_ref(), commitment_signed)
801 _ => panic!("Unexpected event"),
803 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
804 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
805 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
806 check_added_monitors!(nodes[1], 1);
808 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
810 // nothing happens since node[1] is in AwaitingRemoteRevoke
811 nodes[1].node.send_payment_with_route(&route, our_payment_hash,
812 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
814 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
815 assert_eq!(added_monitors.len(), 0);
816 added_monitors.clear();
818 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
819 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
820 // node[1] has nothing to do
822 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
823 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
824 check_added_monitors!(nodes[0], 1);
826 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
827 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
828 // No commitment_signed so get_event_msg's assert(len == 1) passes
829 check_added_monitors!(nodes[0], 1);
830 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
831 check_added_monitors!(nodes[1], 1);
832 // AwaitingRemoteRevoke ends here
834 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
835 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
836 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
837 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
838 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
839 assert_eq!(commitment_update.update_fee.is_none(), true);
841 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
842 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
843 check_added_monitors!(nodes[0], 1);
844 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
846 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
847 check_added_monitors!(nodes[1], 1);
848 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
850 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
851 check_added_monitors!(nodes[1], 1);
852 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
853 // No commitment_signed so get_event_msg's assert(len == 1) passes
855 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
856 check_added_monitors!(nodes[0], 1);
857 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
859 expect_pending_htlcs_forwardable!(nodes[0]);
861 let events = nodes[0].node.get_and_clear_pending_events();
862 assert_eq!(events.len(), 1);
864 Event::PaymentClaimable { .. } => { },
865 _ => panic!("Unexpected event"),
868 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
870 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
871 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
872 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
873 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
874 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
878 fn test_update_fee() {
879 let chanmon_cfgs = create_chanmon_cfgs(2);
880 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
881 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
882 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
883 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
884 let channel_id = chan.2;
887 // (1) update_fee/commitment_signed ->
888 // <- (2) revoke_and_ack
889 // .- send (3) commitment_signed
890 // (4) update_fee/commitment_signed ->
891 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
892 // <- (3) commitment_signed delivered
893 // send (6) revoke_and_ack -.
894 // <- (5) deliver revoke_and_ack
895 // (6) deliver revoke_and_ack ->
896 // .- send (7) commitment_signed in response to (4)
897 // <- (7) deliver commitment_signed
900 // Create and deliver (1)...
903 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
904 feerate = *feerate_lock;
905 *feerate_lock = feerate + 20;
907 nodes[0].node.timer_tick_occurred();
908 check_added_monitors!(nodes[0], 1);
910 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
911 assert_eq!(events_0.len(), 1);
912 let (update_msg, commitment_signed) = match events_0[0] {
913 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 } } => {
914 (update_fee.as_ref(), commitment_signed)
916 _ => panic!("Unexpected event"),
918 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
920 // Generate (2) and (3):
921 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
922 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
923 check_added_monitors!(nodes[1], 1);
926 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
927 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
928 check_added_monitors!(nodes[0], 1);
930 // Create and deliver (4)...
932 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
933 *feerate_lock = feerate + 30;
935 nodes[0].node.timer_tick_occurred();
936 check_added_monitors!(nodes[0], 1);
937 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
938 assert_eq!(events_0.len(), 1);
939 let (update_msg, commitment_signed) = match events_0[0] {
940 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 } } => {
941 (update_fee.as_ref(), commitment_signed)
943 _ => panic!("Unexpected event"),
946 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
947 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
948 check_added_monitors!(nodes[1], 1);
950 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
951 // No commitment_signed so get_event_msg's assert(len == 1) passes
953 // Handle (3), creating (6):
954 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
955 check_added_monitors!(nodes[0], 1);
956 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
957 // No commitment_signed so get_event_msg's assert(len == 1) passes
960 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
961 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
962 check_added_monitors!(nodes[0], 1);
964 // Deliver (6), creating (7):
965 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
966 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
967 assert!(commitment_update.update_add_htlcs.is_empty());
968 assert!(commitment_update.update_fulfill_htlcs.is_empty());
969 assert!(commitment_update.update_fail_htlcs.is_empty());
970 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
971 assert!(commitment_update.update_fee.is_none());
972 check_added_monitors!(nodes[1], 1);
975 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
976 check_added_monitors!(nodes[0], 1);
977 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
978 // No commitment_signed so get_event_msg's assert(len == 1) passes
980 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
981 check_added_monitors!(nodes[1], 1);
982 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
984 assert_eq!(get_feerate!(nodes[0], nodes[1], channel_id), feerate + 30);
985 assert_eq!(get_feerate!(nodes[1], nodes[0], channel_id), feerate + 30);
986 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
987 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
988 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
992 fn fake_network_test() {
993 // Simple test which builds a network of ChannelManagers, connects them to each other, and
994 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
995 let chanmon_cfgs = create_chanmon_cfgs(4);
996 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
997 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
998 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1000 // Create some initial channels
1001 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1002 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1003 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
1005 // Rebalance the network a bit by relaying one payment through all the channels...
1006 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
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);
1011 // Send some more payments
1012 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
1013 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
1014 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
1016 // Test failure packets
1017 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1018 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1020 // Add a new channel that skips 3
1021 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
1023 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
1024 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
1025 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
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);
1031 // Do some rebalance loop payments, simultaneously
1032 let mut hops = Vec::with_capacity(3);
1033 hops.push(RouteHop {
1034 pubkey: nodes[2].node.get_our_node_id(),
1035 node_features: NodeFeatures::empty(),
1036 short_channel_id: chan_2.0.contents.short_channel_id,
1037 channel_features: ChannelFeatures::empty(),
1039 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1041 hops.push(RouteHop {
1042 pubkey: nodes[3].node.get_our_node_id(),
1043 node_features: NodeFeatures::empty(),
1044 short_channel_id: chan_3.0.contents.short_channel_id,
1045 channel_features: ChannelFeatures::empty(),
1047 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1049 hops.push(RouteHop {
1050 pubkey: nodes[1].node.get_our_node_id(),
1051 node_features: nodes[1].node.node_features(),
1052 short_channel_id: chan_4.0.contents.short_channel_id,
1053 channel_features: nodes[1].node.channel_features(),
1055 cltv_expiry_delta: TEST_FINAL_CLTV,
1057 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;
1058 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;
1059 let payment_preimage_1 = send_along_route(&nodes[1],
1060 Route { paths: vec![Path { hops, blinded_tail: None }], route_params: None },
1061 &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1063 let mut hops = Vec::with_capacity(3);
1064 hops.push(RouteHop {
1065 pubkey: nodes[3].node.get_our_node_id(),
1066 node_features: NodeFeatures::empty(),
1067 short_channel_id: chan_4.0.contents.short_channel_id,
1068 channel_features: ChannelFeatures::empty(),
1070 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1072 hops.push(RouteHop {
1073 pubkey: nodes[2].node.get_our_node_id(),
1074 node_features: NodeFeatures::empty(),
1075 short_channel_id: chan_3.0.contents.short_channel_id,
1076 channel_features: ChannelFeatures::empty(),
1078 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1080 hops.push(RouteHop {
1081 pubkey: nodes[1].node.get_our_node_id(),
1082 node_features: nodes[1].node.node_features(),
1083 short_channel_id: chan_2.0.contents.short_channel_id,
1084 channel_features: nodes[1].node.channel_features(),
1086 cltv_expiry_delta: TEST_FINAL_CLTV,
1088 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;
1089 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;
1090 let payment_hash_2 = send_along_route(&nodes[1],
1091 Route { paths: vec![Path { hops, blinded_tail: None }], route_params: None },
1092 &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1094 // Claim the rebalances...
1095 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1096 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1098 // Close down the channels...
1099 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1100 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1101 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
1102 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1103 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[2].node.get_our_node_id()], 100000);
1104 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1105 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1106 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure, [nodes[3].node.get_our_node_id()], 100000);
1107 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure, [nodes[2].node.get_our_node_id()], 100000);
1108 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1109 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[3].node.get_our_node_id()], 100000);
1110 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1114 fn holding_cell_htlc_counting() {
1115 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1116 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1117 // commitment dance rounds.
1118 let chanmon_cfgs = create_chanmon_cfgs(3);
1119 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1120 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1121 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1122 create_announced_chan_between_nodes(&nodes, 0, 1);
1123 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1125 // Fetch a route in advance as we will be unable to once we're unable to send.
1126 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1128 let mut payments = Vec::new();
1130 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1131 nodes[1].node.send_payment_with_route(&route, payment_hash,
1132 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1133 payments.push((payment_preimage, payment_hash));
1135 check_added_monitors!(nodes[1], 1);
1137 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1138 assert_eq!(events.len(), 1);
1139 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1140 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1142 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1143 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1146 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, payment_hash_1,
1147 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)
1148 ), true, APIError::ChannelUnavailable { .. }, {});
1149 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1152 // This should also be true if we try to forward a payment.
1153 let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1155 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1156 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1157 check_added_monitors!(nodes[0], 1);
1160 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1161 assert_eq!(events.len(), 1);
1162 let payment_event = SendEvent::from_event(events.pop().unwrap());
1163 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1165 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1166 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1167 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1168 // fails), the second will process the resulting failure and fail the HTLC backward.
1169 expect_pending_htlcs_forwardable!(nodes[1]);
1170 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 }]);
1171 check_added_monitors!(nodes[1], 1);
1173 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1174 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1175 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1177 expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1179 // Now forward all the pending HTLCs and claim them back
1180 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1181 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1182 check_added_monitors!(nodes[2], 1);
1184 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1185 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1186 check_added_monitors!(nodes[1], 1);
1187 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1189 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1190 check_added_monitors!(nodes[1], 1);
1191 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1193 for ref update in as_updates.update_add_htlcs.iter() {
1194 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1196 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1197 check_added_monitors!(nodes[2], 1);
1198 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1199 check_added_monitors!(nodes[2], 1);
1200 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1202 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1203 check_added_monitors!(nodes[1], 1);
1204 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1205 check_added_monitors!(nodes[1], 1);
1206 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1208 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1209 check_added_monitors!(nodes[2], 1);
1211 expect_pending_htlcs_forwardable!(nodes[2]);
1213 let events = nodes[2].node.get_and_clear_pending_events();
1214 assert_eq!(events.len(), payments.len());
1215 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1217 &Event::PaymentClaimable { ref payment_hash, .. } => {
1218 assert_eq!(*payment_hash, *hash);
1220 _ => panic!("Unexpected event"),
1224 for (preimage, _) in payments.drain(..) {
1225 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1228 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1232 fn duplicate_htlc_test() {
1233 // Test that we accept duplicate payment_hash HTLCs across the network and that
1234 // claiming/failing them are all separate and don't affect each other
1235 let chanmon_cfgs = create_chanmon_cfgs(6);
1236 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1237 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1238 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1240 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1241 create_announced_chan_between_nodes(&nodes, 0, 3);
1242 create_announced_chan_between_nodes(&nodes, 1, 3);
1243 create_announced_chan_between_nodes(&nodes, 2, 3);
1244 create_announced_chan_between_nodes(&nodes, 3, 4);
1245 create_announced_chan_between_nodes(&nodes, 3, 5);
1247 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1249 *nodes[0].network_payment_count.borrow_mut() -= 1;
1250 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1252 *nodes[0].network_payment_count.borrow_mut() -= 1;
1253 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1255 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1256 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1257 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1261 fn test_duplicate_htlc_different_direction_onchain() {
1262 // Test that ChannelMonitor doesn't generate 2 preimage txn
1263 // when we have 2 HTLCs with same preimage that go across a node
1264 // in opposite directions, even with the same payment secret.
1265 let chanmon_cfgs = create_chanmon_cfgs(2);
1266 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1267 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1268 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1270 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1273 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1275 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1277 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1278 let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
1279 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1281 // Provide preimage to node 0 by claiming payment
1282 nodes[0].node.claim_funds(payment_preimage);
1283 expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1284 check_added_monitors!(nodes[0], 1);
1286 // Broadcast node 1 commitment txn
1287 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1289 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1290 let mut has_both_htlcs = 0; // check htlcs match ones committed
1291 for outp in remote_txn[0].output.iter() {
1292 if outp.value == 800_000 / 1000 {
1293 has_both_htlcs += 1;
1294 } else if outp.value == 900_000 / 1000 {
1295 has_both_htlcs += 1;
1298 assert_eq!(has_both_htlcs, 2);
1300 mine_transaction(&nodes[0], &remote_txn[0]);
1301 check_added_monitors!(nodes[0], 1);
1302 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
1303 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
1305 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1306 assert_eq!(claim_txn.len(), 3);
1308 check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1309 check_spends!(claim_txn[1], remote_txn[0]);
1310 check_spends!(claim_txn[2], remote_txn[0]);
1311 let preimage_tx = &claim_txn[0];
1312 let (preimage_bump_tx, timeout_tx) = if claim_txn[1].input[0].previous_output == preimage_tx.input[0].previous_output {
1313 (&claim_txn[1], &claim_txn[2])
1315 (&claim_txn[2], &claim_txn[1])
1318 assert_eq!(preimage_tx.input.len(), 1);
1319 assert_eq!(preimage_bump_tx.input.len(), 1);
1321 assert_eq!(preimage_tx.input.len(), 1);
1322 assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1323 assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1325 assert_eq!(timeout_tx.input.len(), 1);
1326 assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1327 check_spends!(timeout_tx, remote_txn[0]);
1328 assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1330 let events = nodes[0].node.get_and_clear_pending_msg_events();
1331 assert_eq!(events.len(), 3);
1334 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1335 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1336 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1337 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1339 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, .. } } => {
1340 assert!(update_add_htlcs.is_empty());
1341 assert!(update_fail_htlcs.is_empty());
1342 assert_eq!(update_fulfill_htlcs.len(), 1);
1343 assert!(update_fail_malformed_htlcs.is_empty());
1344 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1346 _ => panic!("Unexpected event"),
1352 fn test_basic_channel_reserve() {
1353 let chanmon_cfgs = create_chanmon_cfgs(2);
1354 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1355 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1356 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1357 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1359 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1360 let channel_reserve = chan_stat.channel_reserve_msat;
1362 // The 2* and +1 are for the fee spike reserve.
1363 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));
1364 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1365 let (mut route, our_payment_hash, _, our_payment_secret) =
1366 get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
1367 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1368 let err = nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1369 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1371 PaymentSendFailure::AllFailedResendSafe(ref fails) => {
1372 if let &APIError::ChannelUnavailable { .. } = &fails[0] {}
1373 else { panic!("Unexpected error variant"); }
1375 _ => panic!("Unexpected error variant"),
1377 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1379 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1383 fn test_fee_spike_violation_fails_htlc() {
1384 let chanmon_cfgs = create_chanmon_cfgs(2);
1385 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1386 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1387 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1388 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1390 let (mut route, payment_hash, _, payment_secret) =
1391 get_route_and_payment_hash!(nodes[0], nodes[1], 3460000);
1392 route.paths[0].hops[0].fee_msat += 1;
1393 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1394 let secp_ctx = Secp256k1::new();
1395 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1397 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1399 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1400 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1401 3460001, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1402 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1403 let msg = msgs::UpdateAddHTLC {
1406 amount_msat: htlc_msat,
1407 payment_hash: payment_hash,
1408 cltv_expiry: htlc_cltv,
1409 onion_routing_packet: onion_packet,
1410 skimmed_fee_msat: None,
1413 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1415 // Now manually create the commitment_signed message corresponding to the update_add
1416 // nodes[0] just sent. In the code for construction of this message, "local" refers
1417 // to the sender of the message, and "remote" refers to the receiver.
1419 let feerate_per_kw = get_feerate!(nodes[0], nodes[1], chan.2);
1421 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1423 // Get the TestChannelSigner for each channel, which will be used to (1) get the keys
1424 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1425 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1426 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1427 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1428 let local_chan = chan_lock.channel_by_id.get(&chan.2).map(
1429 |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
1430 ).flatten().unwrap();
1431 let chan_signer = local_chan.get_signer();
1432 // Make the signer believe we validated another commitment, so we can release the secret
1433 chan_signer.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
1435 let pubkeys = chan_signer.as_ref().pubkeys();
1436 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1437 chan_signer.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1438 chan_signer.as_ref().get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1439 chan_signer.as_ref().pubkeys().funding_pubkey)
1441 let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1442 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
1443 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
1444 let remote_chan = chan_lock.channel_by_id.get(&chan.2).map(
1445 |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
1446 ).flatten().unwrap();
1447 let chan_signer = remote_chan.get_signer();
1448 let pubkeys = chan_signer.as_ref().pubkeys();
1449 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1450 chan_signer.as_ref().get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1451 chan_signer.as_ref().pubkeys().funding_pubkey)
1454 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1455 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1456 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
1458 // Build the remote commitment transaction so we can sign it, and then later use the
1459 // signature for the commitment_signed message.
1460 let local_chan_balance = 1313;
1462 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1464 amount_msat: 3460001,
1465 cltv_expiry: htlc_cltv,
1467 transaction_output_index: Some(1),
1470 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1473 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1474 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1475 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).map(
1476 |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
1477 ).flatten().unwrap();
1478 let local_chan_signer = local_chan.get_signer();
1479 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1483 local_funding, remote_funding,
1484 commit_tx_keys.clone(),
1486 &mut vec![(accepted_htlc_info, ())],
1487 &local_chan.context.channel_transaction_parameters.as_counterparty_broadcastable()
1489 local_chan_signer.as_ecdsa().unwrap().sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1492 let commit_signed_msg = msgs::CommitmentSigned {
1495 htlc_signatures: res.1,
1497 partial_signature_with_nonce: None,
1500 // Send the commitment_signed message to the nodes[1].
1501 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1502 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1504 // Send the RAA to nodes[1].
1505 let raa_msg = msgs::RevokeAndACK {
1507 per_commitment_secret: local_secret,
1508 next_per_commitment_point: next_local_point,
1510 next_local_nonce: None,
1512 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1514 let events = nodes[1].node.get_and_clear_pending_msg_events();
1515 assert_eq!(events.len(), 1);
1516 // Make sure the HTLC failed in the way we expect.
1518 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1519 assert_eq!(update_fail_htlcs.len(), 1);
1520 update_fail_htlcs[0].clone()
1522 _ => panic!("Unexpected event"),
1524 nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1525 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", raa_msg.channel_id), 1);
1527 check_added_monitors!(nodes[1], 2);
1531 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1532 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1533 // Set the fee rate for the channel very high, to the point where the fundee
1534 // sending any above-dust amount would result in a channel reserve violation.
1535 // In this test we check that we would be prevented from sending an HTLC in
1537 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1538 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1539 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1540 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1541 let default_config = UserConfig::default();
1542 let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1544 let mut push_amt = 100_000_000;
1545 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1547 push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1549 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1551 // Fetch a route in advance as we will be unable to once we're unable to send.
1552 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1553 // Sending exactly enough to hit the reserve amount should be accepted
1554 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1555 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1558 // However one more HTLC should be significantly over the reserve amount and fail.
1559 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1560 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1561 ), true, APIError::ChannelUnavailable { .. }, {});
1562 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1566 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1567 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1568 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1569 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1570 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1571 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1572 let default_config = UserConfig::default();
1573 let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1575 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1576 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1577 // transaction fee with 0 HTLCs (183 sats)).
1578 let mut push_amt = 100_000_000;
1579 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1580 push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1581 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1583 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1584 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1585 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1588 let (mut route, payment_hash, _, payment_secret) =
1589 get_route_and_payment_hash!(nodes[1], nodes[0], 1000);
1590 route.paths[0].hops[0].fee_msat = 700_000;
1591 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1592 let secp_ctx = Secp256k1::new();
1593 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1594 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1595 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1596 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1597 700_000, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1598 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1599 let msg = msgs::UpdateAddHTLC {
1601 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1602 amount_msat: htlc_msat,
1603 payment_hash: payment_hash,
1604 cltv_expiry: htlc_cltv,
1605 onion_routing_packet: onion_packet,
1606 skimmed_fee_msat: None,
1609 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1610 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1611 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value".to_string(), 1);
1612 assert_eq!(nodes[0].node.list_channels().len(), 0);
1613 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1614 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1615 check_added_monitors!(nodes[0], 1);
1616 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() },
1617 [nodes[1].node.get_our_node_id()], 100000);
1621 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1622 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1623 // calculating our commitment transaction fee (this was previously broken).
1624 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1625 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1627 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1628 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1629 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1630 let default_config = UserConfig::default();
1631 let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1633 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1634 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1635 // transaction fee with 0 HTLCs (183 sats)).
1636 let mut push_amt = 100_000_000;
1637 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1638 push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1639 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt);
1641 let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1642 + feerate_per_kw as u64 * htlc_success_tx_weight(&channel_type_features) / 1000 * 1000 - 1;
1643 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1644 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1645 // commitment transaction fee.
1646 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1648 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1649 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1650 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1653 // One more than the dust amt should fail, however.
1654 let (mut route, our_payment_hash, _, our_payment_secret) =
1655 get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt);
1656 route.paths[0].hops[0].fee_msat += 1;
1657 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1658 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1659 ), true, APIError::ChannelUnavailable { .. }, {});
1663 fn test_chan_init_feerate_unaffordability() {
1664 // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1665 // channel reserve and feerate requirements.
1666 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1667 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1668 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1669 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1670 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1671 let default_config = UserConfig::default();
1672 let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1674 // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1676 let mut push_amt = 100_000_000;
1677 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1678 assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1679 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1681 // During open, we don't have a "counterparty channel reserve" to check against, so that
1682 // requirement only comes into play on the open_channel handling side.
1683 push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1684 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1685 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1686 open_channel_msg.push_msat += 1;
1687 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
1689 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1690 assert_eq!(msg_events.len(), 1);
1691 match msg_events[0] {
1692 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1693 assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1695 _ => panic!("Unexpected event"),
1700 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1701 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1702 // calculating our counterparty's commitment transaction fee (this was previously broken).
1703 let chanmon_cfgs = create_chanmon_cfgs(2);
1704 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1705 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1706 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1707 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000);
1709 let payment_amt = 46000; // Dust amount
1710 // In the previous code, these first four payments would succeed.
1711 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1712 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1713 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1714 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1716 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1717 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1718 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1719 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1720 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1721 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1723 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1724 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1725 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1726 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1730 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1731 let chanmon_cfgs = create_chanmon_cfgs(3);
1732 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1733 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1734 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1735 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1736 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
1739 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1740 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1741 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
1742 let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
1744 // Add a 2* and +1 for the fee spike reserve.
1745 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features);
1746 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;
1747 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1749 // Add a pending HTLC.
1750 let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1751 let payment_event_1 = {
1752 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1753 RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1754 check_added_monitors!(nodes[0], 1);
1756 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1757 assert_eq!(events.len(), 1);
1758 SendEvent::from_event(events.remove(0))
1760 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1762 // Attempt to trigger a channel reserve violation --> payment failure.
1763 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, &channel_type_features);
1764 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;
1765 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1766 let mut route_2 = route_1.clone();
1767 route_2.paths[0].hops.last_mut().unwrap().fee_msat = amt_msat_2;
1769 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1770 let secp_ctx = Secp256k1::new();
1771 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1772 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1773 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1774 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
1775 &route_2.paths[0], recv_value_2, RecipientOnionFields::spontaneous_empty(), cur_height, &None).unwrap();
1776 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1).unwrap();
1777 let msg = msgs::UpdateAddHTLC {
1780 amount_msat: htlc_msat + 1,
1781 payment_hash: our_payment_hash_1,
1782 cltv_expiry: htlc_cltv,
1783 onion_routing_packet: onion_packet,
1784 skimmed_fee_msat: None,
1787 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1788 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1789 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1790 assert_eq!(nodes[1].node.list_channels().len(), 1);
1791 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1792 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1793 check_added_monitors!(nodes[1], 1);
1794 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() },
1795 [nodes[0].node.get_our_node_id()], 100000);
1799 fn test_inbound_outbound_capacity_is_not_zero() {
1800 let chanmon_cfgs = create_chanmon_cfgs(2);
1801 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1802 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1803 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1804 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1805 let channels0 = node_chanmgrs[0].list_channels();
1806 let channels1 = node_chanmgrs[1].list_channels();
1807 let default_config = UserConfig::default();
1808 assert_eq!(channels0.len(), 1);
1809 assert_eq!(channels1.len(), 1);
1811 let reserve = get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1812 assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1813 assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1815 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1816 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1819 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, channel_type_features: &ChannelTypeFeatures) -> u64 {
1820 (commitment_tx_base_weight(channel_type_features) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1824 fn test_channel_reserve_holding_cell_htlcs() {
1825 let chanmon_cfgs = create_chanmon_cfgs(3);
1826 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1827 // When this test was written, the default base fee floated based on the HTLC count.
1828 // It is now fixed, so we simply set the fee to the expected value here.
1829 let mut config = test_default_channel_config();
1830 config.channel_config.forwarding_fee_base_msat = 239;
1831 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1832 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1833 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001);
1834 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001);
1836 let mut stat01 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1837 let mut stat11 = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
1839 let mut stat12 = get_channel_value_stat!(nodes[1], nodes[2], chan_2.2);
1840 let mut stat22 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
1842 macro_rules! expect_forward {
1844 let mut events = $node.node.get_and_clear_pending_msg_events();
1845 assert_eq!(events.len(), 1);
1846 check_added_monitors!($node, 1);
1847 let payment_event = SendEvent::from_event(events.remove(0));
1852 let feemsat = 239; // set above
1853 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1854 let feerate = get_feerate!(nodes[0], nodes[1], chan_1.2);
1855 let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_1.2);
1857 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1859 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1861 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1862 .with_bolt11_features(nodes[2].node.invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1863 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, recv_value_0);
1864 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1865 assert!(route.paths[0].hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1867 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1868 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1869 ), true, APIError::ChannelUnavailable { .. }, {});
1870 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1873 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1874 // nodes[0]'s wealth
1876 let amt_msat = recv_value_0 + total_fee_msat;
1877 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1878 // Also, ensure that each payment has enough to be over the dust limit to
1879 // ensure it'll be included in each commit tx fee calculation.
1880 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, &channel_type_features);
1881 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1882 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1886 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1887 .with_bolt11_features(nodes[2].node.invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1888 let route = get_route!(nodes[0], payment_params, recv_value_0).unwrap();
1889 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1890 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1892 let (stat01_, stat11_, stat12_, stat22_) = (
1893 get_channel_value_stat!(nodes[0], nodes[1], chan_1.2),
1894 get_channel_value_stat!(nodes[1], nodes[0], chan_1.2),
1895 get_channel_value_stat!(nodes[1], nodes[2], chan_2.2),
1896 get_channel_value_stat!(nodes[2], nodes[1], chan_2.2),
1899 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1900 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1901 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1902 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1903 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1906 // adding pending output.
1907 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1908 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1909 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1910 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1911 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1912 // cases where 1 msat over X amount will cause a payment failure, but anything less than
1913 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1914 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1915 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1917 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features);
1918 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1919 let amt_msat_1 = recv_value_1 + total_fee_msat;
1921 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);
1922 let payment_event_1 = {
1923 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1924 RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1925 check_added_monitors!(nodes[0], 1);
1927 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1928 assert_eq!(events.len(), 1);
1929 SendEvent::from_event(events.remove(0))
1931 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1933 // channel reserve test with htlc pending output > 0
1934 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1936 let mut route = route_1.clone();
1937 route.paths[0].hops.last_mut().unwrap().fee_msat = recv_value_2 + 1;
1938 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
1939 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1940 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1941 ), true, APIError::ChannelUnavailable { .. }, {});
1942 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1945 // split the rest to test holding cell
1946 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, &channel_type_features);
1947 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1948 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1949 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1951 let stat = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1952 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);
1955 // now see if they go through on both sides
1956 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);
1957 // but this will stuck in the holding cell
1958 nodes[0].node.send_payment_with_route(&route_21, our_payment_hash_21,
1959 RecipientOnionFields::secret_only(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
1960 check_added_monitors!(nodes[0], 0);
1961 let events = nodes[0].node.get_and_clear_pending_events();
1962 assert_eq!(events.len(), 0);
1964 // test with outbound holding cell amount > 0
1966 let (mut route, our_payment_hash, _, our_payment_secret) =
1967 get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22);
1968 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1969 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1970 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1971 ), true, APIError::ChannelUnavailable { .. }, {});
1972 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1975 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);
1976 // this will also stuck in the holding cell
1977 nodes[0].node.send_payment_with_route(&route_22, our_payment_hash_22,
1978 RecipientOnionFields::secret_only(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
1979 check_added_monitors!(nodes[0], 0);
1980 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1981 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1983 // flush the pending htlc
1984 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1985 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1986 check_added_monitors!(nodes[1], 1);
1988 // the pending htlc should be promoted to committed
1989 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1990 check_added_monitors!(nodes[0], 1);
1991 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1993 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1994 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1995 // No commitment_signed so get_event_msg's assert(len == 1) passes
1996 check_added_monitors!(nodes[0], 1);
1998 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1999 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2000 check_added_monitors!(nodes[1], 1);
2002 expect_pending_htlcs_forwardable!(nodes[1]);
2004 let ref payment_event_11 = expect_forward!(nodes[1]);
2005 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
2006 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
2008 expect_pending_htlcs_forwardable!(nodes[2]);
2009 expect_payment_claimable!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
2011 // flush the htlcs in the holding cell
2012 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
2013 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
2014 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
2015 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
2016 expect_pending_htlcs_forwardable!(nodes[1]);
2018 let ref payment_event_3 = expect_forward!(nodes[1]);
2019 assert_eq!(payment_event_3.msgs.len(), 2);
2020 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
2021 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
2023 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2024 expect_pending_htlcs_forwardable!(nodes[2]);
2026 let events = nodes[2].node.get_and_clear_pending_events();
2027 assert_eq!(events.len(), 2);
2029 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2030 assert_eq!(our_payment_hash_21, *payment_hash);
2031 assert_eq!(recv_value_21, amount_msat);
2032 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2033 assert_eq!(via_channel_id, Some(chan_2.2));
2035 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2036 assert!(payment_preimage.is_none());
2037 assert_eq!(our_payment_secret_21, *payment_secret);
2039 _ => panic!("expected PaymentPurpose::InvoicePayment")
2042 _ => panic!("Unexpected event"),
2045 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2046 assert_eq!(our_payment_hash_22, *payment_hash);
2047 assert_eq!(recv_value_22, amount_msat);
2048 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2049 assert_eq!(via_channel_id, Some(chan_2.2));
2051 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2052 assert!(payment_preimage.is_none());
2053 assert_eq!(our_payment_secret_22, *payment_secret);
2055 _ => panic!("expected PaymentPurpose::InvoicePayment")
2058 _ => panic!("Unexpected event"),
2061 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2062 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2063 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2065 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, &channel_type_features);
2066 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2067 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2069 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
2070 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);
2071 let stat0 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
2072 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2073 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2075 let stat2 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
2076 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2080 fn channel_reserve_in_flight_removes() {
2081 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2082 // can send to its counterparty, but due to update ordering, the other side may not yet have
2083 // considered those HTLCs fully removed.
2084 // This tests that we don't count HTLCs which will not be included in the next remote
2085 // commitment transaction towards the reserve value (as it implies no commitment transaction
2086 // will be generated which violates the remote reserve value).
2087 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2089 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2090 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2091 // you only consider the value of the first HTLC, it may not),
2092 // * start routing a third HTLC from A to B,
2093 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2094 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2095 // * deliver the first fulfill from B
2096 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2098 // * deliver A's response CS and RAA.
2099 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2100 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
2101 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2102 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2103 let chanmon_cfgs = create_chanmon_cfgs(2);
2104 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2105 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2106 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2107 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2109 let b_chan_values = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
2110 // Route the first two HTLCs.
2111 let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2112 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2113 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2115 // Start routing the third HTLC (this is just used to get everyone in the right state).
2116 let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2118 nodes[0].node.send_payment_with_route(&route, payment_hash_3,
2119 RecipientOnionFields::secret_only(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2120 check_added_monitors!(nodes[0], 1);
2121 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2122 assert_eq!(events.len(), 1);
2123 SendEvent::from_event(events.remove(0))
2126 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2127 // initial fulfill/CS.
2128 nodes[1].node.claim_funds(payment_preimage_1);
2129 expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2130 check_added_monitors!(nodes[1], 1);
2131 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2133 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2134 // remove the second HTLC when we send the HTLC back from B to A.
2135 nodes[1].node.claim_funds(payment_preimage_2);
2136 expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2137 check_added_monitors!(nodes[1], 1);
2138 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2140 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2141 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2142 check_added_monitors!(nodes[0], 1);
2143 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2144 expect_payment_sent(&nodes[0], payment_preimage_1, None, false, false);
2146 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2147 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2148 check_added_monitors!(nodes[1], 1);
2149 // B is already AwaitingRAA, so cant generate a CS here
2150 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2152 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2153 check_added_monitors!(nodes[1], 1);
2154 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2156 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2157 check_added_monitors!(nodes[0], 1);
2158 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2160 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2161 check_added_monitors!(nodes[1], 1);
2162 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2164 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2165 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2166 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2167 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2168 // on-chain as necessary).
2169 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2170 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2171 check_added_monitors!(nodes[0], 1);
2172 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2173 expect_payment_sent(&nodes[0], payment_preimage_2, None, false, false);
2175 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2176 check_added_monitors!(nodes[1], 1);
2177 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2179 expect_pending_htlcs_forwardable!(nodes[1]);
2180 expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2182 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2183 // resolve the second HTLC from A's point of view.
2184 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2185 check_added_monitors!(nodes[0], 1);
2186 expect_payment_path_successful!(nodes[0]);
2187 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2189 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2190 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2191 let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2193 nodes[1].node.send_payment_with_route(&route, payment_hash_4,
2194 RecipientOnionFields::secret_only(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2195 check_added_monitors!(nodes[1], 1);
2196 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2197 assert_eq!(events.len(), 1);
2198 SendEvent::from_event(events.remove(0))
2201 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2202 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2203 check_added_monitors!(nodes[0], 1);
2204 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2206 // Now just resolve all the outstanding messages/HTLCs for completeness...
2208 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2209 check_added_monitors!(nodes[1], 1);
2210 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2212 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2213 check_added_monitors!(nodes[1], 1);
2215 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2216 check_added_monitors!(nodes[0], 1);
2217 expect_payment_path_successful!(nodes[0]);
2218 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2220 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2221 check_added_monitors!(nodes[1], 1);
2222 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2224 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2225 check_added_monitors!(nodes[0], 1);
2227 expect_pending_htlcs_forwardable!(nodes[0]);
2228 expect_payment_claimable!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2230 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2231 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2235 fn channel_monitor_network_test() {
2236 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2237 // tests that ChannelMonitor is able to recover from various states.
2238 let chanmon_cfgs = create_chanmon_cfgs(5);
2239 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2240 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2241 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2243 // Create some initial channels
2244 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2245 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2246 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2247 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
2249 // Make sure all nodes are at the same starting height
2250 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2251 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2252 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2253 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2254 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2256 // Rebalance the network a bit by relaying one payment through all the channels...
2257 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2258 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2259 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2260 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2262 // Simple case with no pending HTLCs:
2263 nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2264 check_added_monitors!(nodes[1], 1);
2265 check_closed_broadcast!(nodes[1], true);
2267 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2268 assert_eq!(node_txn.len(), 1);
2269 mine_transaction(&nodes[0], &node_txn[0]);
2270 check_added_monitors!(nodes[0], 1);
2271 test_txn_broadcast(&nodes[0], &chan_1, Some(node_txn[0].clone()), HTLCType::NONE);
2273 check_closed_broadcast!(nodes[0], true);
2274 assert_eq!(nodes[0].node.list_channels().len(), 0);
2275 assert_eq!(nodes[1].node.list_channels().len(), 1);
2276 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2277 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[0].node.get_our_node_id()], 100000);
2279 // One pending HTLC is discarded by the force-close:
2280 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2282 // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2283 // broadcasted until we reach the timelock time).
2284 nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2285 check_closed_broadcast!(nodes[1], true);
2286 check_added_monitors!(nodes[1], 1);
2288 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2289 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2290 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2291 mine_transaction(&nodes[2], &node_txn[0]);
2292 check_added_monitors!(nodes[2], 1);
2293 test_txn_broadcast(&nodes[2], &chan_2, Some(node_txn[0].clone()), HTLCType::NONE);
2295 check_closed_broadcast!(nodes[2], true);
2296 assert_eq!(nodes[1].node.list_channels().len(), 0);
2297 assert_eq!(nodes[2].node.list_channels().len(), 1);
2298 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[2].node.get_our_node_id()], 100000);
2299 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2301 macro_rules! claim_funds {
2302 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2304 $node.node.claim_funds($preimage);
2305 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2306 check_added_monitors!($node, 1);
2308 let events = $node.node.get_and_clear_pending_msg_events();
2309 assert_eq!(events.len(), 1);
2311 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2312 assert!(update_add_htlcs.is_empty());
2313 assert!(update_fail_htlcs.is_empty());
2314 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2316 _ => panic!("Unexpected event"),
2322 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2323 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2324 nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2325 check_added_monitors!(nodes[2], 1);
2326 check_closed_broadcast!(nodes[2], true);
2327 let node2_commitment_txid;
2329 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2330 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2331 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2332 node2_commitment_txid = node_txn[0].txid();
2334 // Claim the payment on nodes[3], giving it knowledge of the preimage
2335 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2336 mine_transaction(&nodes[3], &node_txn[0]);
2337 check_added_monitors!(nodes[3], 1);
2338 check_preimage_claim(&nodes[3], &node_txn);
2340 check_closed_broadcast!(nodes[3], true);
2341 assert_eq!(nodes[2].node.list_channels().len(), 0);
2342 assert_eq!(nodes[3].node.list_channels().len(), 1);
2343 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed, [nodes[3].node.get_our_node_id()], 100000);
2344 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
2346 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2347 // confusing us in the following tests.
2348 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2350 // One pending HTLC to time out:
2351 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2352 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2355 let (close_chan_update_1, close_chan_update_2) = {
2356 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2357 let events = nodes[3].node.get_and_clear_pending_msg_events();
2358 assert_eq!(events.len(), 2);
2359 let close_chan_update_1 = match events[0] {
2360 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2363 _ => panic!("Unexpected event"),
2366 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2367 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2369 _ => panic!("Unexpected event"),
2371 check_added_monitors!(nodes[3], 1);
2373 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2375 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2376 node_txn.retain(|tx| {
2377 if tx.input[0].previous_output.txid == node2_commitment_txid {
2383 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2385 // Claim the payment on nodes[4], giving it knowledge of the preimage
2386 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2388 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2389 let events = nodes[4].node.get_and_clear_pending_msg_events();
2390 assert_eq!(events.len(), 2);
2391 let close_chan_update_2 = match events[0] {
2392 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2395 _ => panic!("Unexpected event"),
2398 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2399 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2401 _ => panic!("Unexpected event"),
2403 check_added_monitors!(nodes[4], 1);
2404 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2406 mine_transaction(&nodes[4], &node_txn[0]);
2407 check_preimage_claim(&nodes[4], &node_txn);
2408 (close_chan_update_1, close_chan_update_2)
2410 nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2411 nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2412 assert_eq!(nodes[3].node.list_channels().len(), 0);
2413 assert_eq!(nodes[4].node.list_channels().len(), 0);
2415 assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2416 ChannelMonitorUpdateStatus::Completed);
2417 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed, [nodes[4].node.get_our_node_id()], 100000);
2418 check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed, [nodes[3].node.get_our_node_id()], 100000);
2422 fn test_justice_tx_htlc_timeout() {
2423 // Test justice txn built on revoked HTLC-Timeout tx, against both sides
2424 let mut alice_config = UserConfig::default();
2425 alice_config.channel_handshake_config.announced_channel = true;
2426 alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2427 alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2428 let mut bob_config = UserConfig::default();
2429 bob_config.channel_handshake_config.announced_channel = true;
2430 bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2431 bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2432 let user_cfgs = [Some(alice_config), Some(bob_config)];
2433 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2434 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2435 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2436 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2437 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2438 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2439 // Create some new channels:
2440 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
2442 // A pending HTLC which will be revoked:
2443 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2444 // Get the will-be-revoked local txn from nodes[0]
2445 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2446 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2447 assert_eq!(revoked_local_txn[0].input.len(), 1);
2448 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2449 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2450 assert_eq!(revoked_local_txn[1].input.len(), 1);
2451 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2452 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2453 // Revoke the old state
2454 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2457 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2459 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2460 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2461 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2462 check_spends!(node_txn[0], revoked_local_txn[0]);
2463 node_txn.swap_remove(0);
2465 check_added_monitors!(nodes[1], 1);
2466 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2467 test_txn_broadcast(&nodes[1], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2469 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2470 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2471 // Verify broadcast of revoked HTLC-timeout
2472 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2473 check_added_monitors!(nodes[0], 1);
2474 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2475 // Broadcast revoked HTLC-timeout on node 1
2476 mine_transaction(&nodes[1], &node_txn[1]);
2477 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2479 get_announce_close_broadcast_events(&nodes, 0, 1);
2480 assert_eq!(nodes[0].node.list_channels().len(), 0);
2481 assert_eq!(nodes[1].node.list_channels().len(), 0);
2485 fn test_justice_tx_htlc_success() {
2486 // Test justice txn built on revoked HTLC-Success tx, against both sides
2487 let mut alice_config = UserConfig::default();
2488 alice_config.channel_handshake_config.announced_channel = true;
2489 alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2490 alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2491 let mut bob_config = UserConfig::default();
2492 bob_config.channel_handshake_config.announced_channel = true;
2493 bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2494 bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2495 let user_cfgs = [Some(alice_config), Some(bob_config)];
2496 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2497 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2498 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2499 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2500 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2501 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2502 // Create some new channels:
2503 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
2505 // A pending HTLC which will be revoked:
2506 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2507 // Get the will-be-revoked local txn from B
2508 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2509 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2510 assert_eq!(revoked_local_txn[0].input.len(), 1);
2511 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2512 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2513 // Revoke the old state
2514 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2516 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2518 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2519 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2520 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2522 check_spends!(node_txn[0], revoked_local_txn[0]);
2523 node_txn.swap_remove(0);
2525 check_added_monitors!(nodes[0], 1);
2526 test_txn_broadcast(&nodes[0], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2528 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2529 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2530 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2531 check_added_monitors!(nodes[1], 1);
2532 mine_transaction(&nodes[0], &node_txn[1]);
2533 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2534 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2536 get_announce_close_broadcast_events(&nodes, 0, 1);
2537 assert_eq!(nodes[0].node.list_channels().len(), 0);
2538 assert_eq!(nodes[1].node.list_channels().len(), 0);
2542 fn revoked_output_claim() {
2543 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2544 // transaction is broadcast by its counterparty
2545 let chanmon_cfgs = create_chanmon_cfgs(2);
2546 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2547 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2548 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2549 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2550 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2551 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2552 assert_eq!(revoked_local_txn.len(), 1);
2553 // Only output is the full channel value back to nodes[0]:
2554 assert_eq!(revoked_local_txn[0].output.len(), 1);
2555 // Send a payment through, updating everyone's latest commitment txn
2556 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2558 // Inform nodes[1] that nodes[0] broadcast a stale tx
2559 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2560 check_added_monitors!(nodes[1], 1);
2561 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2562 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2563 assert_eq!(node_txn.len(), 1); // ChannelMonitor: justice tx against revoked to_local output
2565 check_spends!(node_txn[0], revoked_local_txn[0]);
2567 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2568 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2569 get_announce_close_broadcast_events(&nodes, 0, 1);
2570 check_added_monitors!(nodes[0], 1);
2571 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2575 fn test_forming_justice_tx_from_monitor_updates() {
2576 do_test_forming_justice_tx_from_monitor_updates(true);
2577 do_test_forming_justice_tx_from_monitor_updates(false);
2580 fn do_test_forming_justice_tx_from_monitor_updates(broadcast_initial_commitment: bool) {
2581 // Simple test to make sure that the justice tx formed in WatchtowerPersister
2582 // is properly formed and can be broadcasted/confirmed successfully in the event
2583 // that a revoked commitment transaction is broadcasted
2584 // (Similar to `revoked_output_claim` test but we get the justice tx + broadcast manually)
2585 let chanmon_cfgs = create_chanmon_cfgs(2);
2586 let destination_script0 = chanmon_cfgs[0].keys_manager.get_destination_script().unwrap();
2587 let destination_script1 = chanmon_cfgs[1].keys_manager.get_destination_script().unwrap();
2588 let persisters = vec![WatchtowerPersister::new(destination_script0),
2589 WatchtowerPersister::new(destination_script1)];
2590 let node_cfgs = create_node_cfgs_with_persisters(2, &chanmon_cfgs, persisters.iter().collect());
2591 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2592 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2593 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
2594 let funding_txo = OutPoint { txid: funding_tx.txid(), index: 0 };
2596 if !broadcast_initial_commitment {
2597 // Send a payment to move the channel forward
2598 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5_000_000);
2601 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output.
2602 // We'll keep this commitment transaction to broadcast once it's revoked.
2603 let revoked_local_txn = get_local_commitment_txn!(nodes[0], channel_id);
2604 assert_eq!(revoked_local_txn.len(), 1);
2605 let revoked_commitment_tx = &revoked_local_txn[0];
2607 // Send another payment, now revoking the previous commitment tx
2608 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5_000_000);
2610 let justice_tx = persisters[1].justice_tx(funding_txo, &revoked_commitment_tx.txid()).unwrap();
2611 check_spends!(justice_tx, revoked_commitment_tx);
2613 mine_transactions(&nodes[1], &[revoked_commitment_tx, &justice_tx]);
2614 mine_transactions(&nodes[0], &[revoked_commitment_tx, &justice_tx]);
2616 check_added_monitors!(nodes[1], 1);
2617 check_closed_event(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false,
2618 &[nodes[0].node.get_our_node_id()], 100_000);
2619 get_announce_close_broadcast_events(&nodes, 1, 0);
2621 check_added_monitors!(nodes[0], 1);
2622 check_closed_event(&nodes[0], 1, ClosureReason::CommitmentTxConfirmed, false,
2623 &[nodes[1].node.get_our_node_id()], 100_000);
2625 // Check that the justice tx has sent the revoked output value to nodes[1]
2626 let monitor = get_monitor!(nodes[1], channel_id);
2627 let total_claimable_balance = monitor.get_claimable_balances().iter().fold(0, |sum, balance| {
2629 channelmonitor::Balance::ClaimableAwaitingConfirmations { amount_satoshis, .. } => sum + amount_satoshis,
2630 _ => panic!("Unexpected balance type"),
2633 // On the first commitment, node[1]'s balance was below dust so it didn't have an output
2634 let node1_channel_balance = if broadcast_initial_commitment { 0 } else { revoked_commitment_tx.output[0].value };
2635 let expected_claimable_balance = node1_channel_balance + justice_tx.output[0].value;
2636 assert_eq!(total_claimable_balance, expected_claimable_balance);
2641 fn claim_htlc_outputs_shared_tx() {
2642 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2643 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2644 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2645 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2646 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2647 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2649 // Create some new channel:
2650 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2652 // Rebalance the network to generate htlc in the two directions
2653 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2654 // 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
2655 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2656 let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2658 // Get the will-be-revoked local txn from node[0]
2659 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2660 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2661 assert_eq!(revoked_local_txn[0].input.len(), 1);
2662 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2663 assert_eq!(revoked_local_txn[1].input.len(), 1);
2664 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2665 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2666 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2668 //Revoke the old state
2669 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2672 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2673 check_added_monitors!(nodes[0], 1);
2674 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2675 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2676 check_added_monitors!(nodes[1], 1);
2677 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2678 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2679 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2681 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2682 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2684 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2685 check_spends!(node_txn[0], revoked_local_txn[0]);
2687 let mut witness_lens = BTreeSet::new();
2688 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2689 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2690 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2691 assert_eq!(witness_lens.len(), 3);
2692 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2693 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2694 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2696 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2697 // ANTI_REORG_DELAY confirmations.
2698 mine_transaction(&nodes[1], &node_txn[0]);
2699 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2700 expect_payment_failed!(nodes[1], payment_hash_2, false);
2702 get_announce_close_broadcast_events(&nodes, 0, 1);
2703 assert_eq!(nodes[0].node.list_channels().len(), 0);
2704 assert_eq!(nodes[1].node.list_channels().len(), 0);
2708 fn claim_htlc_outputs_single_tx() {
2709 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2710 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2711 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2712 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2713 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2714 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2716 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2718 // Rebalance the network to generate htlc in the two directions
2719 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2720 // 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
2721 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2722 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2723 let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2725 // Get the will-be-revoked local txn from node[0]
2726 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2728 //Revoke the old state
2729 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2732 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2733 check_added_monitors!(nodes[0], 1);
2734 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2735 check_added_monitors!(nodes[1], 1);
2736 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2737 let mut events = nodes[0].node.get_and_clear_pending_events();
2738 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2739 match events.last().unwrap() {
2740 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2741 _ => panic!("Unexpected event"),
2744 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2745 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2747 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcast();
2749 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2750 assert_eq!(node_txn[0].input.len(), 1);
2751 check_spends!(node_txn[0], chan_1.3);
2752 assert_eq!(node_txn[1].input.len(), 1);
2753 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2754 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2755 check_spends!(node_txn[1], node_txn[0]);
2757 // Filter out any non justice transactions.
2758 node_txn.retain(|tx| tx.input[0].previous_output.txid == revoked_local_txn[0].txid());
2759 assert!(node_txn.len() > 3);
2761 assert_eq!(node_txn[0].input.len(), 1);
2762 assert_eq!(node_txn[1].input.len(), 1);
2763 assert_eq!(node_txn[2].input.len(), 1);
2765 check_spends!(node_txn[0], revoked_local_txn[0]);
2766 check_spends!(node_txn[1], revoked_local_txn[0]);
2767 check_spends!(node_txn[2], revoked_local_txn[0]);
2769 let mut witness_lens = BTreeSet::new();
2770 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2771 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2772 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2773 assert_eq!(witness_lens.len(), 3);
2774 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2775 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2776 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2778 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2779 // ANTI_REORG_DELAY confirmations.
2780 mine_transaction(&nodes[1], &node_txn[0]);
2781 mine_transaction(&nodes[1], &node_txn[1]);
2782 mine_transaction(&nodes[1], &node_txn[2]);
2783 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2784 expect_payment_failed!(nodes[1], payment_hash_2, false);
2786 get_announce_close_broadcast_events(&nodes, 0, 1);
2787 assert_eq!(nodes[0].node.list_channels().len(), 0);
2788 assert_eq!(nodes[1].node.list_channels().len(), 0);
2792 fn test_htlc_on_chain_success() {
2793 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2794 // the preimage backward accordingly. So here we test that ChannelManager is
2795 // broadcasting the right event to other nodes in payment path.
2796 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2797 // A --------------------> B ----------------------> C (preimage)
2798 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2799 // commitment transaction was broadcast.
2800 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2802 // B should be able to claim via preimage if A then broadcasts its local tx.
2803 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2804 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2805 // PaymentSent event).
2807 let chanmon_cfgs = create_chanmon_cfgs(3);
2808 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2809 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2810 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2812 // Create some initial channels
2813 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2814 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2816 // Ensure all nodes are at the same height
2817 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2818 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2819 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2820 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2822 // Rebalance the network a bit by relaying one payment through all the channels...
2823 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2824 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2826 let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2827 let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2829 // Broadcast legit commitment tx from C on B's chain
2830 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2831 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2832 assert_eq!(commitment_tx.len(), 1);
2833 check_spends!(commitment_tx[0], chan_2.3);
2834 nodes[2].node.claim_funds(our_payment_preimage);
2835 expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2836 nodes[2].node.claim_funds(our_payment_preimage_2);
2837 expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2838 check_added_monitors!(nodes[2], 2);
2839 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2840 assert!(updates.update_add_htlcs.is_empty());
2841 assert!(updates.update_fail_htlcs.is_empty());
2842 assert!(updates.update_fail_malformed_htlcs.is_empty());
2843 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2845 mine_transaction(&nodes[2], &commitment_tx[0]);
2846 check_closed_broadcast!(nodes[2], true);
2847 check_added_monitors!(nodes[2], 1);
2848 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2849 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 2 (2 * HTLC-Success tx)
2850 assert_eq!(node_txn.len(), 2);
2851 check_spends!(node_txn[0], commitment_tx[0]);
2852 check_spends!(node_txn[1], commitment_tx[0]);
2853 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2854 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2855 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2856 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2857 assert_eq!(node_txn[0].lock_time.0, 0);
2858 assert_eq!(node_txn[1].lock_time.0, 0);
2860 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2861 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()]));
2862 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2864 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2865 assert_eq!(added_monitors.len(), 1);
2866 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2867 added_monitors.clear();
2869 let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2870 assert_eq!(forwarded_events.len(), 3);
2871 match forwarded_events[0] {
2872 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2873 _ => panic!("Unexpected event"),
2875 let chan_id = Some(chan_1.2);
2876 match forwarded_events[1] {
2877 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2878 assert_eq!(fee_earned_msat, Some(1000));
2879 assert_eq!(prev_channel_id, chan_id);
2880 assert_eq!(claim_from_onchain_tx, true);
2881 assert_eq!(next_channel_id, Some(chan_2.2));
2882 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2886 match forwarded_events[2] {
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 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2898 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2899 assert_eq!(added_monitors.len(), 2);
2900 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2901 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2902 added_monitors.clear();
2904 assert_eq!(events.len(), 3);
2906 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
2907 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
2909 match nodes_2_event {
2910 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2911 _ => panic!("Unexpected event"),
2914 match nodes_0_event {
2915 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, .. } } => {
2916 assert!(update_add_htlcs.is_empty());
2917 assert!(update_fail_htlcs.is_empty());
2918 assert_eq!(update_fulfill_htlcs.len(), 1);
2919 assert!(update_fail_malformed_htlcs.is_empty());
2920 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2922 _ => panic!("Unexpected event"),
2925 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
2927 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2928 _ => panic!("Unexpected event"),
2931 macro_rules! check_tx_local_broadcast {
2932 ($node: expr, $htlc_offered: expr, $commitment_tx: expr) => { {
2933 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2934 assert_eq!(node_txn.len(), 2);
2935 // Node[1]: 2 * HTLC-timeout tx
2936 // Node[0]: 2 * HTLC-timeout tx
2937 check_spends!(node_txn[0], $commitment_tx);
2938 check_spends!(node_txn[1], $commitment_tx);
2939 assert_ne!(node_txn[0].lock_time.0, 0);
2940 assert_ne!(node_txn[1].lock_time.0, 0);
2942 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2943 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2944 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2945 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2947 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2948 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2949 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2950 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2955 // nodes[1] now broadcasts its own timeout-claim of the output that nodes[2] just claimed via success.
2956 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0]);
2958 // Broadcast legit commitment tx from A on B's chain
2959 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2960 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2961 check_spends!(node_a_commitment_tx[0], chan_1.3);
2962 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2963 check_closed_broadcast!(nodes[1], true);
2964 check_added_monitors!(nodes[1], 1);
2965 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2966 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2967 assert!(node_txn.len() == 1 || node_txn.len() == 3); // HTLC-Success, 2* RBF bumps of above HTLC txn
2968 let commitment_spend =
2969 if node_txn.len() == 1 {
2972 // Certain `ConnectStyle`s will cause RBF bumps of the previous HTLC transaction to be broadcast.
2973 // FullBlockViaListen
2974 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2975 check_spends!(node_txn[1], commitment_tx[0]);
2976 check_spends!(node_txn[2], commitment_tx[0]);
2977 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2980 check_spends!(node_txn[0], commitment_tx[0]);
2981 check_spends!(node_txn[1], commitment_tx[0]);
2982 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2987 check_spends!(commitment_spend, node_a_commitment_tx[0]);
2988 assert_eq!(commitment_spend.input.len(), 2);
2989 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2990 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2991 assert_eq!(commitment_spend.lock_time.0, nodes[1].best_block_info().1);
2992 assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2993 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2994 // we already checked the same situation with A.
2996 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2997 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()]));
2998 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
2999 check_closed_broadcast!(nodes[0], true);
3000 check_added_monitors!(nodes[0], 1);
3001 let events = nodes[0].node.get_and_clear_pending_events();
3002 assert_eq!(events.len(), 5);
3003 let mut first_claimed = false;
3004 for event in events {
3006 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3007 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
3008 assert!(!first_claimed);
3009 first_claimed = true;
3011 assert_eq!(payment_preimage, our_payment_preimage_2);
3012 assert_eq!(payment_hash, payment_hash_2);
3015 Event::PaymentPathSuccessful { .. } => {},
3016 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
3017 _ => panic!("Unexpected event"),
3020 check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0]);
3023 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
3024 // Test that in case of a unilateral close onchain, we detect the state of output and
3025 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
3026 // broadcasting the right event to other nodes in payment path.
3027 // A ------------------> B ----------------------> C (timeout)
3028 // B's commitment tx C's commitment tx
3030 // B's HTLC timeout tx B's timeout tx
3032 let chanmon_cfgs = create_chanmon_cfgs(3);
3033 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3034 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3035 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3036 *nodes[0].connect_style.borrow_mut() = connect_style;
3037 *nodes[1].connect_style.borrow_mut() = connect_style;
3038 *nodes[2].connect_style.borrow_mut() = connect_style;
3040 // Create some intial channels
3041 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
3042 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3044 // Rebalance the network a bit by relaying one payment thorugh all the channels...
3045 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
3046 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
3048 let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
3050 // Broadcast legit commitment tx from C on B's chain
3051 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
3052 check_spends!(commitment_tx[0], chan_2.3);
3053 nodes[2].node.fail_htlc_backwards(&payment_hash);
3054 check_added_monitors!(nodes[2], 0);
3055 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
3056 check_added_monitors!(nodes[2], 1);
3058 let events = nodes[2].node.get_and_clear_pending_msg_events();
3059 assert_eq!(events.len(), 1);
3061 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, .. } } => {
3062 assert!(update_add_htlcs.is_empty());
3063 assert!(!update_fail_htlcs.is_empty());
3064 assert!(update_fulfill_htlcs.is_empty());
3065 assert!(update_fail_malformed_htlcs.is_empty());
3066 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
3068 _ => panic!("Unexpected event"),
3070 mine_transaction(&nodes[2], &commitment_tx[0]);
3071 check_closed_broadcast!(nodes[2], true);
3072 check_added_monitors!(nodes[2], 1);
3073 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
3074 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
3075 assert_eq!(node_txn.len(), 0);
3077 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
3078 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
3079 mine_transaction(&nodes[1], &commitment_tx[0]);
3080 check_closed_event!(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false
3081 , [nodes[2].node.get_our_node_id()], 100000);
3082 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
3084 let mut txn = nodes[1].tx_broadcaster.txn_broadcast();
3085 if nodes[1].connect_style.borrow().skips_blocks() {
3086 assert_eq!(txn.len(), 1);
3088 assert_eq!(txn.len(), 3); // Two extra fee bumps for timeout transaction
3090 txn.iter().for_each(|tx| check_spends!(tx, commitment_tx[0]));
3091 assert_eq!(txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3095 mine_transaction(&nodes[1], &timeout_tx);
3096 check_added_monitors!(nodes[1], 1);
3097 check_closed_broadcast!(nodes[1], true);
3099 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3101 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 }]);
3102 check_added_monitors!(nodes[1], 1);
3103 let events = nodes[1].node.get_and_clear_pending_msg_events();
3104 assert_eq!(events.len(), 1);
3106 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, .. } } => {
3107 assert!(update_add_htlcs.is_empty());
3108 assert!(!update_fail_htlcs.is_empty());
3109 assert!(update_fulfill_htlcs.is_empty());
3110 assert!(update_fail_malformed_htlcs.is_empty());
3111 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3113 _ => panic!("Unexpected event"),
3116 // Broadcast legit commitment tx from B on A's chain
3117 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3118 check_spends!(commitment_tx[0], chan_1.3);
3120 mine_transaction(&nodes[0], &commitment_tx[0]);
3121 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
3123 check_closed_broadcast!(nodes[0], true);
3124 check_added_monitors!(nodes[0], 1);
3125 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
3126 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // 1 timeout tx
3127 assert_eq!(node_txn.len(), 1);
3128 check_spends!(node_txn[0], commitment_tx[0]);
3129 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3133 fn test_htlc_on_chain_timeout() {
3134 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3135 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3136 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3140 fn test_simple_commitment_revoked_fail_backward() {
3141 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3142 // and fail backward accordingly.
3144 let chanmon_cfgs = create_chanmon_cfgs(3);
3145 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3146 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3147 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3149 // Create some initial channels
3150 create_announced_chan_between_nodes(&nodes, 0, 1);
3151 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3153 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3154 // Get the will-be-revoked local txn from nodes[2]
3155 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3156 // Revoke the old state
3157 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3159 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3161 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3162 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
3163 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3164 check_added_monitors!(nodes[1], 1);
3165 check_closed_broadcast!(nodes[1], true);
3167 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 }]);
3168 check_added_monitors!(nodes[1], 1);
3169 let events = nodes[1].node.get_and_clear_pending_msg_events();
3170 assert_eq!(events.len(), 1);
3172 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, .. } } => {
3173 assert!(update_add_htlcs.is_empty());
3174 assert_eq!(update_fail_htlcs.len(), 1);
3175 assert!(update_fulfill_htlcs.is_empty());
3176 assert!(update_fail_malformed_htlcs.is_empty());
3177 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3179 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3180 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3181 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3183 _ => panic!("Unexpected event"),
3187 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3188 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3189 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3190 // commitment transaction anymore.
3191 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3192 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3193 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3194 // technically disallowed and we should probably handle it reasonably.
3195 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3196 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3198 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3199 // commitment_signed (implying it will be in the latest remote commitment transaction).
3200 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3201 // and once they revoke the previous commitment transaction (allowing us to send a new
3202 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3203 let chanmon_cfgs = create_chanmon_cfgs(3);
3204 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3205 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3206 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3208 // Create some initial channels
3209 create_announced_chan_between_nodes(&nodes, 0, 1);
3210 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3212 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3213 // Get the will-be-revoked local txn from nodes[2]
3214 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3215 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3216 // Revoke the old state
3217 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3219 let value = if use_dust {
3220 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3221 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3222 nodes[2].node.per_peer_state.read().unwrap().get(&nodes[1].node.get_our_node_id())
3223 .unwrap().lock().unwrap().channel_by_id.get(&chan_2.2).unwrap().context().holder_dust_limit_satoshis * 1000
3226 let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3227 let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3228 let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3230 nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3231 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3232 check_added_monitors!(nodes[2], 1);
3233 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3234 assert!(updates.update_add_htlcs.is_empty());
3235 assert!(updates.update_fulfill_htlcs.is_empty());
3236 assert!(updates.update_fail_malformed_htlcs.is_empty());
3237 assert_eq!(updates.update_fail_htlcs.len(), 1);
3238 assert!(updates.update_fee.is_none());
3239 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3240 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3241 // Drop the last RAA from 3 -> 2
3243 nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3244 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3245 check_added_monitors!(nodes[2], 1);
3246 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3247 assert!(updates.update_add_htlcs.is_empty());
3248 assert!(updates.update_fulfill_htlcs.is_empty());
3249 assert!(updates.update_fail_malformed_htlcs.is_empty());
3250 assert_eq!(updates.update_fail_htlcs.len(), 1);
3251 assert!(updates.update_fee.is_none());
3252 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3253 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3254 check_added_monitors!(nodes[1], 1);
3255 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3256 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3257 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3258 check_added_monitors!(nodes[2], 1);
3260 nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3261 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3262 check_added_monitors!(nodes[2], 1);
3263 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3264 assert!(updates.update_add_htlcs.is_empty());
3265 assert!(updates.update_fulfill_htlcs.is_empty());
3266 assert!(updates.update_fail_malformed_htlcs.is_empty());
3267 assert_eq!(updates.update_fail_htlcs.len(), 1);
3268 assert!(updates.update_fee.is_none());
3269 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3270 // At this point first_payment_hash has dropped out of the latest two commitment
3271 // transactions that nodes[1] is tracking...
3272 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3273 check_added_monitors!(nodes[1], 1);
3274 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3275 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3276 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3277 check_added_monitors!(nodes[2], 1);
3279 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3280 // on nodes[2]'s RAA.
3281 let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3282 nodes[1].node.send_payment_with_route(&route, fourth_payment_hash,
3283 RecipientOnionFields::secret_only(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3284 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3285 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3286 check_added_monitors!(nodes[1], 0);
3289 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3290 // One monitor for the new revocation preimage, no second on as we won't generate a new
3291 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3292 check_added_monitors!(nodes[1], 1);
3293 let events = nodes[1].node.get_and_clear_pending_events();
3294 assert_eq!(events.len(), 2);
3296 Event::PendingHTLCsForwardable { .. } => { },
3297 _ => panic!("Unexpected event"),
3300 Event::HTLCHandlingFailed { .. } => { },
3301 _ => panic!("Unexpected event"),
3303 // Deliberately don't process the pending fail-back so they all fail back at once after
3304 // block connection just like the !deliver_bs_raa case
3307 let mut failed_htlcs = HashSet::new();
3308 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3310 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3311 check_added_monitors!(nodes[1], 1);
3312 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3314 let events = nodes[1].node.get_and_clear_pending_events();
3315 assert_eq!(events.len(), if deliver_bs_raa { 3 + nodes.len() - 1 } else { 4 + nodes.len() });
3317 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3318 _ => panic!("Unexepected event"),
3321 Event::PaymentPathFailed { ref payment_hash, .. } => {
3322 assert_eq!(*payment_hash, fourth_payment_hash);
3324 _ => panic!("Unexpected event"),
3327 Event::PaymentFailed { ref payment_hash, .. } => {
3328 assert_eq!(*payment_hash, fourth_payment_hash);
3330 _ => panic!("Unexpected event"),
3333 nodes[1].node.process_pending_htlc_forwards();
3334 check_added_monitors!(nodes[1], 1);
3336 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
3337 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3340 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3341 match nodes_2_event {
3342 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, .. } } => {
3343 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3344 assert_eq!(update_add_htlcs.len(), 1);
3345 assert!(update_fulfill_htlcs.is_empty());
3346 assert!(update_fail_htlcs.is_empty());
3347 assert!(update_fail_malformed_htlcs.is_empty());
3349 _ => panic!("Unexpected event"),
3353 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3354 match nodes_2_event {
3355 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3356 assert_eq!(channel_id, chan_2.2);
3357 assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3359 _ => panic!("Unexpected event"),
3362 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
3363 match nodes_0_event {
3364 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, .. } } => {
3365 assert!(update_add_htlcs.is_empty());
3366 assert_eq!(update_fail_htlcs.len(), 3);
3367 assert!(update_fulfill_htlcs.is_empty());
3368 assert!(update_fail_malformed_htlcs.is_empty());
3369 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3371 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3372 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3373 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3375 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3377 let events = nodes[0].node.get_and_clear_pending_events();
3378 assert_eq!(events.len(), 6);
3380 Event::PaymentPathFailed { ref payment_hash, ref failure, .. } => {
3381 assert!(failed_htlcs.insert(payment_hash.0));
3382 // If we delivered B's RAA we got an unknown preimage error, not something
3383 // that we should update our routing table for.
3384 if !deliver_bs_raa {
3385 if let PathFailure::OnPath { network_update: Some(_) } = failure { } else { panic!("Unexpected path failure") }
3388 _ => panic!("Unexpected event"),
3391 Event::PaymentFailed { ref payment_hash, .. } => {
3392 assert_eq!(*payment_hash, first_payment_hash);
3394 _ => panic!("Unexpected event"),
3397 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3398 assert!(failed_htlcs.insert(payment_hash.0));
3400 _ => panic!("Unexpected event"),
3403 Event::PaymentFailed { ref payment_hash, .. } => {
3404 assert_eq!(*payment_hash, second_payment_hash);
3406 _ => panic!("Unexpected event"),
3409 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3410 assert!(failed_htlcs.insert(payment_hash.0));
3412 _ => panic!("Unexpected event"),
3415 Event::PaymentFailed { ref payment_hash, .. } => {
3416 assert_eq!(*payment_hash, third_payment_hash);
3418 _ => panic!("Unexpected event"),
3421 _ => panic!("Unexpected event"),
3424 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
3426 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3427 _ => panic!("Unexpected event"),
3430 assert!(failed_htlcs.contains(&first_payment_hash.0));
3431 assert!(failed_htlcs.contains(&second_payment_hash.0));
3432 assert!(failed_htlcs.contains(&third_payment_hash.0));
3436 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3437 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3438 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3439 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3440 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3444 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3445 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3446 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3447 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3448 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3452 fn fail_backward_pending_htlc_upon_channel_failure() {
3453 let chanmon_cfgs = create_chanmon_cfgs(2);
3454 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3455 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3456 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3457 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
3459 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3461 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3462 nodes[0].node.send_payment_with_route(&route, payment_hash, RecipientOnionFields::secret_only(payment_secret),
3463 PaymentId(payment_hash.0)).unwrap();
3464 check_added_monitors!(nodes[0], 1);
3466 let payment_event = {
3467 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3468 assert_eq!(events.len(), 1);
3469 SendEvent::from_event(events.remove(0))
3471 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3472 assert_eq!(payment_event.msgs.len(), 1);
3475 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3476 let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3478 nodes[0].node.send_payment_with_route(&route, failed_payment_hash,
3479 RecipientOnionFields::secret_only(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3480 check_added_monitors!(nodes[0], 0);
3482 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3485 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3487 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3489 let secp_ctx = Secp256k1::new();
3490 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3491 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3492 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(
3493 &route.paths[0], 50_000, RecipientOnionFields::secret_only(payment_secret), current_height, &None).unwrap();
3494 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3495 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
3497 // Send a 0-msat update_add_htlc to fail the channel.
3498 let update_add_htlc = msgs::UpdateAddHTLC {
3504 onion_routing_packet,
3505 skimmed_fee_msat: None,
3507 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3509 let events = nodes[0].node.get_and_clear_pending_events();
3510 assert_eq!(events.len(), 3);
3511 // Check that Alice fails backward the pending HTLC from the second payment.
3513 Event::PaymentPathFailed { payment_hash, .. } => {
3514 assert_eq!(payment_hash, failed_payment_hash);
3516 _ => panic!("Unexpected event"),
3519 Event::PaymentFailed { payment_hash, .. } => {
3520 assert_eq!(payment_hash, failed_payment_hash);
3522 _ => panic!("Unexpected event"),
3525 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3526 assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3528 _ => panic!("Unexpected event {:?}", events[1]),
3530 check_closed_broadcast!(nodes[0], true);
3531 check_added_monitors!(nodes[0], 1);
3535 fn test_htlc_ignore_latest_remote_commitment() {
3536 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3537 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3538 let chanmon_cfgs = create_chanmon_cfgs(2);
3539 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3540 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3541 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3542 if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3543 // We rely on the ability to connect a block redundantly, which isn't allowed via
3544 // `chain::Listen`, so we never run the test if we randomly get assigned that
3548 create_announced_chan_between_nodes(&nodes, 0, 1);
3550 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3551 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3552 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3553 check_closed_broadcast!(nodes[0], true);
3554 check_added_monitors!(nodes[0], 1);
3555 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
3557 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3558 assert_eq!(node_txn.len(), 3);
3559 assert_eq!(node_txn[0].txid(), node_txn[1].txid());
3561 let block = create_dummy_block(nodes[1].best_block_hash(), 42, vec![node_txn[0].clone(), node_txn[1].clone()]);
3562 connect_block(&nodes[1], &block);
3563 check_closed_broadcast!(nodes[1], true);
3564 check_added_monitors!(nodes[1], 1);
3565 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
3567 // Duplicate the connect_block call since this may happen due to other listeners
3568 // registering new transactions
3569 connect_block(&nodes[1], &block);
3573 fn test_force_close_fail_back() {
3574 // Check which HTLCs are failed-backwards on channel force-closure
3575 let chanmon_cfgs = create_chanmon_cfgs(3);
3576 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3577 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3578 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3579 create_announced_chan_between_nodes(&nodes, 0, 1);
3580 create_announced_chan_between_nodes(&nodes, 1, 2);
3582 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3584 let mut payment_event = {
3585 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
3586 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3587 check_added_monitors!(nodes[0], 1);
3589 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3590 assert_eq!(events.len(), 1);
3591 SendEvent::from_event(events.remove(0))
3594 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3595 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3597 expect_pending_htlcs_forwardable!(nodes[1]);
3599 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3600 assert_eq!(events_2.len(), 1);
3601 payment_event = SendEvent::from_event(events_2.remove(0));
3602 assert_eq!(payment_event.msgs.len(), 1);
3604 check_added_monitors!(nodes[1], 1);
3605 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3606 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3607 check_added_monitors!(nodes[2], 1);
3608 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3610 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3611 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3612 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3614 nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3615 check_closed_broadcast!(nodes[2], true);
3616 check_added_monitors!(nodes[2], 1);
3617 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
3619 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3620 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3621 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3622 // back to nodes[1] upon timeout otherwise.
3623 assert_eq!(node_txn.len(), 1);
3627 mine_transaction(&nodes[1], &tx);
3629 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3630 check_closed_broadcast!(nodes[1], true);
3631 check_added_monitors!(nodes[1], 1);
3632 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
3634 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3636 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3637 .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);
3639 mine_transaction(&nodes[2], &tx);
3640 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3641 assert_eq!(node_txn.len(), 1);
3642 assert_eq!(node_txn[0].input.len(), 1);
3643 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3644 assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3645 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3647 check_spends!(node_txn[0], tx);
3651 fn test_dup_events_on_peer_disconnect() {
3652 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3653 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3654 // as we used to generate the event immediately upon receipt of the payment preimage in the
3655 // update_fulfill_htlc message.
3657 let chanmon_cfgs = create_chanmon_cfgs(2);
3658 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3659 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3660 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3661 create_announced_chan_between_nodes(&nodes, 0, 1);
3663 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3665 nodes[1].node.claim_funds(payment_preimage);
3666 expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3667 check_added_monitors!(nodes[1], 1);
3668 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3669 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3670 expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
3672 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3673 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3675 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3676 reconnect_args.pending_htlc_claims.0 = 1;
3677 reconnect_nodes(reconnect_args);
3678 expect_payment_path_successful!(nodes[0]);
3682 fn test_peer_disconnected_before_funding_broadcasted() {
3683 // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3684 // before the funding transaction has been broadcasted.
3685 let chanmon_cfgs = create_chanmon_cfgs(2);
3686 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3687 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3688 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3690 // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3691 // broadcasted, even though it's created by `nodes[0]`.
3692 let expected_temporary_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
3693 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3694 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
3695 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3696 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
3698 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3699 assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3701 assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3703 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3704 assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3706 // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3707 // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3710 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3713 // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3714 // disconnected before the funding transaction was broadcasted.
3715 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3716 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3718 check_closed_event!(&nodes[0], 1, ClosureReason::DisconnectedPeer, false
3719 , [nodes[1].node.get_our_node_id()], 1000000);
3720 check_closed_event!(&nodes[1], 1, ClosureReason::DisconnectedPeer, false
3721 , [nodes[0].node.get_our_node_id()], 1000000);
3725 fn test_simple_peer_disconnect() {
3726 // Test that we can reconnect when there are no lost messages
3727 let chanmon_cfgs = create_chanmon_cfgs(3);
3728 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3729 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3730 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3731 create_announced_chan_between_nodes(&nodes, 0, 1);
3732 create_announced_chan_between_nodes(&nodes, 1, 2);
3734 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3735 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3736 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3737 reconnect_args.send_channel_ready = (true, true);
3738 reconnect_nodes(reconnect_args);
3740 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3741 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3742 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3743 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
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 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3749 let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3750 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3751 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3752 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3754 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3755 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3757 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3758 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3760 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3761 reconnect_args.pending_cell_htlc_fails.0 = 1;
3762 reconnect_args.pending_cell_htlc_claims.0 = 1;
3763 reconnect_nodes(reconnect_args);
3765 let events = nodes[0].node.get_and_clear_pending_events();
3766 assert_eq!(events.len(), 4);
3768 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3769 assert_eq!(payment_preimage, payment_preimage_3);
3770 assert_eq!(payment_hash, payment_hash_3);
3772 _ => panic!("Unexpected event"),
3775 Event::PaymentPathSuccessful { .. } => {},
3776 _ => panic!("Unexpected event"),
3779 Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3780 assert_eq!(payment_hash, payment_hash_5);
3781 assert!(payment_failed_permanently);
3783 _ => panic!("Unexpected event"),
3786 Event::PaymentFailed { payment_hash, .. } => {
3787 assert_eq!(payment_hash, payment_hash_5);
3789 _ => panic!("Unexpected event"),
3792 check_added_monitors(&nodes[0], 1);
3794 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3795 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3798 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3799 // Test that we can reconnect when in-flight HTLC updates get dropped
3800 let chanmon_cfgs = create_chanmon_cfgs(2);
3801 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3802 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3803 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3805 let mut as_channel_ready = None;
3806 let channel_id = if messages_delivered == 0 {
3807 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3808 as_channel_ready = Some(channel_ready);
3809 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3810 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3811 // it before the channel_reestablish message.
3814 create_announced_chan_between_nodes(&nodes, 0, 1).2
3817 let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3819 let payment_event = {
3820 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
3821 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3822 check_added_monitors!(nodes[0], 1);
3824 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3825 assert_eq!(events.len(), 1);
3826 SendEvent::from_event(events.remove(0))
3828 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3830 if messages_delivered < 2 {
3831 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3833 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3834 if messages_delivered >= 3 {
3835 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3836 check_added_monitors!(nodes[1], 1);
3837 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3839 if messages_delivered >= 4 {
3840 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3841 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3842 check_added_monitors!(nodes[0], 1);
3844 if messages_delivered >= 5 {
3845 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3846 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3847 // No commitment_signed so get_event_msg's assert(len == 1) passes
3848 check_added_monitors!(nodes[0], 1);
3850 if messages_delivered >= 6 {
3851 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3852 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3853 check_added_monitors!(nodes[1], 1);
3860 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3861 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3862 if messages_delivered < 3 {
3863 if simulate_broken_lnd {
3864 // lnd has a long-standing bug where they send a channel_ready prior to a
3865 // channel_reestablish if you reconnect prior to channel_ready time.
3867 // Here we simulate that behavior, delivering a channel_ready immediately on
3868 // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3869 // in `reconnect_nodes` but we currently don't fail based on that.
3871 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3872 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3874 // Even if the channel_ready messages get exchanged, as long as nothing further was
3875 // received on either side, both sides will need to resend them.
3876 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3877 reconnect_args.send_channel_ready = (true, true);
3878 reconnect_args.pending_htlc_adds.1 = 1;
3879 reconnect_nodes(reconnect_args);
3880 } else if messages_delivered == 3 {
3881 // nodes[0] still wants its RAA + commitment_signed
3882 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3883 reconnect_args.pending_htlc_adds.0 = -1;
3884 reconnect_args.pending_raa.0 = true;
3885 reconnect_nodes(reconnect_args);
3886 } else if messages_delivered == 4 {
3887 // nodes[0] still wants its commitment_signed
3888 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3889 reconnect_args.pending_htlc_adds.0 = -1;
3890 reconnect_nodes(reconnect_args);
3891 } else if messages_delivered == 5 {
3892 // nodes[1] still wants its final RAA
3893 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3894 reconnect_args.pending_raa.1 = true;
3895 reconnect_nodes(reconnect_args);
3896 } else if messages_delivered == 6 {
3897 // Everything was delivered...
3898 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3901 let events_1 = nodes[1].node.get_and_clear_pending_events();
3902 if messages_delivered == 0 {
3903 assert_eq!(events_1.len(), 2);
3905 Event::ChannelReady { .. } => { },
3906 _ => panic!("Unexpected event"),
3909 Event::PendingHTLCsForwardable { .. } => { },
3910 _ => panic!("Unexpected event"),
3913 assert_eq!(events_1.len(), 1);
3915 Event::PendingHTLCsForwardable { .. } => { },
3916 _ => panic!("Unexpected event"),
3920 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3921 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3922 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3924 nodes[1].node.process_pending_htlc_forwards();
3926 let events_2 = nodes[1].node.get_and_clear_pending_events();
3927 assert_eq!(events_2.len(), 1);
3929 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
3930 assert_eq!(payment_hash_1, *payment_hash);
3931 assert_eq!(amount_msat, 1_000_000);
3932 assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3933 assert_eq!(via_channel_id, Some(channel_id));
3935 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3936 assert!(payment_preimage.is_none());
3937 assert_eq!(payment_secret_1, *payment_secret);
3939 _ => panic!("expected PaymentPurpose::InvoicePayment")
3942 _ => panic!("Unexpected event"),
3945 nodes[1].node.claim_funds(payment_preimage_1);
3946 check_added_monitors!(nodes[1], 1);
3947 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3949 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3950 assert_eq!(events_3.len(), 1);
3951 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3952 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3953 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3954 assert!(updates.update_add_htlcs.is_empty());
3955 assert!(updates.update_fail_htlcs.is_empty());
3956 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3957 assert!(updates.update_fail_malformed_htlcs.is_empty());
3958 assert!(updates.update_fee.is_none());
3959 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3961 _ => panic!("Unexpected event"),
3964 if messages_delivered >= 1 {
3965 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3967 let events_4 = nodes[0].node.get_and_clear_pending_events();
3968 assert_eq!(events_4.len(), 1);
3970 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3971 assert_eq!(payment_preimage_1, *payment_preimage);
3972 assert_eq!(payment_hash_1, *payment_hash);
3974 _ => panic!("Unexpected event"),
3977 if messages_delivered >= 2 {
3978 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3979 check_added_monitors!(nodes[0], 1);
3980 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3982 if messages_delivered >= 3 {
3983 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3984 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3985 check_added_monitors!(nodes[1], 1);
3987 if messages_delivered >= 4 {
3988 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3989 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3990 // No commitment_signed so get_event_msg's assert(len == 1) passes
3991 check_added_monitors!(nodes[1], 1);
3993 if messages_delivered >= 5 {
3994 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3995 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3996 check_added_monitors!(nodes[0], 1);
4003 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4004 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4005 if messages_delivered < 2 {
4006 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4007 reconnect_args.pending_htlc_claims.0 = 1;
4008 reconnect_nodes(reconnect_args);
4009 if messages_delivered < 1 {
4010 expect_payment_sent!(nodes[0], payment_preimage_1);
4012 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4014 } else if messages_delivered == 2 {
4015 // nodes[0] still wants its RAA + commitment_signed
4016 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4017 reconnect_args.pending_htlc_adds.1 = -1;
4018 reconnect_args.pending_raa.1 = true;
4019 reconnect_nodes(reconnect_args);
4020 } else if messages_delivered == 3 {
4021 // nodes[0] still wants its commitment_signed
4022 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4023 reconnect_args.pending_htlc_adds.1 = -1;
4024 reconnect_nodes(reconnect_args);
4025 } else if messages_delivered == 4 {
4026 // nodes[1] still wants its final RAA
4027 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4028 reconnect_args.pending_raa.0 = true;
4029 reconnect_nodes(reconnect_args);
4030 } else if messages_delivered == 5 {
4031 // Everything was delivered...
4032 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
4035 if messages_delivered == 1 || messages_delivered == 2 {
4036 expect_payment_path_successful!(nodes[0]);
4038 if messages_delivered <= 5 {
4039 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4040 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4042 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
4044 if messages_delivered > 2 {
4045 expect_payment_path_successful!(nodes[0]);
4048 // Channel should still work fine...
4049 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4050 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
4051 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4055 fn test_drop_messages_peer_disconnect_a() {
4056 do_test_drop_messages_peer_disconnect(0, true);
4057 do_test_drop_messages_peer_disconnect(0, false);
4058 do_test_drop_messages_peer_disconnect(1, false);
4059 do_test_drop_messages_peer_disconnect(2, false);
4063 fn test_drop_messages_peer_disconnect_b() {
4064 do_test_drop_messages_peer_disconnect(3, false);
4065 do_test_drop_messages_peer_disconnect(4, false);
4066 do_test_drop_messages_peer_disconnect(5, false);
4067 do_test_drop_messages_peer_disconnect(6, false);
4071 fn test_channel_ready_without_best_block_updated() {
4072 // Previously, if we were offline when a funding transaction was locked in, and then we came
4073 // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
4074 // generate a channel_ready until a later best_block_updated. This tests that we generate the
4075 // channel_ready immediately instead.
4076 let chanmon_cfgs = create_chanmon_cfgs(2);
4077 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4078 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4079 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4080 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
4082 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
4084 let conf_height = nodes[0].best_block_info().1 + 1;
4085 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4086 let block_txn = [funding_tx];
4087 let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
4088 let conf_block_header = nodes[0].get_block_header(conf_height);
4089 nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
4091 // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4092 let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4093 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4097 fn test_drop_messages_peer_disconnect_dual_htlc() {
4098 // Test that we can handle reconnecting when both sides of a channel have pending
4099 // commitment_updates when we disconnect.
4100 let chanmon_cfgs = create_chanmon_cfgs(2);
4101 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4102 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4103 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4104 create_announced_chan_between_nodes(&nodes, 0, 1);
4106 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
4108 // Now try to send a second payment which will fail to send
4109 let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4110 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
4111 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
4112 check_added_monitors!(nodes[0], 1);
4114 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4115 assert_eq!(events_1.len(), 1);
4117 MessageSendEvent::UpdateHTLCs { .. } => {},
4118 _ => panic!("Unexpected event"),
4121 nodes[1].node.claim_funds(payment_preimage_1);
4122 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4123 check_added_monitors!(nodes[1], 1);
4125 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4126 assert_eq!(events_2.len(), 1);
4128 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 } } => {
4129 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4130 assert!(update_add_htlcs.is_empty());
4131 assert_eq!(update_fulfill_htlcs.len(), 1);
4132 assert!(update_fail_htlcs.is_empty());
4133 assert!(update_fail_malformed_htlcs.is_empty());
4134 assert!(update_fee.is_none());
4136 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4137 let events_3 = nodes[0].node.get_and_clear_pending_events();
4138 assert_eq!(events_3.len(), 1);
4140 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4141 assert_eq!(*payment_preimage, payment_preimage_1);
4142 assert_eq!(*payment_hash, payment_hash_1);
4144 _ => panic!("Unexpected event"),
4147 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4148 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4149 // No commitment_signed so get_event_msg's assert(len == 1) passes
4150 check_added_monitors!(nodes[0], 1);
4152 _ => panic!("Unexpected event"),
4155 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4156 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4158 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
4159 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
4161 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4162 assert_eq!(reestablish_1.len(), 1);
4163 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
4164 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
4166 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4167 assert_eq!(reestablish_2.len(), 1);
4169 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4170 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4171 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4172 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4174 assert!(as_resp.0.is_none());
4175 assert!(bs_resp.0.is_none());
4177 assert!(bs_resp.1.is_none());
4178 assert!(bs_resp.2.is_none());
4180 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4182 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4183 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4184 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4185 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4186 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4187 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4188 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4189 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4190 // No commitment_signed so get_event_msg's assert(len == 1) passes
4191 check_added_monitors!(nodes[1], 1);
4193 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4194 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4195 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4196 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4197 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4198 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4199 assert!(bs_second_commitment_signed.update_fee.is_none());
4200 check_added_monitors!(nodes[1], 1);
4202 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4203 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4204 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4205 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4206 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4207 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4208 assert!(as_commitment_signed.update_fee.is_none());
4209 check_added_monitors!(nodes[0], 1);
4211 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4212 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4213 // No commitment_signed so get_event_msg's assert(len == 1) passes
4214 check_added_monitors!(nodes[0], 1);
4216 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4217 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4218 // No commitment_signed so get_event_msg's assert(len == 1) passes
4219 check_added_monitors!(nodes[1], 1);
4221 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4222 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4223 check_added_monitors!(nodes[1], 1);
4225 expect_pending_htlcs_forwardable!(nodes[1]);
4227 let events_5 = nodes[1].node.get_and_clear_pending_events();
4228 assert_eq!(events_5.len(), 1);
4230 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4231 assert_eq!(payment_hash_2, *payment_hash);
4233 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4234 assert!(payment_preimage.is_none());
4235 assert_eq!(payment_secret_2, *payment_secret);
4237 _ => panic!("expected PaymentPurpose::InvoicePayment")
4240 _ => panic!("Unexpected event"),
4243 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4244 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4245 check_added_monitors!(nodes[0], 1);
4247 expect_payment_path_successful!(nodes[0]);
4248 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4251 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4252 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4253 // to avoid our counterparty failing the channel.
4254 let chanmon_cfgs = create_chanmon_cfgs(2);
4255 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4256 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4257 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4259 create_announced_chan_between_nodes(&nodes, 0, 1);
4261 let our_payment_hash = if send_partial_mpp {
4262 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4263 // Use the utility function send_payment_along_path to send the payment with MPP data which
4264 // indicates there are more HTLCs coming.
4265 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.
4266 let payment_id = PaymentId([42; 32]);
4267 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
4268 RecipientOnionFields::secret_only(payment_secret), payment_id, &route).unwrap();
4269 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
4270 RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id,
4271 &None, session_privs[0]).unwrap();
4272 check_added_monitors!(nodes[0], 1);
4273 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4274 assert_eq!(events.len(), 1);
4275 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4276 // hop should *not* yet generate any PaymentClaimable event(s).
4277 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4280 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4283 let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
4284 connect_block(&nodes[0], &block);
4285 connect_block(&nodes[1], &block);
4286 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4287 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4288 block.header.prev_blockhash = block.block_hash();
4289 connect_block(&nodes[0], &block);
4290 connect_block(&nodes[1], &block);
4293 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4295 check_added_monitors!(nodes[1], 1);
4296 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4297 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4298 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4299 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4300 assert!(htlc_timeout_updates.update_fee.is_none());
4302 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4303 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4304 // 100_000 msat as u64, followed by the height at which we failed back above
4305 let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4306 expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4307 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4311 fn test_htlc_timeout() {
4312 do_test_htlc_timeout(true);
4313 do_test_htlc_timeout(false);
4316 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4317 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4318 let chanmon_cfgs = create_chanmon_cfgs(3);
4319 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4320 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4321 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4322 create_announced_chan_between_nodes(&nodes, 0, 1);
4323 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4325 // Make sure all nodes are at the same starting height
4326 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4327 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4328 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4330 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4331 let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4332 nodes[1].node.send_payment_with_route(&route, first_payment_hash,
4333 RecipientOnionFields::secret_only(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4334 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4335 check_added_monitors!(nodes[1], 1);
4337 // Now attempt to route a second payment, which should be placed in the holding cell
4338 let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4339 let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4340 sending_node.node.send_payment_with_route(&route, second_payment_hash,
4341 RecipientOnionFields::secret_only(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4343 check_added_monitors!(nodes[0], 1);
4344 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4345 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4346 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4347 expect_pending_htlcs_forwardable!(nodes[1]);
4349 check_added_monitors!(nodes[1], 0);
4351 connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4352 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4353 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4354 connect_blocks(&nodes[1], 1);
4357 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 }]);
4358 check_added_monitors!(nodes[1], 1);
4359 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4360 assert_eq!(fail_commit.len(), 1);
4361 match fail_commit[0] {
4362 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4363 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4364 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4366 _ => unreachable!(),
4368 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4370 expect_payment_failed!(nodes[1], second_payment_hash, false);
4375 fn test_holding_cell_htlc_add_timeouts() {
4376 do_test_holding_cell_htlc_add_timeouts(false);
4377 do_test_holding_cell_htlc_add_timeouts(true);
4380 macro_rules! check_spendable_outputs {
4381 ($node: expr, $keysinterface: expr) => {
4383 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4384 let mut txn = Vec::new();
4385 let mut all_outputs = Vec::new();
4386 let secp_ctx = Secp256k1::new();
4387 for event in events.drain(..) {
4389 Event::SpendableOutputs { mut outputs, channel_id: _ } => {
4390 for outp in outputs.drain(..) {
4391 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());
4392 all_outputs.push(outp);
4395 _ => panic!("Unexpected event"),
4398 if all_outputs.len() > 1 {
4399 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) {
4409 fn test_claim_sizeable_push_msat() {
4410 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4411 let chanmon_cfgs = create_chanmon_cfgs(2);
4412 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4413 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4414 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4416 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4417 nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4418 check_closed_broadcast!(nodes[1], true);
4419 check_added_monitors!(nodes[1], 1);
4420 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[0].node.get_our_node_id()], 100000);
4421 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4422 assert_eq!(node_txn.len(), 1);
4423 check_spends!(node_txn[0], chan.3);
4424 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
4426 mine_transaction(&nodes[1], &node_txn[0]);
4427 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4429 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4430 assert_eq!(spend_txn.len(), 1);
4431 assert_eq!(spend_txn[0].input.len(), 1);
4432 check_spends!(spend_txn[0], node_txn[0]);
4433 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4437 fn test_claim_on_remote_sizeable_push_msat() {
4438 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4439 // to_remote output is encumbered by a P2WPKH
4440 let chanmon_cfgs = create_chanmon_cfgs(2);
4441 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4442 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4443 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4445 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4446 nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4447 check_closed_broadcast!(nodes[0], true);
4448 check_added_monitors!(nodes[0], 1);
4449 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
4451 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4452 assert_eq!(node_txn.len(), 1);
4453 check_spends!(node_txn[0], chan.3);
4454 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
4456 mine_transaction(&nodes[1], &node_txn[0]);
4457 check_closed_broadcast!(nodes[1], true);
4458 check_added_monitors!(nodes[1], 1);
4459 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4460 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4462 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4463 assert_eq!(spend_txn.len(), 1);
4464 check_spends!(spend_txn[0], node_txn[0]);
4468 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4469 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4470 // to_remote output is encumbered by a P2WPKH
4472 let chanmon_cfgs = create_chanmon_cfgs(2);
4473 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4474 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4475 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4477 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4478 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4479 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4480 assert_eq!(revoked_local_txn[0].input.len(), 1);
4481 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4483 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4484 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4485 check_closed_broadcast!(nodes[1], true);
4486 check_added_monitors!(nodes[1], 1);
4487 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4489 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4490 mine_transaction(&nodes[1], &node_txn[0]);
4491 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4493 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4494 assert_eq!(spend_txn.len(), 3);
4495 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4496 check_spends!(spend_txn[1], node_txn[0]);
4497 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4501 fn test_static_spendable_outputs_preimage_tx() {
4502 let chanmon_cfgs = create_chanmon_cfgs(2);
4503 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4504 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4505 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4507 // Create some initial channels
4508 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4510 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4512 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4513 assert_eq!(commitment_tx[0].input.len(), 1);
4514 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4516 // Settle A's commitment tx on B's chain
4517 nodes[1].node.claim_funds(payment_preimage);
4518 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4519 check_added_monitors!(nodes[1], 1);
4520 mine_transaction(&nodes[1], &commitment_tx[0]);
4521 check_added_monitors!(nodes[1], 1);
4522 let events = nodes[1].node.get_and_clear_pending_msg_events();
4524 MessageSendEvent::UpdateHTLCs { .. } => {},
4525 _ => panic!("Unexpected event"),
4528 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4529 _ => panic!("Unexepected event"),
4532 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4533 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4534 assert_eq!(node_txn.len(), 1);
4535 check_spends!(node_txn[0], commitment_tx[0]);
4536 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4538 mine_transaction(&nodes[1], &node_txn[0]);
4539 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4540 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4542 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4543 assert_eq!(spend_txn.len(), 1);
4544 check_spends!(spend_txn[0], node_txn[0]);
4548 fn test_static_spendable_outputs_timeout_tx() {
4549 let chanmon_cfgs = create_chanmon_cfgs(2);
4550 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4551 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4552 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4554 // Create some initial channels
4555 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4557 // Rebalance the network a bit by relaying one payment through all the channels ...
4558 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4560 let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4562 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4563 assert_eq!(commitment_tx[0].input.len(), 1);
4564 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4566 // Settle A's commitment tx on B' chain
4567 mine_transaction(&nodes[1], &commitment_tx[0]);
4568 check_added_monitors!(nodes[1], 1);
4569 let events = nodes[1].node.get_and_clear_pending_msg_events();
4571 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4572 _ => panic!("Unexpected event"),
4574 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4576 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4577 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4578 assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4579 check_spends!(node_txn[0], commitment_tx[0].clone());
4580 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4582 mine_transaction(&nodes[1], &node_txn[0]);
4583 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4584 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4585 expect_payment_failed!(nodes[1], our_payment_hash, false);
4587 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4588 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4589 check_spends!(spend_txn[0], commitment_tx[0]);
4590 check_spends!(spend_txn[1], node_txn[0]);
4591 check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4595 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4596 let chanmon_cfgs = create_chanmon_cfgs(2);
4597 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4598 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4599 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4601 // Create some initial channels
4602 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4604 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4605 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4606 assert_eq!(revoked_local_txn[0].input.len(), 1);
4607 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4609 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4611 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4612 check_closed_broadcast!(nodes[1], true);
4613 check_added_monitors!(nodes[1], 1);
4614 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4616 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4617 assert_eq!(node_txn.len(), 1);
4618 assert_eq!(node_txn[0].input.len(), 2);
4619 check_spends!(node_txn[0], revoked_local_txn[0]);
4621 mine_transaction(&nodes[1], &node_txn[0]);
4622 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4624 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4625 assert_eq!(spend_txn.len(), 1);
4626 check_spends!(spend_txn[0], node_txn[0]);
4630 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4631 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4632 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4633 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4634 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4635 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4637 // Create some initial channels
4638 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4640 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4641 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4642 assert_eq!(revoked_local_txn[0].input.len(), 1);
4643 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4645 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4647 // A will generate HTLC-Timeout from revoked commitment tx
4648 mine_transaction(&nodes[0], &revoked_local_txn[0]);
4649 check_closed_broadcast!(nodes[0], true);
4650 check_added_monitors!(nodes[0], 1);
4651 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4652 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4654 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4655 assert_eq!(revoked_htlc_txn.len(), 1);
4656 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4657 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4658 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4659 assert_ne!(revoked_htlc_txn[0].lock_time.0, 0); // HTLC-Timeout
4661 // B will generate justice tx from A's revoked commitment/HTLC tx
4662 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4663 check_closed_broadcast!(nodes[1], true);
4664 check_added_monitors!(nodes[1], 1);
4665 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4667 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4668 assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4669 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4670 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4671 // transactions next...
4672 assert_eq!(node_txn[0].input.len(), 3);
4673 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4675 assert_eq!(node_txn[1].input.len(), 2);
4676 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4677 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4678 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4680 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4681 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4684 mine_transaction(&nodes[1], &node_txn[1]);
4685 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4687 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4688 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4689 assert_eq!(spend_txn.len(), 1);
4690 assert_eq!(spend_txn[0].input.len(), 1);
4691 check_spends!(spend_txn[0], node_txn[1]);
4695 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4696 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4697 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4698 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4699 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4700 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4702 // Create some initial channels
4703 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4705 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4706 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4707 assert_eq!(revoked_local_txn[0].input.len(), 1);
4708 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4710 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4711 assert_eq!(revoked_local_txn[0].output.len(), 2);
4713 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4715 // B will generate HTLC-Success from revoked commitment tx
4716 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4717 check_closed_broadcast!(nodes[1], true);
4718 check_added_monitors!(nodes[1], 1);
4719 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4720 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4722 assert_eq!(revoked_htlc_txn.len(), 1);
4723 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4724 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4725 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4727 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4728 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4729 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4731 // A will generate justice tx from B's revoked commitment/HTLC tx
4732 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4733 check_closed_broadcast!(nodes[0], true);
4734 check_added_monitors!(nodes[0], 1);
4735 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4737 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4738 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4740 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4741 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4742 // transactions next...
4743 assert_eq!(node_txn[0].input.len(), 2);
4744 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4745 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4746 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4748 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4749 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4752 assert_eq!(node_txn[1].input.len(), 1);
4753 check_spends!(node_txn[1], revoked_htlc_txn[0]);
4755 mine_transaction(&nodes[0], &node_txn[1]);
4756 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4758 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4759 // didn't try to generate any new transactions.
4761 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4762 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4763 assert_eq!(spend_txn.len(), 3);
4764 assert_eq!(spend_txn[0].input.len(), 1);
4765 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4766 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4767 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4768 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4772 fn test_onchain_to_onchain_claim() {
4773 // Test that in case of channel closure, we detect the state of output and claim HTLC
4774 // on downstream peer's remote commitment tx.
4775 // First, have C claim an HTLC against its own latest commitment transaction.
4776 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4778 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4781 let chanmon_cfgs = create_chanmon_cfgs(3);
4782 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4783 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4784 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4786 // Create some initial channels
4787 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4788 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4790 // Ensure all nodes are at the same height
4791 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4792 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4793 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4794 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4796 // Rebalance the network a bit by relaying one payment through all the channels ...
4797 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4798 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4800 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4801 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4802 check_spends!(commitment_tx[0], chan_2.3);
4803 nodes[2].node.claim_funds(payment_preimage);
4804 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4805 check_added_monitors!(nodes[2], 1);
4806 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4807 assert!(updates.update_add_htlcs.is_empty());
4808 assert!(updates.update_fail_htlcs.is_empty());
4809 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4810 assert!(updates.update_fail_malformed_htlcs.is_empty());
4812 mine_transaction(&nodes[2], &commitment_tx[0]);
4813 check_closed_broadcast!(nodes[2], true);
4814 check_added_monitors!(nodes[2], 1);
4815 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4817 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4818 assert_eq!(c_txn.len(), 1);
4819 check_spends!(c_txn[0], commitment_tx[0]);
4820 assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4821 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4822 assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
4824 // 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
4825 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![commitment_tx[0].clone(), c_txn[0].clone()]));
4826 check_added_monitors!(nodes[1], 1);
4827 let events = nodes[1].node.get_and_clear_pending_events();
4828 assert_eq!(events.len(), 2);
4830 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4831 _ => panic!("Unexpected event"),
4834 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
4835 assert_eq!(fee_earned_msat, Some(1000));
4836 assert_eq!(prev_channel_id, Some(chan_1.2));
4837 assert_eq!(claim_from_onchain_tx, true);
4838 assert_eq!(next_channel_id, Some(chan_2.2));
4839 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
4841 _ => panic!("Unexpected event"),
4843 check_added_monitors!(nodes[1], 1);
4844 let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4845 assert_eq!(msg_events.len(), 3);
4846 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut msg_events);
4847 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut msg_events);
4849 match nodes_2_event {
4850 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
4851 _ => panic!("Unexpected event"),
4854 match nodes_0_event {
4855 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, .. } } => {
4856 assert!(update_add_htlcs.is_empty());
4857 assert!(update_fail_htlcs.is_empty());
4858 assert_eq!(update_fulfill_htlcs.len(), 1);
4859 assert!(update_fail_malformed_htlcs.is_empty());
4860 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4862 _ => panic!("Unexpected event"),
4865 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
4866 match msg_events[0] {
4867 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4868 _ => panic!("Unexpected event"),
4871 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4872 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4873 mine_transaction(&nodes[1], &commitment_tx[0]);
4874 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4875 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4876 // ChannelMonitor: HTLC-Success tx
4877 assert_eq!(b_txn.len(), 1);
4878 check_spends!(b_txn[0], commitment_tx[0]);
4879 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4880 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4881 assert_eq!(b_txn[0].lock_time.0, nodes[1].best_block_info().1); // Success tx
4883 check_closed_broadcast!(nodes[1], true);
4884 check_added_monitors!(nodes[1], 1);
4888 fn test_duplicate_payment_hash_one_failure_one_success() {
4889 // Topology : A --> B --> C --> D
4890 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4891 // Note that because C will refuse to generate two payment secrets for the same payment hash,
4892 // we forward one of the payments onwards to D.
4893 let chanmon_cfgs = create_chanmon_cfgs(4);
4894 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4895 // When this test was written, the default base fee floated based on the HTLC count.
4896 // It is now fixed, so we simply set the fee to the expected value here.
4897 let mut config = test_default_channel_config();
4898 config.channel_config.forwarding_fee_base_msat = 196;
4899 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4900 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4901 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4903 create_announced_chan_between_nodes(&nodes, 0, 1);
4904 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4905 create_announced_chan_between_nodes(&nodes, 2, 3);
4907 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4908 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4909 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4910 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4911 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4913 let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
4915 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
4916 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4917 // script push size limit so that the below script length checks match
4918 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
4919 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV - 40)
4920 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
4921 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000);
4922 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
4924 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4925 assert_eq!(commitment_txn[0].input.len(), 1);
4926 check_spends!(commitment_txn[0], chan_2.3);
4928 mine_transaction(&nodes[1], &commitment_txn[0]);
4929 check_closed_broadcast!(nodes[1], true);
4930 check_added_monitors!(nodes[1], 1);
4931 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
4932 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
4934 let htlc_timeout_tx;
4935 { // Extract one of the two HTLC-Timeout transaction
4936 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4937 // ChannelMonitor: timeout tx * 2-or-3
4938 assert!(node_txn.len() == 2 || node_txn.len() == 3);
4940 check_spends!(node_txn[0], commitment_txn[0]);
4941 assert_eq!(node_txn[0].input.len(), 1);
4942 assert_eq!(node_txn[0].output.len(), 1);
4944 if node_txn.len() > 2 {
4945 check_spends!(node_txn[1], commitment_txn[0]);
4946 assert_eq!(node_txn[1].input.len(), 1);
4947 assert_eq!(node_txn[1].output.len(), 1);
4948 assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4950 check_spends!(node_txn[2], commitment_txn[0]);
4951 assert_eq!(node_txn[2].input.len(), 1);
4952 assert_eq!(node_txn[2].output.len(), 1);
4953 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
4955 check_spends!(node_txn[1], commitment_txn[0]);
4956 assert_eq!(node_txn[1].input.len(), 1);
4957 assert_eq!(node_txn[1].output.len(), 1);
4958 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4961 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4962 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4963 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
4964 // (with value 900 sats) will be claimed in the below `claim_funds` call.
4965 if node_txn.len() > 2 {
4966 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4967 htlc_timeout_tx = if node_txn[2].output[0].value < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
4969 htlc_timeout_tx = if node_txn[0].output[0].value < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
4973 nodes[2].node.claim_funds(our_payment_preimage);
4974 expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
4976 mine_transaction(&nodes[2], &commitment_txn[0]);
4977 check_added_monitors!(nodes[2], 2);
4978 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4979 let events = nodes[2].node.get_and_clear_pending_msg_events();
4981 MessageSendEvent::UpdateHTLCs { .. } => {},
4982 _ => panic!("Unexpected event"),
4985 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4986 _ => panic!("Unexepected event"),
4988 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4989 assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
4990 check_spends!(htlc_success_txn[0], commitment_txn[0]);
4991 check_spends!(htlc_success_txn[1], commitment_txn[0]);
4992 assert_eq!(htlc_success_txn[0].input.len(), 1);
4993 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4994 assert_eq!(htlc_success_txn[1].input.len(), 1);
4995 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4996 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
4997 assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
4999 mine_transaction(&nodes[1], &htlc_timeout_tx);
5000 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5001 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 }]);
5002 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5003 assert!(htlc_updates.update_add_htlcs.is_empty());
5004 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5005 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5006 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5007 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5008 check_added_monitors!(nodes[1], 1);
5010 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5011 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5013 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5015 expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5017 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5018 mine_transaction(&nodes[1], &htlc_success_txn[1]);
5019 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
5020 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5021 assert!(updates.update_add_htlcs.is_empty());
5022 assert!(updates.update_fail_htlcs.is_empty());
5023 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5024 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5025 assert!(updates.update_fail_malformed_htlcs.is_empty());
5026 check_added_monitors!(nodes[1], 1);
5028 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5029 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5030 expect_payment_sent(&nodes[0], our_payment_preimage, None, true, true);
5034 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5035 let chanmon_cfgs = create_chanmon_cfgs(2);
5036 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5037 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5038 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5040 // Create some initial channels
5041 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5043 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
5044 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5045 assert_eq!(local_txn.len(), 1);
5046 assert_eq!(local_txn[0].input.len(), 1);
5047 check_spends!(local_txn[0], chan_1.3);
5049 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5050 nodes[1].node.claim_funds(payment_preimage);
5051 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
5052 check_added_monitors!(nodes[1], 1);
5054 mine_transaction(&nodes[1], &local_txn[0]);
5055 check_added_monitors!(nodes[1], 1);
5056 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
5057 let events = nodes[1].node.get_and_clear_pending_msg_events();
5059 MessageSendEvent::UpdateHTLCs { .. } => {},
5060 _ => panic!("Unexpected event"),
5063 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5064 _ => panic!("Unexepected event"),
5067 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5068 assert_eq!(node_txn.len(), 1);
5069 assert_eq!(node_txn[0].input.len(), 1);
5070 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5071 check_spends!(node_txn[0], local_txn[0]);
5075 mine_transaction(&nodes[1], &node_tx);
5076 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5078 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5079 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5080 assert_eq!(spend_txn.len(), 1);
5081 assert_eq!(spend_txn[0].input.len(), 1);
5082 check_spends!(spend_txn[0], node_tx);
5083 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5086 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5087 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5088 // unrevoked commitment transaction.
5089 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5090 // a remote RAA before they could be failed backwards (and combinations thereof).
5091 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5092 // use the same payment hashes.
5093 // Thus, we use a six-node network:
5098 // And test where C fails back to A/B when D announces its latest commitment transaction
5099 let chanmon_cfgs = create_chanmon_cfgs(6);
5100 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5101 // When this test was written, the default base fee floated based on the HTLC count.
5102 // It is now fixed, so we simply set the fee to the expected value here.
5103 let mut config = test_default_channel_config();
5104 config.channel_config.forwarding_fee_base_msat = 196;
5105 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5106 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5107 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5109 let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2);
5110 let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5111 let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5112 let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
5113 let chan_3_5 = create_announced_chan_between_nodes(&nodes, 3, 5);
5115 // Rebalance and check output sanity...
5116 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5117 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5118 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
5120 let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
5121 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().context().holder_dust_limit_satoshis;
5123 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
5125 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
5126 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5128 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
5130 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
5132 let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5134 let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5135 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5137 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());
5139 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());
5142 let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5144 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5145 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
5148 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
5150 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5151 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());
5153 // Double-check that six of the new HTLC were added
5154 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5155 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5156 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5157 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5159 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5160 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5161 nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5162 nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5163 nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5164 nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5165 check_added_monitors!(nodes[4], 0);
5167 let failed_destinations = vec![
5168 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5169 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5170 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5171 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5173 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5174 check_added_monitors!(nodes[4], 1);
5176 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5177 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5178 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5179 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5180 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5181 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5183 // Fail 3rd below-dust and 7th above-dust HTLCs
5184 nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5185 nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5186 check_added_monitors!(nodes[5], 0);
5188 let failed_destinations_2 = vec![
5189 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5190 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5192 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5193 check_added_monitors!(nodes[5], 1);
5195 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5196 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5197 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5198 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5200 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5202 // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5203 let failed_destinations_3 = vec![
5204 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5205 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5206 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5207 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5208 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5209 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5211 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5212 check_added_monitors!(nodes[3], 1);
5213 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5214 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5215 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5216 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5217 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5218 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5219 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5220 if deliver_last_raa {
5221 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5223 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5226 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5227 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5228 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5229 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5231 // We now broadcast the latest commitment transaction, which *should* result in failures for
5232 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5233 // the non-broadcast above-dust HTLCs.
5235 // Alternatively, we may broadcast the previous commitment transaction, which should only
5236 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5237 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5239 if announce_latest {
5240 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5242 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5244 let events = nodes[2].node.get_and_clear_pending_events();
5245 let close_event = if deliver_last_raa {
5246 assert_eq!(events.len(), 2 + 6);
5247 events.last().clone().unwrap()
5249 assert_eq!(events.len(), 1);
5250 events.last().clone().unwrap()
5253 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5254 _ => panic!("Unexpected event"),
5257 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5258 check_closed_broadcast!(nodes[2], true);
5259 if deliver_last_raa {
5260 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5262 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();
5263 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5265 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5266 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5268 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5271 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5273 check_added_monitors!(nodes[2], 3);
5275 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5276 assert_eq!(cs_msgs.len(), 2);
5277 let mut a_done = false;
5278 for msg in cs_msgs {
5280 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5281 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5282 // should be failed-backwards here.
5283 let target = if *node_id == nodes[0].node.get_our_node_id() {
5284 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5285 for htlc in &updates.update_fail_htlcs {
5286 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 });
5288 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5293 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5294 for htlc in &updates.update_fail_htlcs {
5295 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5297 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5298 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5301 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5302 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5303 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5304 if announce_latest {
5305 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5306 if *node_id == nodes[0].node.get_our_node_id() {
5307 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5310 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5312 _ => panic!("Unexpected event"),
5316 let as_events = nodes[0].node.get_and_clear_pending_events();
5317 assert_eq!(as_events.len(), if announce_latest { 10 } else { 6 });
5318 let mut as_failds = HashSet::new();
5319 let mut as_updates = 0;
5320 for event in as_events.iter() {
5321 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5322 assert!(as_failds.insert(*payment_hash));
5323 if *payment_hash != payment_hash_2 {
5324 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5326 assert!(!payment_failed_permanently);
5328 if let PathFailure::OnPath { network_update: Some(_) } = failure {
5331 } else if let &Event::PaymentFailed { .. } = event {
5332 } else { panic!("Unexpected event"); }
5334 assert!(as_failds.contains(&payment_hash_1));
5335 assert!(as_failds.contains(&payment_hash_2));
5336 if announce_latest {
5337 assert!(as_failds.contains(&payment_hash_3));
5338 assert!(as_failds.contains(&payment_hash_5));
5340 assert!(as_failds.contains(&payment_hash_6));
5342 let bs_events = nodes[1].node.get_and_clear_pending_events();
5343 assert_eq!(bs_events.len(), if announce_latest { 8 } else { 6 });
5344 let mut bs_failds = HashSet::new();
5345 let mut bs_updates = 0;
5346 for event in bs_events.iter() {
5347 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5348 assert!(bs_failds.insert(*payment_hash));
5349 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5350 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5352 assert!(!payment_failed_permanently);
5354 if let PathFailure::OnPath { network_update: Some(_) } = failure {
5357 } else if let &Event::PaymentFailed { .. } = event {
5358 } else { panic!("Unexpected event"); }
5360 assert!(bs_failds.contains(&payment_hash_1));
5361 assert!(bs_failds.contains(&payment_hash_2));
5362 if announce_latest {
5363 assert!(bs_failds.contains(&payment_hash_4));
5365 assert!(bs_failds.contains(&payment_hash_5));
5367 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5368 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5369 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5370 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5371 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5372 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5376 fn test_fail_backwards_latest_remote_announce_a() {
5377 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5381 fn test_fail_backwards_latest_remote_announce_b() {
5382 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5386 fn test_fail_backwards_previous_remote_announce() {
5387 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5388 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5389 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5393 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5394 let chanmon_cfgs = create_chanmon_cfgs(2);
5395 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5396 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5397 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5399 // Create some initial channels
5400 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5402 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5403 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5404 assert_eq!(local_txn[0].input.len(), 1);
5405 check_spends!(local_txn[0], chan_1.3);
5407 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5408 mine_transaction(&nodes[0], &local_txn[0]);
5409 check_closed_broadcast!(nodes[0], true);
5410 check_added_monitors!(nodes[0], 1);
5411 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5412 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5414 let htlc_timeout = {
5415 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5416 assert_eq!(node_txn.len(), 1);
5417 assert_eq!(node_txn[0].input.len(), 1);
5418 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5419 check_spends!(node_txn[0], local_txn[0]);
5423 mine_transaction(&nodes[0], &htlc_timeout);
5424 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5425 expect_payment_failed!(nodes[0], our_payment_hash, false);
5427 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5428 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5429 assert_eq!(spend_txn.len(), 3);
5430 check_spends!(spend_txn[0], local_txn[0]);
5431 assert_eq!(spend_txn[1].input.len(), 1);
5432 check_spends!(spend_txn[1], htlc_timeout);
5433 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5434 assert_eq!(spend_txn[2].input.len(), 2);
5435 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5436 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5437 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5441 fn test_key_derivation_params() {
5442 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5443 // manager rotation to test that `channel_keys_id` returned in
5444 // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5445 // then derive a `delayed_payment_key`.
5447 let chanmon_cfgs = create_chanmon_cfgs(3);
5449 // We manually create the node configuration to backup the seed.
5450 let seed = [42; 32];
5451 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5452 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);
5453 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[0].logger));
5454 let scorer = RwLock::new(test_utils::TestScorer::new());
5455 let router = test_utils::TestRouter::new(network_graph.clone(), &scorer);
5456 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)) };
5457 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5458 node_cfgs.remove(0);
5459 node_cfgs.insert(0, node);
5461 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5462 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5464 // Create some initial channels
5465 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5467 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2);
5468 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5469 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5471 // Ensure all nodes are at the same height
5472 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5473 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5474 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5475 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5477 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5478 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5479 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5480 assert_eq!(local_txn_1[0].input.len(), 1);
5481 check_spends!(local_txn_1[0], chan_1.3);
5483 // We check funding pubkey are unique
5484 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]));
5485 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]));
5486 if from_0_funding_key_0 == from_1_funding_key_0
5487 || from_0_funding_key_0 == from_1_funding_key_1
5488 || from_0_funding_key_1 == from_1_funding_key_0
5489 || from_0_funding_key_1 == from_1_funding_key_1 {
5490 panic!("Funding pubkeys aren't unique");
5493 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5494 mine_transaction(&nodes[0], &local_txn_1[0]);
5495 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5496 check_closed_broadcast!(nodes[0], true);
5497 check_added_monitors!(nodes[0], 1);
5498 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5500 let htlc_timeout = {
5501 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5502 assert_eq!(node_txn.len(), 1);
5503 assert_eq!(node_txn[0].input.len(), 1);
5504 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5505 check_spends!(node_txn[0], local_txn_1[0]);
5509 mine_transaction(&nodes[0], &htlc_timeout);
5510 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5511 expect_payment_failed!(nodes[0], our_payment_hash, false);
5513 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5514 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5515 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5516 assert_eq!(spend_txn.len(), 3);
5517 check_spends!(spend_txn[0], local_txn_1[0]);
5518 assert_eq!(spend_txn[1].input.len(), 1);
5519 check_spends!(spend_txn[1], htlc_timeout);
5520 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5521 assert_eq!(spend_txn[2].input.len(), 2);
5522 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5523 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5524 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5528 fn test_static_output_closing_tx() {
5529 let chanmon_cfgs = create_chanmon_cfgs(2);
5530 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5531 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5532 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5534 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5536 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5537 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5539 mine_transaction(&nodes[0], &closing_tx);
5540 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
5541 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5543 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5544 assert_eq!(spend_txn.len(), 1);
5545 check_spends!(spend_txn[0], closing_tx);
5547 mine_transaction(&nodes[1], &closing_tx);
5548 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
5549 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5551 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5552 assert_eq!(spend_txn.len(), 1);
5553 check_spends!(spend_txn[0], closing_tx);
5556 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5557 let chanmon_cfgs = create_chanmon_cfgs(2);
5558 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5559 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5560 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5561 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5563 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5565 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5566 // present in B's local commitment transaction, but none of A's commitment transactions.
5567 nodes[1].node.claim_funds(payment_preimage);
5568 check_added_monitors!(nodes[1], 1);
5569 expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5571 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5572 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5573 expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
5575 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5576 check_added_monitors!(nodes[0], 1);
5577 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5578 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5579 check_added_monitors!(nodes[1], 1);
5581 let starting_block = nodes[1].best_block_info();
5582 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5583 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5584 connect_block(&nodes[1], &block);
5585 block.header.prev_blockhash = block.block_hash();
5587 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5588 check_closed_broadcast!(nodes[1], true);
5589 check_added_monitors!(nodes[1], 1);
5590 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
5593 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5594 let chanmon_cfgs = create_chanmon_cfgs(2);
5595 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5596 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5597 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5598 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5600 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5601 nodes[0].node.send_payment_with_route(&route, payment_hash,
5602 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
5603 check_added_monitors!(nodes[0], 1);
5605 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5607 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5608 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5609 // to "time out" the HTLC.
5611 let starting_block = nodes[1].best_block_info();
5612 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5614 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5615 connect_block(&nodes[0], &block);
5616 block.header.prev_blockhash = block.block_hash();
5618 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5619 check_closed_broadcast!(nodes[0], true);
5620 check_added_monitors!(nodes[0], 1);
5621 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5624 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5625 let chanmon_cfgs = create_chanmon_cfgs(3);
5626 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5627 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5628 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5629 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5631 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5632 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5633 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5634 // actually revoked.
5635 let htlc_value = if use_dust { 50000 } else { 3000000 };
5636 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5637 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5638 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5639 check_added_monitors!(nodes[1], 1);
5641 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5642 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5643 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5644 check_added_monitors!(nodes[0], 1);
5645 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5646 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5647 check_added_monitors!(nodes[1], 1);
5648 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5649 check_added_monitors!(nodes[1], 1);
5650 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5652 if check_revoke_no_close {
5653 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5654 check_added_monitors!(nodes[0], 1);
5657 let starting_block = nodes[1].best_block_info();
5658 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5659 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5660 connect_block(&nodes[0], &block);
5661 block.header.prev_blockhash = block.block_hash();
5663 if !check_revoke_no_close {
5664 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5665 check_closed_broadcast!(nodes[0], true);
5666 check_added_monitors!(nodes[0], 1);
5667 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5669 expect_payment_failed!(nodes[0], our_payment_hash, true);
5673 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5674 // There are only a few cases to test here:
5675 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5676 // broadcastable commitment transactions result in channel closure,
5677 // * its included in an unrevoked-but-previous remote commitment transaction,
5678 // * its included in the latest remote or local commitment transactions.
5679 // We test each of the three possible commitment transactions individually and use both dust and
5681 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5682 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5683 // tested for at least one of the cases in other tests.
5685 fn htlc_claim_single_commitment_only_a() {
5686 do_htlc_claim_local_commitment_only(true);
5687 do_htlc_claim_local_commitment_only(false);
5689 do_htlc_claim_current_remote_commitment_only(true);
5690 do_htlc_claim_current_remote_commitment_only(false);
5694 fn htlc_claim_single_commitment_only_b() {
5695 do_htlc_claim_previous_remote_commitment_only(true, false);
5696 do_htlc_claim_previous_remote_commitment_only(false, false);
5697 do_htlc_claim_previous_remote_commitment_only(true, true);
5698 do_htlc_claim_previous_remote_commitment_only(false, true);
5703 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5704 let chanmon_cfgs = create_chanmon_cfgs(2);
5705 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5706 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5707 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5708 // Force duplicate randomness for every get-random call
5709 for node in nodes.iter() {
5710 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5713 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5714 let channel_value_satoshis=10000;
5715 let push_msat=10001;
5716 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5717 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5718 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5719 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5721 // Create a second channel with the same random values. This used to panic due to a colliding
5722 // channel_id, but now panics due to a colliding outbound SCID alias.
5723 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5727 fn bolt2_open_channel_sending_node_checks_part2() {
5728 let chanmon_cfgs = create_chanmon_cfgs(2);
5729 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5730 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5731 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5733 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5734 let channel_value_satoshis=2^24;
5735 let push_msat=10001;
5736 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5738 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5739 let channel_value_satoshis=10000;
5740 // Test when push_msat is equal to 1000 * funding_satoshis.
5741 let push_msat=1000*channel_value_satoshis+1;
5742 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5744 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5745 let channel_value_satoshis=10000;
5746 let push_msat=10001;
5747 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_ok()); //Create a valid channel
5748 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5749 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5751 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5752 // 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
5753 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5755 // 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.
5756 assert!(BREAKDOWN_TIMEOUT>0);
5757 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5759 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5760 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5761 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5763 // 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.
5764 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5765 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5766 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5767 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5768 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5772 fn bolt2_open_channel_sane_dust_limit() {
5773 let chanmon_cfgs = create_chanmon_cfgs(2);
5774 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5775 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5776 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5778 let channel_value_satoshis=1000000;
5779 let push_msat=10001;
5780 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5781 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5782 node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5783 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5785 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5786 let events = nodes[1].node.get_and_clear_pending_msg_events();
5787 let err_msg = match events[0] {
5788 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5791 _ => panic!("Unexpected event"),
5793 assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5796 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5797 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5798 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5799 // is no longer affordable once it's freed.
5801 fn test_fail_holding_cell_htlc_upon_free() {
5802 let chanmon_cfgs = create_chanmon_cfgs(2);
5803 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5804 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5805 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5806 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5808 // First nodes[0] generates an update_fee, setting the channel's
5809 // pending_update_fee.
5811 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5812 *feerate_lock += 20;
5814 nodes[0].node.timer_tick_occurred();
5815 check_added_monitors!(nodes[0], 1);
5817 let events = nodes[0].node.get_and_clear_pending_msg_events();
5818 assert_eq!(events.len(), 1);
5819 let (update_msg, commitment_signed) = match events[0] {
5820 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5821 (update_fee.as_ref(), commitment_signed)
5823 _ => panic!("Unexpected event"),
5826 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5828 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5829 let channel_reserve = chan_stat.channel_reserve_msat;
5830 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5831 let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
5833 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5834 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
5835 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5837 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5838 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5839 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5840 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5841 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5843 // Flush the pending fee update.
5844 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5845 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5846 check_added_monitors!(nodes[1], 1);
5847 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5848 check_added_monitors!(nodes[0], 1);
5850 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5851 // HTLC, but now that the fee has been raised the payment will now fail, causing
5852 // us to surface its failure to the user.
5853 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5854 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5855 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Freeing holding cell with 1 HTLC updates in channel {}", chan.2), 1);
5857 // Check that the payment failed to be sent out.
5858 let events = nodes[0].node.get_and_clear_pending_events();
5859 assert_eq!(events.len(), 2);
5861 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5862 assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5863 assert_eq!(our_payment_hash.clone(), *payment_hash);
5864 assert_eq!(*payment_failed_permanently, false);
5865 assert_eq!(*short_channel_id, Some(route.paths[0].hops[0].short_channel_id));
5867 _ => panic!("Unexpected event"),
5870 &Event::PaymentFailed { ref payment_hash, .. } => {
5871 assert_eq!(our_payment_hash.clone(), *payment_hash);
5873 _ => panic!("Unexpected event"),
5877 // Test that if multiple HTLCs are released from the holding cell and one is
5878 // valid but the other is no longer valid upon release, the valid HTLC can be
5879 // successfully completed while the other one fails as expected.
5881 fn test_free_and_fail_holding_cell_htlcs() {
5882 let chanmon_cfgs = create_chanmon_cfgs(2);
5883 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5884 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5885 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5886 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5888 // First nodes[0] generates an update_fee, setting the channel's
5889 // pending_update_fee.
5891 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5892 *feerate_lock += 200;
5894 nodes[0].node.timer_tick_occurred();
5895 check_added_monitors!(nodes[0], 1);
5897 let events = nodes[0].node.get_and_clear_pending_msg_events();
5898 assert_eq!(events.len(), 1);
5899 let (update_msg, commitment_signed) = match events[0] {
5900 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5901 (update_fee.as_ref(), commitment_signed)
5903 _ => panic!("Unexpected event"),
5906 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5908 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5909 let channel_reserve = chan_stat.channel_reserve_msat;
5910 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5911 let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
5913 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5915 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features) - amt_1;
5916 let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5917 let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5919 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5920 nodes[0].node.send_payment_with_route(&route_1, payment_hash_1,
5921 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
5922 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5923 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
5924 let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
5925 nodes[0].node.send_payment_with_route(&route_2, payment_hash_2,
5926 RecipientOnionFields::secret_only(payment_secret_2), payment_id_2).unwrap();
5927 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5928 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
5930 // Flush the pending fee update.
5931 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5932 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5933 check_added_monitors!(nodes[1], 1);
5934 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
5935 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5936 check_added_monitors!(nodes[0], 2);
5938 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
5939 // but now that the fee has been raised the second payment will now fail, causing us
5940 // to surface its failure to the user. The first payment should succeed.
5941 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5942 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5943 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Freeing holding cell with 2 HTLC updates in channel {}", chan.2), 1);
5945 // Check that the second payment failed to be sent out.
5946 let events = nodes[0].node.get_and_clear_pending_events();
5947 assert_eq!(events.len(), 2);
5949 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5950 assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
5951 assert_eq!(payment_hash_2.clone(), *payment_hash);
5952 assert_eq!(*payment_failed_permanently, false);
5953 assert_eq!(*short_channel_id, Some(route_2.paths[0].hops[0].short_channel_id));
5955 _ => panic!("Unexpected event"),
5958 &Event::PaymentFailed { ref payment_hash, .. } => {
5959 assert_eq!(payment_hash_2.clone(), *payment_hash);
5961 _ => panic!("Unexpected event"),
5964 // Complete the first payment and the RAA from the fee update.
5965 let (payment_event, send_raa_event) = {
5966 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
5967 assert_eq!(msgs.len(), 2);
5968 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
5970 let raa = match send_raa_event {
5971 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
5972 _ => panic!("Unexpected event"),
5974 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5975 check_added_monitors!(nodes[1], 1);
5976 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5977 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5978 let events = nodes[1].node.get_and_clear_pending_events();
5979 assert_eq!(events.len(), 1);
5981 Event::PendingHTLCsForwardable { .. } => {},
5982 _ => panic!("Unexpected event"),
5984 nodes[1].node.process_pending_htlc_forwards();
5985 let events = nodes[1].node.get_and_clear_pending_events();
5986 assert_eq!(events.len(), 1);
5988 Event::PaymentClaimable { .. } => {},
5989 _ => panic!("Unexpected event"),
5991 nodes[1].node.claim_funds(payment_preimage_1);
5992 check_added_monitors!(nodes[1], 1);
5993 expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
5995 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5996 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
5997 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
5998 expect_payment_sent!(nodes[0], payment_preimage_1);
6001 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6002 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6003 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6006 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6007 let chanmon_cfgs = create_chanmon_cfgs(3);
6008 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6009 // Avoid having to include routing fees in calculations
6010 let mut config = test_default_channel_config();
6011 config.channel_config.forwarding_fee_base_msat = 0;
6012 config.channel_config.forwarding_fee_proportional_millionths = 0;
6013 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6014 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6015 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6016 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
6018 // First nodes[1] generates an update_fee, setting the channel's
6019 // pending_update_fee.
6021 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6022 *feerate_lock += 20;
6024 nodes[1].node.timer_tick_occurred();
6025 check_added_monitors!(nodes[1], 1);
6027 let events = nodes[1].node.get_and_clear_pending_msg_events();
6028 assert_eq!(events.len(), 1);
6029 let (update_msg, commitment_signed) = match events[0] {
6030 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6031 (update_fee.as_ref(), commitment_signed)
6033 _ => panic!("Unexpected event"),
6036 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6038 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan_0_1.2);
6039 let channel_reserve = chan_stat.channel_reserve_msat;
6040 let feerate = get_feerate!(nodes[0], nodes[1], chan_0_1.2);
6041 let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_0_1.2);
6043 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6044 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
6045 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6046 let payment_event = {
6047 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6048 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6049 check_added_monitors!(nodes[0], 1);
6051 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6052 assert_eq!(events.len(), 1);
6054 SendEvent::from_event(events.remove(0))
6056 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6057 check_added_monitors!(nodes[1], 0);
6058 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6059 expect_pending_htlcs_forwardable!(nodes[1]);
6061 chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
6062 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6064 // Flush the pending fee update.
6065 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6066 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6067 check_added_monitors!(nodes[2], 1);
6068 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6069 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6070 check_added_monitors!(nodes[1], 2);
6072 // A final RAA message is generated to finalize the fee update.
6073 let events = nodes[1].node.get_and_clear_pending_msg_events();
6074 assert_eq!(events.len(), 1);
6076 let raa_msg = match &events[0] {
6077 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6080 _ => panic!("Unexpected event"),
6083 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6084 check_added_monitors!(nodes[2], 1);
6085 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6087 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6088 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6089 assert_eq!(process_htlc_forwards_event.len(), 2);
6090 match &process_htlc_forwards_event[0] {
6091 &Event::PendingHTLCsForwardable { .. } => {},
6092 _ => panic!("Unexpected event"),
6095 // In response, we call ChannelManager's process_pending_htlc_forwards
6096 nodes[1].node.process_pending_htlc_forwards();
6097 check_added_monitors!(nodes[1], 1);
6099 // This causes the HTLC to be failed backwards.
6100 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6101 assert_eq!(fail_event.len(), 1);
6102 let (fail_msg, commitment_signed) = match &fail_event[0] {
6103 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6104 assert_eq!(updates.update_add_htlcs.len(), 0);
6105 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6106 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6107 assert_eq!(updates.update_fail_htlcs.len(), 1);
6108 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6110 _ => panic!("Unexpected event"),
6113 // Pass the failure messages back to nodes[0].
6114 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6115 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6117 // Complete the HTLC failure+removal process.
6118 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6119 check_added_monitors!(nodes[0], 1);
6120 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6121 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6122 check_added_monitors!(nodes[1], 2);
6123 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6124 assert_eq!(final_raa_event.len(), 1);
6125 let raa = match &final_raa_event[0] {
6126 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6127 _ => panic!("Unexpected event"),
6129 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6130 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6131 check_added_monitors!(nodes[0], 1);
6134 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6135 // 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.
6136 //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.
6139 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6140 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6141 let chanmon_cfgs = create_chanmon_cfgs(2);
6142 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6143 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6144 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6145 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6147 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6148 route.paths[0].hops[0].fee_msat = 100;
6150 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6151 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6152 ), true, APIError::ChannelUnavailable { .. }, {});
6153 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6157 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6158 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6159 let chanmon_cfgs = create_chanmon_cfgs(2);
6160 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6161 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6162 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6163 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6165 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6166 route.paths[0].hops[0].fee_msat = 0;
6167 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6168 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)),
6169 true, APIError::ChannelUnavailable { ref err },
6170 assert_eq!(err, "Cannot send 0-msat HTLC"));
6172 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6173 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send 0-msat HTLC", 1);
6177 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6178 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6179 let chanmon_cfgs = create_chanmon_cfgs(2);
6180 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6181 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6182 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6183 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6185 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6186 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6187 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6188 check_added_monitors!(nodes[0], 1);
6189 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6190 updates.update_add_htlcs[0].amount_msat = 0;
6192 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6193 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6194 check_closed_broadcast!(nodes[1], true).unwrap();
6195 check_added_monitors!(nodes[1], 1);
6196 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() },
6197 [nodes[0].node.get_our_node_id()], 100000);
6201 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6202 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6203 //It is enforced when constructing a route.
6204 let chanmon_cfgs = create_chanmon_cfgs(2);
6205 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6206 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6207 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6208 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6210 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6211 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
6212 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);
6213 route.paths[0].hops.last_mut().unwrap().cltv_expiry_delta = 500000001;
6214 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6215 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6216 ), true, APIError::InvalidRoute { ref err },
6217 assert_eq!(err, &"Channel CLTV overflowed?"));
6221 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6222 //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.
6223 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6224 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6225 let chanmon_cfgs = create_chanmon_cfgs(2);
6226 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6227 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6228 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6229 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6230 let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6231 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context().counterparty_max_accepted_htlcs as u64;
6233 // Fetch a route in advance as we will be unable to once we're unable to send.
6234 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6235 for i in 0..max_accepted_htlcs {
6236 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6237 let payment_event = {
6238 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6239 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6240 check_added_monitors!(nodes[0], 1);
6242 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6243 assert_eq!(events.len(), 1);
6244 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6245 assert_eq!(htlcs[0].htlc_id, i);
6249 SendEvent::from_event(events.remove(0))
6251 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6252 check_added_monitors!(nodes[1], 0);
6253 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6255 expect_pending_htlcs_forwardable!(nodes[1]);
6256 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6258 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6259 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6260 ), true, APIError::ChannelUnavailable { .. }, {});
6262 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6266 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6267 //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.
6268 let chanmon_cfgs = create_chanmon_cfgs(2);
6269 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6270 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6271 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6272 let channel_value = 100000;
6273 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6274 let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6276 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6278 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6279 // Manually create a route over our max in flight (which our router normally automatically
6281 route.paths[0].hops[0].fee_msat = max_in_flight + 1;
6282 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6283 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6284 ), true, APIError::ChannelUnavailable { .. }, {});
6285 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6287 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6290 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6292 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6293 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6294 let chanmon_cfgs = create_chanmon_cfgs(2);
6295 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6296 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6297 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6298 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6299 let htlc_minimum_msat: u64;
6301 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6302 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6303 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6304 htlc_minimum_msat = channel.context().get_holder_htlc_minimum_msat();
6307 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6308 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6309 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6310 check_added_monitors!(nodes[0], 1);
6311 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6312 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6313 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6314 assert!(nodes[1].node.list_channels().is_empty());
6315 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6316 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()));
6317 check_added_monitors!(nodes[1], 1);
6318 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6322 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6323 //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
6324 let chanmon_cfgs = create_chanmon_cfgs(2);
6325 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6326 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6327 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6328 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6330 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6331 let channel_reserve = chan_stat.channel_reserve_msat;
6332 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6333 let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
6334 // The 2* and +1 are for the fee spike reserve.
6335 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
6337 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6338 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6339 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6340 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6341 check_added_monitors!(nodes[0], 1);
6342 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6344 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6345 // at this time channel-initiatee receivers are not required to enforce that senders
6346 // respect the fee_spike_reserve.
6347 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6348 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6350 assert!(nodes[1].node.list_channels().is_empty());
6351 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6352 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6353 check_added_monitors!(nodes[1], 1);
6354 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6358 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6359 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6360 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6361 let chanmon_cfgs = create_chanmon_cfgs(2);
6362 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6363 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6364 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6365 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6367 let send_amt = 3999999;
6368 let (mut route, our_payment_hash, _, our_payment_secret) =
6369 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
6370 route.paths[0].hops[0].fee_msat = send_amt;
6371 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6372 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6373 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6374 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
6375 &route.paths[0], send_amt, RecipientOnionFields::secret_only(our_payment_secret), cur_height, &None).unwrap();
6376 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
6378 let mut msg = msgs::UpdateAddHTLC {
6382 payment_hash: our_payment_hash,
6383 cltv_expiry: htlc_cltv,
6384 onion_routing_packet: onion_packet.clone(),
6385 skimmed_fee_msat: None,
6389 msg.htlc_id = i as u64;
6390 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6392 msg.htlc_id = (50) as u64;
6393 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6395 assert!(nodes[1].node.list_channels().is_empty());
6396 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6397 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6398 check_added_monitors!(nodes[1], 1);
6399 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6403 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6404 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6405 let chanmon_cfgs = create_chanmon_cfgs(2);
6406 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6407 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6408 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6409 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6411 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6412 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6413 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6414 check_added_monitors!(nodes[0], 1);
6415 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6416 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;
6417 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6419 assert!(nodes[1].node.list_channels().is_empty());
6420 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6421 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6422 check_added_monitors!(nodes[1], 1);
6423 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 1000000);
6427 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6428 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6429 let chanmon_cfgs = create_chanmon_cfgs(2);
6430 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6431 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6432 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6434 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6435 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6436 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6437 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6438 check_added_monitors!(nodes[0], 1);
6439 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6440 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6441 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6443 assert!(nodes[1].node.list_channels().is_empty());
6444 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6445 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6446 check_added_monitors!(nodes[1], 1);
6447 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6451 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6452 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6453 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6454 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6455 let chanmon_cfgs = create_chanmon_cfgs(2);
6456 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6457 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6458 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6460 create_announced_chan_between_nodes(&nodes, 0, 1);
6461 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6462 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6463 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6464 check_added_monitors!(nodes[0], 1);
6465 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6466 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6468 //Disconnect and Reconnect
6469 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
6470 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
6471 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
6472 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
6474 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6475 assert_eq!(reestablish_1.len(), 1);
6476 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
6477 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
6479 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6480 assert_eq!(reestablish_2.len(), 1);
6481 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6482 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6483 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6484 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6487 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6488 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6489 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6490 check_added_monitors!(nodes[1], 1);
6491 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6493 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6495 assert!(nodes[1].node.list_channels().is_empty());
6496 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6497 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6498 check_added_monitors!(nodes[1], 1);
6499 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6503 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6504 //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.
6506 let chanmon_cfgs = create_chanmon_cfgs(2);
6507 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6508 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6509 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6510 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6511 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6512 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6513 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6515 check_added_monitors!(nodes[0], 1);
6516 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6517 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6519 let update_msg = msgs::UpdateFulfillHTLC{
6522 payment_preimage: our_payment_preimage,
6525 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6527 assert!(nodes[0].node.list_channels().is_empty());
6528 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6529 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()));
6530 check_added_monitors!(nodes[0], 1);
6531 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6535 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6536 //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.
6538 let chanmon_cfgs = create_chanmon_cfgs(2);
6539 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6540 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6541 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6542 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6544 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6545 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6546 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6547 check_added_monitors!(nodes[0], 1);
6548 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6549 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6551 let update_msg = msgs::UpdateFailHTLC{
6554 reason: msgs::OnionErrorPacket { data: Vec::new()},
6557 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6559 assert!(nodes[0].node.list_channels().is_empty());
6560 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6561 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()));
6562 check_added_monitors!(nodes[0], 1);
6563 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6567 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6568 //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.
6570 let chanmon_cfgs = create_chanmon_cfgs(2);
6571 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6572 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6573 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6574 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6576 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6577 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6578 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6579 check_added_monitors!(nodes[0], 1);
6580 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6581 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6582 let update_msg = msgs::UpdateFailMalformedHTLC{
6585 sha256_of_onion: [1; 32],
6586 failure_code: 0x8000,
6589 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6591 assert!(nodes[0].node.list_channels().is_empty());
6592 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6593 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()));
6594 check_added_monitors!(nodes[0], 1);
6595 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6599 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6600 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6602 let chanmon_cfgs = create_chanmon_cfgs(2);
6603 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6604 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6605 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6606 create_announced_chan_between_nodes(&nodes, 0, 1);
6608 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6610 nodes[1].node.claim_funds(our_payment_preimage);
6611 check_added_monitors!(nodes[1], 1);
6612 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6614 let events = nodes[1].node.get_and_clear_pending_msg_events();
6615 assert_eq!(events.len(), 1);
6616 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6618 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, .. } } => {
6619 assert!(update_add_htlcs.is_empty());
6620 assert_eq!(update_fulfill_htlcs.len(), 1);
6621 assert!(update_fail_htlcs.is_empty());
6622 assert!(update_fail_malformed_htlcs.is_empty());
6623 assert!(update_fee.is_none());
6624 update_fulfill_htlcs[0].clone()
6626 _ => panic!("Unexpected event"),
6630 update_fulfill_msg.htlc_id = 1;
6632 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6634 assert!(nodes[0].node.list_channels().is_empty());
6635 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6636 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6637 check_added_monitors!(nodes[0], 1);
6638 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6642 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6643 //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.
6645 let chanmon_cfgs = create_chanmon_cfgs(2);
6646 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6647 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6648 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6649 create_announced_chan_between_nodes(&nodes, 0, 1);
6651 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6653 nodes[1].node.claim_funds(our_payment_preimage);
6654 check_added_monitors!(nodes[1], 1);
6655 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6657 let events = nodes[1].node.get_and_clear_pending_msg_events();
6658 assert_eq!(events.len(), 1);
6659 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6661 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, .. } } => {
6662 assert!(update_add_htlcs.is_empty());
6663 assert_eq!(update_fulfill_htlcs.len(), 1);
6664 assert!(update_fail_htlcs.is_empty());
6665 assert!(update_fail_malformed_htlcs.is_empty());
6666 assert!(update_fee.is_none());
6667 update_fulfill_htlcs[0].clone()
6669 _ => panic!("Unexpected event"),
6673 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6675 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6677 assert!(nodes[0].node.list_channels().is_empty());
6678 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6679 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6680 check_added_monitors!(nodes[0], 1);
6681 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6685 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6686 //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.
6688 let chanmon_cfgs = create_chanmon_cfgs(2);
6689 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6690 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6691 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6692 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6694 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6695 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6696 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6697 check_added_monitors!(nodes[0], 1);
6699 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6700 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6702 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6703 check_added_monitors!(nodes[1], 0);
6704 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6706 let events = nodes[1].node.get_and_clear_pending_msg_events();
6708 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6710 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, .. } } => {
6711 assert!(update_add_htlcs.is_empty());
6712 assert!(update_fulfill_htlcs.is_empty());
6713 assert!(update_fail_htlcs.is_empty());
6714 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6715 assert!(update_fee.is_none());
6716 update_fail_malformed_htlcs[0].clone()
6718 _ => panic!("Unexpected event"),
6721 update_msg.failure_code &= !0x8000;
6722 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6724 assert!(nodes[0].node.list_channels().is_empty());
6725 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6726 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6727 check_added_monitors!(nodes[0], 1);
6728 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 1000000);
6732 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6733 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6734 // * 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.
6736 let chanmon_cfgs = create_chanmon_cfgs(3);
6737 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6738 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6739 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6740 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6741 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000);
6743 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6746 let mut payment_event = {
6747 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6748 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6749 check_added_monitors!(nodes[0], 1);
6750 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6751 assert_eq!(events.len(), 1);
6752 SendEvent::from_event(events.remove(0))
6754 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6755 check_added_monitors!(nodes[1], 0);
6756 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6757 expect_pending_htlcs_forwardable!(nodes[1]);
6758 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6759 assert_eq!(events_2.len(), 1);
6760 check_added_monitors!(nodes[1], 1);
6761 payment_event = SendEvent::from_event(events_2.remove(0));
6762 assert_eq!(payment_event.msgs.len(), 1);
6765 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6766 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6767 check_added_monitors!(nodes[2], 0);
6768 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6770 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6771 assert_eq!(events_3.len(), 1);
6772 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6774 MessageSendEvent::UpdateHTLCs { node_id: _ , updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
6775 assert!(update_add_htlcs.is_empty());
6776 assert!(update_fulfill_htlcs.is_empty());
6777 assert!(update_fail_htlcs.is_empty());
6778 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6779 assert!(update_fee.is_none());
6780 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6782 _ => panic!("Unexpected event"),
6786 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6788 check_added_monitors!(nodes[1], 0);
6789 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6790 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 }]);
6791 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6792 assert_eq!(events_4.len(), 1);
6794 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6796 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, .. } } => {
6797 assert!(update_add_htlcs.is_empty());
6798 assert!(update_fulfill_htlcs.is_empty());
6799 assert_eq!(update_fail_htlcs.len(), 1);
6800 assert!(update_fail_malformed_htlcs.is_empty());
6801 assert!(update_fee.is_none());
6803 _ => panic!("Unexpected event"),
6806 check_added_monitors!(nodes[1], 1);
6810 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6811 let chanmon_cfgs = create_chanmon_cfgs(3);
6812 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6813 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6814 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6815 create_announced_chan_between_nodes(&nodes, 0, 1);
6816 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6818 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6821 let mut payment_event = {
6822 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6823 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6824 check_added_monitors!(nodes[0], 1);
6825 SendEvent::from_node(&nodes[0])
6828 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6829 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6830 expect_pending_htlcs_forwardable!(nodes[1]);
6831 check_added_monitors!(nodes[1], 1);
6832 payment_event = SendEvent::from_node(&nodes[1]);
6833 assert_eq!(payment_event.msgs.len(), 1);
6836 payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6837 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6838 check_added_monitors!(nodes[2], 0);
6839 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6841 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6842 assert_eq!(events_3.len(), 1);
6844 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6845 let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6846 // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6847 update_msg.failure_code |= 0x2000;
6849 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6850 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6852 _ => panic!("Unexpected event"),
6855 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6856 vec![HTLCDestination::NextHopChannel {
6857 node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6858 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6859 assert_eq!(events_4.len(), 1);
6860 check_added_monitors!(nodes[1], 1);
6863 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6864 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6865 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6867 _ => panic!("Unexpected event"),
6870 let events_5 = nodes[0].node.get_and_clear_pending_events();
6871 assert_eq!(events_5.len(), 2);
6873 // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6874 // the node originating the error to its next hop.
6876 Event::PaymentPathFailed { error_code, failure: PathFailure::OnPath { network_update: Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }) }, ..
6878 assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6879 assert!(is_permanent);
6880 assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
6882 _ => panic!("Unexpected event"),
6885 Event::PaymentFailed { payment_hash, .. } => {
6886 assert_eq!(payment_hash, our_payment_hash);
6888 _ => panic!("Unexpected event"),
6891 // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
6894 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6895 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6896 // 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
6897 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6899 let mut chanmon_cfgs = create_chanmon_cfgs(2);
6900 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6901 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6902 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6903 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6904 let chan =create_announced_chan_between_nodes(&nodes, 0, 1);
6906 let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6907 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context().holder_dust_limit_satoshis;
6909 // We route 2 dust-HTLCs between A and B
6910 let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6911 let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6912 route_payment(&nodes[0], &[&nodes[1]], 1000000);
6914 // Cache one local commitment tx as previous
6915 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6917 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6918 nodes[1].node.fail_htlc_backwards(&payment_hash_2);
6919 check_added_monitors!(nodes[1], 0);
6920 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
6921 check_added_monitors!(nodes[1], 1);
6923 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6924 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6925 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6926 check_added_monitors!(nodes[0], 1);
6928 // Cache one local commitment tx as lastest
6929 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6931 let events = nodes[0].node.get_and_clear_pending_msg_events();
6933 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6934 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6936 _ => panic!("Unexpected event"),
6939 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6940 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6942 _ => panic!("Unexpected event"),
6945 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6946 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6947 if announce_latest {
6948 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6950 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6953 check_closed_broadcast!(nodes[0], true);
6954 check_added_monitors!(nodes[0], 1);
6955 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
6957 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6958 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6959 let events = nodes[0].node.get_and_clear_pending_events();
6960 // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
6961 assert_eq!(events.len(), 4);
6962 let mut first_failed = false;
6963 for event in events {
6965 Event::PaymentPathFailed { payment_hash, .. } => {
6966 if payment_hash == payment_hash_1 {
6967 assert!(!first_failed);
6968 first_failed = true;
6970 assert_eq!(payment_hash, payment_hash_2);
6973 Event::PaymentFailed { .. } => {}
6974 _ => panic!("Unexpected event"),
6980 fn test_failure_delay_dust_htlc_local_commitment() {
6981 do_test_failure_delay_dust_htlc_local_commitment(true);
6982 do_test_failure_delay_dust_htlc_local_commitment(false);
6985 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6986 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6987 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6988 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6989 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6990 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6991 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6993 let chanmon_cfgs = create_chanmon_cfgs(3);
6994 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6995 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6996 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6997 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6999 let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
7000 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context().holder_dust_limit_satoshis;
7002 let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7003 let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7005 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7006 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7008 // We revoked bs_commitment_tx
7010 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7011 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7014 let mut timeout_tx = Vec::new();
7016 // We fail dust-HTLC 1 by broadcast of local commitment tx
7017 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7018 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7019 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7020 expect_payment_failed!(nodes[0], dust_hash, false);
7022 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7023 check_closed_broadcast!(nodes[0], true);
7024 check_added_monitors!(nodes[0], 1);
7025 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7026 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7027 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7028 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7029 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7030 mine_transaction(&nodes[0], &timeout_tx[0]);
7031 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7032 expect_payment_failed!(nodes[0], non_dust_hash, false);
7034 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7035 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7036 check_closed_broadcast!(nodes[0], true);
7037 check_added_monitors!(nodes[0], 1);
7038 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7039 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7041 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7042 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
7043 .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
7044 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
7045 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
7046 // dust HTLC should have been failed.
7047 expect_payment_failed!(nodes[0], dust_hash, false);
7050 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7052 assert_eq!(timeout_tx[0].lock_time.0, 11);
7054 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
7055 mine_transaction(&nodes[0], &timeout_tx[0]);
7056 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7057 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7058 expect_payment_failed!(nodes[0], non_dust_hash, false);
7063 fn test_sweep_outbound_htlc_failure_update() {
7064 do_test_sweep_outbound_htlc_failure_update(false, true);
7065 do_test_sweep_outbound_htlc_failure_update(false, false);
7066 do_test_sweep_outbound_htlc_failure_update(true, false);
7070 fn test_user_configurable_csv_delay() {
7071 // We test our channel constructors yield errors when we pass them absurd csv delay
7073 let mut low_our_to_self_config = UserConfig::default();
7074 low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
7075 let mut high_their_to_self_config = UserConfig::default();
7076 high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
7077 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7078 let chanmon_cfgs = create_chanmon_cfgs(2);
7079 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7080 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7081 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7083 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in OutboundV1Channel::new()
7084 if let Err(error) = OutboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7085 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[1].node.init_features(), 1000000, 1000000, 0,
7086 &low_our_to_self_config, 0, 42)
7089 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())); },
7090 _ => panic!("Unexpected event"),
7092 } else { assert!(false) }
7094 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in InboundV1Channel::new()
7095 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7096 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7097 open_channel.to_self_delay = 200;
7098 if let Err(error) = InboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7099 &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,
7100 &low_our_to_self_config, 0, &nodes[0].logger, /*is_0conf=*/false)
7103 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())); },
7104 _ => panic!("Unexpected event"),
7106 } else { assert!(false); }
7108 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7109 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7110 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()));
7111 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7112 accept_channel.to_self_delay = 200;
7113 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
7115 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7117 &ErrorAction::SendErrorMessage { ref msg } => {
7118 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()));
7119 reason_msg = msg.data.clone();
7123 } else { panic!(); }
7124 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg }, [nodes[1].node.get_our_node_id()], 1000000);
7126 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in InboundV1Channel::new()
7127 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7128 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7129 open_channel.to_self_delay = 200;
7130 if let Err(error) = InboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7131 &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,
7132 &high_their_to_self_config, 0, &nodes[0].logger, /*is_0conf=*/false)
7135 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())); },
7136 _ => panic!("Unexpected event"),
7138 } else { assert!(false); }
7142 fn test_check_htlc_underpaying() {
7143 // Send payment through A -> B but A is maliciously
7144 // sending a probe payment (i.e less than expected value0
7145 // to B, B should refuse payment.
7147 let chanmon_cfgs = create_chanmon_cfgs(2);
7148 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7149 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7150 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7152 // Create some initial channels
7153 create_announced_chan_between_nodes(&nodes, 0, 1);
7155 let scorer = test_utils::TestScorer::new();
7156 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7157 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(),
7158 TEST_FINAL_CLTV).with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
7159 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 10_000);
7160 let route = get_route(&nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph.read_only(),
7161 None, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7162 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7163 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, None).unwrap();
7164 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
7165 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
7166 check_added_monitors!(nodes[0], 1);
7168 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7169 assert_eq!(events.len(), 1);
7170 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7171 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7172 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7174 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7175 // and then will wait a second random delay before failing the HTLC back:
7176 expect_pending_htlcs_forwardable!(nodes[1]);
7177 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7179 // Node 3 is expecting payment of 100_000 but received 10_000,
7180 // it should fail htlc like we didn't know the preimage.
7181 nodes[1].node.process_pending_htlc_forwards();
7183 let events = nodes[1].node.get_and_clear_pending_msg_events();
7184 assert_eq!(events.len(), 1);
7185 let (update_fail_htlc, commitment_signed) = match events[0] {
7186 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 } } => {
7187 assert!(update_add_htlcs.is_empty());
7188 assert!(update_fulfill_htlcs.is_empty());
7189 assert_eq!(update_fail_htlcs.len(), 1);
7190 assert!(update_fail_malformed_htlcs.is_empty());
7191 assert!(update_fee.is_none());
7192 (update_fail_htlcs[0].clone(), commitment_signed)
7194 _ => panic!("Unexpected event"),
7196 check_added_monitors!(nodes[1], 1);
7198 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7199 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7201 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7202 let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
7203 expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
7204 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7208 fn test_announce_disable_channels() {
7209 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7210 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7212 let chanmon_cfgs = create_chanmon_cfgs(2);
7213 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7214 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7215 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7217 create_announced_chan_between_nodes(&nodes, 0, 1);
7218 create_announced_chan_between_nodes(&nodes, 1, 0);
7219 create_announced_chan_between_nodes(&nodes, 0, 1);
7222 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
7223 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
7225 for _ in 0..DISABLE_GOSSIP_TICKS + 1 {
7226 nodes[0].node.timer_tick_occurred();
7228 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7229 assert_eq!(msg_events.len(), 3);
7230 let mut chans_disabled = HashMap::new();
7231 for e in msg_events {
7233 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7234 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7235 // Check that each channel gets updated exactly once
7236 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7237 panic!("Generated ChannelUpdate for wrong chan!");
7240 _ => panic!("Unexpected event"),
7244 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
7245 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
7247 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7248 assert_eq!(reestablish_1.len(), 3);
7249 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
7250 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
7252 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7253 assert_eq!(reestablish_2.len(), 3);
7255 // Reestablish chan_1
7256 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7257 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7258 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7259 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7260 // Reestablish chan_2
7261 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7262 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7263 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7264 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7265 // Reestablish chan_3
7266 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7267 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7268 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7269 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7271 for _ in 0..ENABLE_GOSSIP_TICKS {
7272 nodes[0].node.timer_tick_occurred();
7274 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7275 nodes[0].node.timer_tick_occurred();
7276 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7277 assert_eq!(msg_events.len(), 3);
7278 for e in msg_events {
7280 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7281 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7282 match chans_disabled.remove(&msg.contents.short_channel_id) {
7283 // Each update should have a higher timestamp than the previous one, replacing
7285 Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7286 None => panic!("Generated ChannelUpdate for wrong chan!"),
7289 _ => panic!("Unexpected event"),
7292 // Check that each channel gets updated exactly once
7293 assert!(chans_disabled.is_empty());
7297 fn test_bump_penalty_txn_on_revoked_commitment() {
7298 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7299 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7301 let chanmon_cfgs = create_chanmon_cfgs(2);
7302 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7303 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7304 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7306 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7308 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7309 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7310 .with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7311 let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000);
7312 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7314 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7315 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7316 assert_eq!(revoked_txn[0].output.len(), 4);
7317 assert_eq!(revoked_txn[0].input.len(), 1);
7318 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7319 let revoked_txid = revoked_txn[0].txid();
7321 let mut penalty_sum = 0;
7322 for outp in revoked_txn[0].output.iter() {
7323 if outp.script_pubkey.is_v0_p2wsh() {
7324 penalty_sum += outp.value;
7328 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7329 let header_114 = connect_blocks(&nodes[1], 14);
7331 // Actually revoke tx by claiming a HTLC
7332 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7333 connect_block(&nodes[1], &create_dummy_block(header_114, 42, vec![revoked_txn[0].clone()]));
7334 check_added_monitors!(nodes[1], 1);
7336 // One or more justice tx should have been broadcast, check it
7340 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7341 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7342 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7343 assert_eq!(node_txn[0].output.len(), 1);
7344 check_spends!(node_txn[0], revoked_txn[0]);
7345 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7346 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7347 penalty_1 = node_txn[0].txid();
7351 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7352 connect_blocks(&nodes[1], 15);
7353 let mut penalty_2 = penalty_1;
7354 let mut feerate_2 = 0;
7356 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7357 assert_eq!(node_txn.len(), 1);
7358 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7359 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7360 assert_eq!(node_txn[0].output.len(), 1);
7361 check_spends!(node_txn[0], revoked_txn[0]);
7362 penalty_2 = node_txn[0].txid();
7363 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7364 assert_ne!(penalty_2, penalty_1);
7365 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7366 feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7367 // Verify 25% bump heuristic
7368 assert!(feerate_2 * 100 >= feerate_1 * 125);
7372 assert_ne!(feerate_2, 0);
7374 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7375 connect_blocks(&nodes[1], 1);
7377 let mut feerate_3 = 0;
7379 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7380 assert_eq!(node_txn.len(), 1);
7381 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7382 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7383 assert_eq!(node_txn[0].output.len(), 1);
7384 check_spends!(node_txn[0], revoked_txn[0]);
7385 penalty_3 = node_txn[0].txid();
7386 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7387 assert_ne!(penalty_3, penalty_2);
7388 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7389 feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7390 // Verify 25% bump heuristic
7391 assert!(feerate_3 * 100 >= feerate_2 * 125);
7395 assert_ne!(feerate_3, 0);
7397 nodes[1].node.get_and_clear_pending_events();
7398 nodes[1].node.get_and_clear_pending_msg_events();
7402 fn test_bump_penalty_txn_on_revoked_htlcs() {
7403 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7404 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7406 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7407 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7408 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7409 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7410 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7412 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7413 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7414 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 50).with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
7415 let scorer = test_utils::TestScorer::new();
7416 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7417 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 3_000_000);
7418 let route = get_route(&nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph.read_only(), None,
7419 nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7420 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7421 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50).with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7422 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 3_000_000);
7423 let route = get_route(&nodes[1].node.get_our_node_id(), &route_params, &nodes[1].network_graph.read_only(), None,
7424 nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7425 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7427 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7428 assert_eq!(revoked_local_txn[0].input.len(), 1);
7429 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7431 // Revoke local commitment tx
7432 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7434 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7435 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone()]));
7436 check_closed_broadcast!(nodes[1], true);
7437 check_added_monitors!(nodes[1], 1);
7438 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 1000000);
7439 connect_blocks(&nodes[1], 50); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7441 let revoked_htlc_txn = {
7442 let txn = nodes[1].tx_broadcaster.unique_txn_broadcast();
7443 assert_eq!(txn.len(), 2);
7445 assert_eq!(txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7446 assert_eq!(txn[0].input.len(), 1);
7447 check_spends!(txn[0], revoked_local_txn[0]);
7449 assert_eq!(txn[1].input.len(), 1);
7450 assert_eq!(txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7451 assert_eq!(txn[1].output.len(), 1);
7452 check_spends!(txn[1], revoked_local_txn[0]);
7457 // Broadcast set of revoked txn on A
7458 let hash_128 = connect_blocks(&nodes[0], 40);
7459 let block_11 = create_dummy_block(hash_128, 42, vec![revoked_local_txn[0].clone()]);
7460 connect_block(&nodes[0], &block_11);
7461 let block_129 = create_dummy_block(block_11.block_hash(), 42, vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()]);
7462 connect_block(&nodes[0], &block_129);
7463 let events = nodes[0].node.get_and_clear_pending_events();
7464 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7465 match events.last().unwrap() {
7466 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7467 _ => panic!("Unexpected event"),
7473 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7474 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7475 // Verify claim tx are spending revoked HTLC txn
7477 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7478 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7479 // which are included in the same block (they are broadcasted because we scan the
7480 // transactions linearly and generate claims as we go, they likely should be removed in the
7482 assert_eq!(node_txn[0].input.len(), 1);
7483 check_spends!(node_txn[0], revoked_local_txn[0]);
7484 assert_eq!(node_txn[1].input.len(), 1);
7485 check_spends!(node_txn[1], revoked_local_txn[0]);
7486 assert_eq!(node_txn[2].input.len(), 1);
7487 check_spends!(node_txn[2], revoked_local_txn[0]);
7489 // Each of the three justice transactions claim a separate (single) output of the three
7490 // available, which we check here:
7491 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7492 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7493 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7495 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7496 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7498 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7499 // output, checked above).
7500 assert_eq!(node_txn[3].input.len(), 2);
7501 assert_eq!(node_txn[3].output.len(), 1);
7502 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7504 first = node_txn[3].txid();
7505 // Store both feerates for later comparison
7506 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7507 feerate_1 = fee_1 * 1000 / node_txn[3].weight() as u64;
7508 penalty_txn = vec![node_txn[2].clone()];
7512 // Connect one more block to see if bumped penalty are issued for HTLC txn
7513 let block_130 = create_dummy_block(block_129.block_hash(), 42, penalty_txn);
7514 connect_block(&nodes[0], &block_130);
7515 let block_131 = create_dummy_block(block_130.block_hash(), 42, Vec::new());
7516 connect_block(&nodes[0], &block_131);
7518 // Few more blocks to confirm penalty txn
7519 connect_blocks(&nodes[0], 4);
7520 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7521 let header_144 = connect_blocks(&nodes[0], 9);
7523 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7524 assert_eq!(node_txn.len(), 1);
7526 assert_eq!(node_txn[0].input.len(), 2);
7527 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7528 // Verify bumped tx is different and 25% bump heuristic
7529 assert_ne!(first, node_txn[0].txid());
7530 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7531 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7532 assert!(feerate_2 * 100 > feerate_1 * 125);
7533 let txn = vec![node_txn[0].clone()];
7537 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7538 connect_block(&nodes[0], &create_dummy_block(header_144, 42, node_txn));
7539 connect_blocks(&nodes[0], 20);
7541 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7542 // We verify than no new transaction has been broadcast because previously
7543 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7544 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7545 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7546 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7547 // up bumped justice generation.
7548 assert_eq!(node_txn.len(), 0);
7551 check_closed_broadcast!(nodes[0], true);
7552 check_added_monitors!(nodes[0], 1);
7556 fn test_bump_penalty_txn_on_remote_commitment() {
7557 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7558 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7561 // Provide preimage for one
7562 // Check aggregation
7564 let chanmon_cfgs = create_chanmon_cfgs(2);
7565 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7566 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7567 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7569 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7570 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7571 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7573 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7574 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7575 assert_eq!(remote_txn[0].output.len(), 4);
7576 assert_eq!(remote_txn[0].input.len(), 1);
7577 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7579 // Claim a HTLC without revocation (provide B monitor with preimage)
7580 nodes[1].node.claim_funds(payment_preimage);
7581 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7582 mine_transaction(&nodes[1], &remote_txn[0]);
7583 check_added_monitors!(nodes[1], 2);
7584 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7586 // One or more claim tx should have been broadcast, check it
7590 let feerate_timeout;
7591 let feerate_preimage;
7593 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7594 // 3 transactions including:
7595 // preimage and timeout sweeps from remote commitment + preimage sweep bump
7596 assert_eq!(node_txn.len(), 3);
7597 assert_eq!(node_txn[0].input.len(), 1);
7598 assert_eq!(node_txn[1].input.len(), 1);
7599 assert_eq!(node_txn[2].input.len(), 1);
7600 check_spends!(node_txn[0], remote_txn[0]);
7601 check_spends!(node_txn[1], remote_txn[0]);
7602 check_spends!(node_txn[2], remote_txn[0]);
7604 preimage = node_txn[0].txid();
7605 let index = node_txn[0].input[0].previous_output.vout;
7606 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7607 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
7609 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7610 (node_txn[2].clone(), node_txn[1].clone())
7612 (node_txn[1].clone(), node_txn[2].clone())
7615 preimage_bump = preimage_bump_tx;
7616 check_spends!(preimage_bump, remote_txn[0]);
7617 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7619 timeout = timeout_tx.txid();
7620 let index = timeout_tx.input[0].previous_output.vout;
7621 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7622 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
7626 assert_ne!(feerate_timeout, 0);
7627 assert_ne!(feerate_preimage, 0);
7629 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7630 connect_blocks(&nodes[1], 1);
7632 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7633 assert_eq!(node_txn.len(), 1);
7634 assert_eq!(node_txn[0].input.len(), 1);
7635 assert_eq!(preimage_bump.input.len(), 1);
7636 check_spends!(node_txn[0], remote_txn[0]);
7637 check_spends!(preimage_bump, remote_txn[0]);
7639 let index = preimage_bump.input[0].previous_output.vout;
7640 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7641 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
7642 assert!(new_feerate * 100 > feerate_timeout * 125);
7643 assert_ne!(timeout, preimage_bump.txid());
7645 let index = node_txn[0].input[0].previous_output.vout;
7646 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7647 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
7648 assert!(new_feerate * 100 > feerate_preimage * 125);
7649 assert_ne!(preimage, node_txn[0].txid());
7654 nodes[1].node.get_and_clear_pending_events();
7655 nodes[1].node.get_and_clear_pending_msg_events();
7659 fn test_counterparty_raa_skip_no_crash() {
7660 // Previously, if our counterparty sent two RAAs in a row without us having provided a
7661 // commitment transaction, we would have happily carried on and provided them the next
7662 // commitment transaction based on one RAA forward. This would probably eventually have led to
7663 // channel closure, but it would not have resulted in funds loss. Still, our
7664 // TestChannelSigner would have panicked as it doesn't like jumps into the future. Here, we
7665 // check simply that the channel is closed in response to such an RAA, but don't check whether
7666 // we decide to punish our counterparty for revoking their funds (as we don't currently
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);
7672 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7674 let per_commitment_secret;
7675 let next_per_commitment_point;
7677 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7678 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7679 let keys = guard.channel_by_id.get_mut(&channel_id).map(
7680 |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
7681 ).flatten().unwrap().get_signer();
7683 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7685 // Make signer believe we got a counterparty signature, so that it allows the revocation
7686 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7687 per_commitment_secret = keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7689 // Must revoke without gaps
7690 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7691 keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7693 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7694 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7695 &SecretKey::from_slice(&keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7698 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7699 &msgs::RevokeAndACK {
7701 per_commitment_secret,
7702 next_per_commitment_point,
7704 next_local_nonce: None,
7706 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7707 check_added_monitors!(nodes[1], 1);
7708 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() }
7709 , [nodes[0].node.get_our_node_id()], 100000);
7713 fn test_bump_txn_sanitize_tracking_maps() {
7714 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7715 // verify we clean then right after expiration of ANTI_REORG_DELAY.
7717 let chanmon_cfgs = create_chanmon_cfgs(2);
7718 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7719 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7720 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7722 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7723 // Lock HTLC in both directions
7724 let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7725 let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7727 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7728 assert_eq!(revoked_local_txn[0].input.len(), 1);
7729 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7731 // Revoke local commitment tx
7732 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7734 // Broadcast set of revoked txn on A
7735 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7736 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7737 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7739 mine_transaction(&nodes[0], &revoked_local_txn[0]);
7740 check_closed_broadcast!(nodes[0], true);
7741 check_added_monitors!(nodes[0], 1);
7742 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 1000000);
7744 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7745 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7746 check_spends!(node_txn[0], revoked_local_txn[0]);
7747 check_spends!(node_txn[1], revoked_local_txn[0]);
7748 check_spends!(node_txn[2], revoked_local_txn[0]);
7749 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7753 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, penalty_txn));
7754 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7756 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7757 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7758 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7763 fn test_channel_conf_timeout() {
7764 // Tests that, for inbound channels, we give up on them if the funding transaction does not
7765 // confirm within 2016 blocks, as recommended by BOLT 2.
7766 let chanmon_cfgs = create_chanmon_cfgs(2);
7767 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7768 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7769 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7771 let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7773 // The outbound node should wait forever for confirmation:
7774 // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7775 // copied here instead of directly referencing the constant.
7776 connect_blocks(&nodes[0], 2016);
7777 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7779 // The inbound node should fail the channel after exactly 2016 blocks
7780 connect_blocks(&nodes[1], 2015);
7781 check_added_monitors!(nodes[1], 0);
7782 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7784 connect_blocks(&nodes[1], 1);
7785 check_added_monitors!(nodes[1], 1);
7786 check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut, [nodes[0].node.get_our_node_id()], 1000000);
7787 let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7788 assert_eq!(close_ev.len(), 1);
7790 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
7791 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7792 assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7794 _ => panic!("Unexpected event"),
7799 fn test_override_channel_config() {
7800 let chanmon_cfgs = create_chanmon_cfgs(2);
7801 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7802 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7803 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7805 // Node0 initiates a channel to node1 using the override config.
7806 let mut override_config = UserConfig::default();
7807 override_config.channel_handshake_config.our_to_self_delay = 200;
7809 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7811 // Assert the channel created by node0 is using the override config.
7812 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7813 assert_eq!(res.channel_flags, 0);
7814 assert_eq!(res.to_self_delay, 200);
7818 fn test_override_0msat_htlc_minimum() {
7819 let mut zero_config = UserConfig::default();
7820 zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
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, Some(zero_config.clone())]);
7824 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7826 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7827 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7828 assert_eq!(res.htlc_minimum_msat, 1);
7830 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7831 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7832 assert_eq!(res.htlc_minimum_msat, 1);
7836 fn test_channel_update_has_correct_htlc_maximum_msat() {
7837 // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7838 // Bolt 7 specifies that if present `htlc_maximum_msat`:
7839 // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7840 // 90% of the `channel_value`.
7841 // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7843 let mut config_30_percent = UserConfig::default();
7844 config_30_percent.channel_handshake_config.announced_channel = true;
7845 config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7846 let mut config_50_percent = UserConfig::default();
7847 config_50_percent.channel_handshake_config.announced_channel = true;
7848 config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7849 let mut config_95_percent = UserConfig::default();
7850 config_95_percent.channel_handshake_config.announced_channel = true;
7851 config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7852 let mut config_100_percent = UserConfig::default();
7853 config_100_percent.channel_handshake_config.announced_channel = true;
7854 config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7856 let chanmon_cfgs = create_chanmon_cfgs(4);
7857 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7858 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)]);
7859 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7861 let channel_value_satoshis = 100000;
7862 let channel_value_msat = channel_value_satoshis * 1000;
7863 let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7864 let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7865 let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7867 let (node_0_chan_update, node_1_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
7868 let (node_2_chan_update, node_3_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
7870 // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7871 // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7872 assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7873 // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7874 // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7875 assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7877 // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7878 // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7880 assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7881 // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7882 // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7884 assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7888 fn test_manually_accept_inbound_channel_request() {
7889 let mut manually_accept_conf = UserConfig::default();
7890 manually_accept_conf.manually_accept_inbound_channels = true;
7891 let chanmon_cfgs = create_chanmon_cfgs(2);
7892 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7893 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7894 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7896 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7897 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7899 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7901 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7902 // accepting the inbound channel request.
7903 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7905 let events = nodes[1].node.get_and_clear_pending_events();
7907 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7908 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
7910 _ => panic!("Unexpected event"),
7913 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7914 assert_eq!(accept_msg_ev.len(), 1);
7916 match accept_msg_ev[0] {
7917 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7918 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7920 _ => panic!("Unexpected event"),
7923 nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7925 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7926 assert_eq!(close_msg_ev.len(), 1);
7928 let events = nodes[1].node.get_and_clear_pending_events();
7930 Event::ChannelClosed { user_channel_id, .. } => {
7931 assert_eq!(user_channel_id, 23);
7933 _ => panic!("Unexpected event"),
7938 fn test_manually_reject_inbound_channel_request() {
7939 let mut manually_accept_conf = UserConfig::default();
7940 manually_accept_conf.manually_accept_inbound_channels = true;
7941 let chanmon_cfgs = create_chanmon_cfgs(2);
7942 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7943 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7944 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7946 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7947 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7949 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7951 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7952 // rejecting the inbound channel request.
7953 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7955 let events = nodes[1].node.get_and_clear_pending_events();
7957 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7958 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7960 _ => panic!("Unexpected event"),
7963 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7964 assert_eq!(close_msg_ev.len(), 1);
7966 match close_msg_ev[0] {
7967 MessageSendEvent::HandleError { ref node_id, .. } => {
7968 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7970 _ => panic!("Unexpected event"),
7973 // There should be no more events to process, as the channel was never opened.
7974 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
7978 fn test_can_not_accept_inbound_channel_twice() {
7979 let mut manually_accept_conf = UserConfig::default();
7980 manually_accept_conf.manually_accept_inbound_channels = true;
7981 let chanmon_cfgs = create_chanmon_cfgs(2);
7982 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7983 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7984 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7986 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7987 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7989 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7991 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7992 // accepting the inbound channel request.
7993 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7995 let events = nodes[1].node.get_and_clear_pending_events();
7997 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7998 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
7999 let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
8001 Err(APIError::APIMisuseError { err }) => {
8002 assert_eq!(err, "No such channel awaiting to be accepted.");
8004 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8005 Err(e) => panic!("Unexpected Error {:?}", e),
8008 _ => panic!("Unexpected event"),
8011 // Ensure that the channel wasn't closed after attempting to accept it twice.
8012 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8013 assert_eq!(accept_msg_ev.len(), 1);
8015 match accept_msg_ev[0] {
8016 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8017 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8019 _ => panic!("Unexpected event"),
8024 fn test_can_not_accept_unknown_inbound_channel() {
8025 let chanmon_cfg = create_chanmon_cfgs(2);
8026 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8027 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8028 let nodes = create_network(2, &node_cfg, &node_chanmgr);
8030 let unknown_channel_id = ChannelId::new_zero();
8031 let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
8033 Err(APIError::APIMisuseError { err }) => {
8034 assert_eq!(err, "No such channel awaiting to be accepted.");
8036 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8037 Err(e) => panic!("Unexpected Error: {:?}", e),
8042 fn test_onion_value_mpp_set_calculation() {
8043 // Test that we use the onion value `amt_to_forward` when
8044 // calculating whether we've reached the `total_msat` of an MPP
8045 // by having a routing node forward more than `amt_to_forward`
8046 // and checking that the receiving node doesn't generate
8047 // a PaymentClaimable event too early
8049 let chanmon_cfgs = create_chanmon_cfgs(node_count);
8050 let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8051 let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8052 let mut nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8054 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8055 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8056 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8057 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8059 let total_msat = 100_000;
8060 let expected_paths: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
8061 let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], total_msat);
8062 let sample_path = route.paths.pop().unwrap();
8064 let mut path_1 = sample_path.clone();
8065 path_1.hops[0].pubkey = nodes[1].node.get_our_node_id();
8066 path_1.hops[0].short_channel_id = chan_1_id;
8067 path_1.hops[1].pubkey = nodes[3].node.get_our_node_id();
8068 path_1.hops[1].short_channel_id = chan_3_id;
8069 path_1.hops[1].fee_msat = 100_000;
8070 route.paths.push(path_1);
8072 let mut path_2 = sample_path.clone();
8073 path_2.hops[0].pubkey = nodes[2].node.get_our_node_id();
8074 path_2.hops[0].short_channel_id = chan_2_id;
8075 path_2.hops[1].pubkey = nodes[3].node.get_our_node_id();
8076 path_2.hops[1].short_channel_id = chan_4_id;
8077 path_2.hops[1].fee_msat = 1_000;
8078 route.paths.push(path_2);
8081 let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
8082 let onion_session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
8083 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8084 nodes[0].node.test_send_payment_internal(&route, our_payment_hash,
8085 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8086 check_added_monitors!(nodes[0], expected_paths.len());
8088 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8089 assert_eq!(events.len(), expected_paths.len());
8092 let ev = remove_first_msg_event_to_node(&expected_paths[0][0].node.get_our_node_id(), &mut events);
8093 let mut payment_event = SendEvent::from_event(ev);
8094 let mut prev_node = &nodes[0];
8096 for (idx, &node) in expected_paths[0].iter().enumerate() {
8097 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
8099 if idx == 0 { // routing node
8100 let session_priv = [3; 32];
8101 let height = nodes[0].best_block_info().1;
8102 let session_priv = SecretKey::from_slice(&session_priv).unwrap();
8103 let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
8104 let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], 100_000,
8105 RecipientOnionFields::secret_only(our_payment_secret), height + 1, &None).unwrap();
8106 // Edit amt_to_forward to simulate the sender having set
8107 // the final amount and the routing node taking less fee
8108 if let msgs::OutboundOnionPayload::Receive { ref mut amt_msat, .. } = onion_payloads[1] {
8111 let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
8112 payment_event.msgs[0].onion_routing_packet = new_onion_packet;
8115 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
8116 check_added_monitors!(node, 0);
8117 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
8118 expect_pending_htlcs_forwardable!(node);
8121 let mut events_2 = node.node.get_and_clear_pending_msg_events();
8122 assert_eq!(events_2.len(), 1);
8123 check_added_monitors!(node, 1);
8124 payment_event = SendEvent::from_event(events_2.remove(0));
8125 assert_eq!(payment_event.msgs.len(), 1);
8127 let events_2 = node.node.get_and_clear_pending_events();
8128 assert!(events_2.is_empty());
8135 let ev = remove_first_msg_event_to_node(&expected_paths[1][0].node.get_our_node_id(), &mut events);
8136 pass_along_path(&nodes[0], expected_paths[1], 101_000, our_payment_hash.clone(), Some(our_payment_secret), ev, true, None);
8138 claim_payment_along_route(&nodes[0], expected_paths, false, our_payment_preimage);
8141 fn do_test_overshoot_mpp(msat_amounts: &[u64], total_msat: u64) {
8143 let routing_node_count = msat_amounts.len();
8144 let node_count = routing_node_count + 2;
8146 let chanmon_cfgs = create_chanmon_cfgs(node_count);
8147 let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8148 let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8149 let nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8154 // Create channels for each amount
8155 let mut expected_paths = Vec::with_capacity(routing_node_count);
8156 let mut src_chan_ids = Vec::with_capacity(routing_node_count);
8157 let mut dst_chan_ids = Vec::with_capacity(routing_node_count);
8158 for i in 0..routing_node_count {
8159 let routing_node = 2 + i;
8160 let src_chan_id = create_announced_chan_between_nodes(&nodes, src_idx, routing_node).0.contents.short_channel_id;
8161 src_chan_ids.push(src_chan_id);
8162 let dst_chan_id = create_announced_chan_between_nodes(&nodes, routing_node, dst_idx).0.contents.short_channel_id;
8163 dst_chan_ids.push(dst_chan_id);
8164 let path = vec![&nodes[routing_node], &nodes[dst_idx]];
8165 expected_paths.push(path);
8167 let expected_paths: Vec<&[&Node]> = expected_paths.iter().map(|route| route.as_slice()).collect();
8169 // Create a route for each amount
8170 let example_amount = 100000;
8171 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);
8172 let sample_path = route.paths.pop().unwrap();
8173 for i in 0..routing_node_count {
8174 let routing_node = 2 + i;
8175 let mut path = sample_path.clone();
8176 path.hops[0].pubkey = nodes[routing_node].node.get_our_node_id();
8177 path.hops[0].short_channel_id = src_chan_ids[i];
8178 path.hops[1].pubkey = nodes[dst_idx].node.get_our_node_id();
8179 path.hops[1].short_channel_id = dst_chan_ids[i];
8180 path.hops[1].fee_msat = msat_amounts[i];
8181 route.paths.push(path);
8184 // Send payment with manually set total_msat
8185 let payment_id = PaymentId(nodes[src_idx].keys_manager.backing.get_secure_random_bytes());
8186 let onion_session_privs = nodes[src_idx].node.test_add_new_pending_payment(our_payment_hash,
8187 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8188 nodes[src_idx].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[src_idx], expected_paths.len());
8192 let mut events = nodes[src_idx].node.get_and_clear_pending_msg_events();
8193 assert_eq!(events.len(), expected_paths.len());
8194 let mut amount_received = 0;
8195 for (path_idx, expected_path) in expected_paths.iter().enumerate() {
8196 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
8198 let current_path_amount = msat_amounts[path_idx];
8199 amount_received += current_path_amount;
8200 let became_claimable_now = amount_received >= total_msat && amount_received - current_path_amount < total_msat;
8201 pass_along_path(&nodes[src_idx], expected_path, amount_received, our_payment_hash.clone(), Some(our_payment_secret), ev, became_claimable_now, None);
8204 claim_payment_along_route(&nodes[src_idx], &expected_paths, false, our_payment_preimage);
8208 fn test_overshoot_mpp() {
8209 do_test_overshoot_mpp(&[100_000, 101_000], 200_000);
8210 do_test_overshoot_mpp(&[100_000, 10_000, 100_000], 200_000);
8214 fn test_simple_mpp() {
8215 // Simple test of sending a multi-path payment.
8216 let chanmon_cfgs = create_chanmon_cfgs(4);
8217 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8218 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8219 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8221 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8222 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8223 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8224 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8226 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8227 let path = route.paths[0].clone();
8228 route.paths.push(path);
8229 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
8230 route.paths[0].hops[0].short_channel_id = chan_1_id;
8231 route.paths[0].hops[1].short_channel_id = chan_3_id;
8232 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
8233 route.paths[1].hops[0].short_channel_id = chan_2_id;
8234 route.paths[1].hops[1].short_channel_id = chan_4_id;
8235 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8236 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8240 fn test_preimage_storage() {
8241 // Simple test of payment preimage storage allowing no client-side storage to claim payments
8242 let chanmon_cfgs = create_chanmon_cfgs(2);
8243 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8244 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8245 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8247 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8250 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
8251 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8252 nodes[0].node.send_payment_with_route(&route, payment_hash,
8253 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8254 check_added_monitors!(nodes[0], 1);
8255 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8256 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8257 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8258 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8260 // Note that after leaving the above scope we have no knowledge of any arguments or return
8261 // values from previous calls.
8262 expect_pending_htlcs_forwardable!(nodes[1]);
8263 let events = nodes[1].node.get_and_clear_pending_events();
8264 assert_eq!(events.len(), 1);
8266 Event::PaymentClaimable { ref purpose, .. } => {
8268 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8269 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8271 _ => panic!("expected PaymentPurpose::InvoicePayment")
8274 _ => panic!("Unexpected event"),
8279 fn test_bad_secret_hash() {
8280 // Simple test of unregistered payment hash/invalid payment secret handling
8281 let chanmon_cfgs = create_chanmon_cfgs(2);
8282 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8283 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8284 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8286 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8288 let random_payment_hash = PaymentHash([42; 32]);
8289 let random_payment_secret = PaymentSecret([43; 32]);
8290 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8291 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8293 // All the below cases should end up being handled exactly identically, so we macro the
8294 // resulting events.
8295 macro_rules! handle_unknown_invalid_payment_data {
8296 ($payment_hash: expr) => {
8297 check_added_monitors!(nodes[0], 1);
8298 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8299 let payment_event = SendEvent::from_event(events.pop().unwrap());
8300 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8301 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8303 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8304 // again to process the pending backwards-failure of the HTLC
8305 expect_pending_htlcs_forwardable!(nodes[1]);
8306 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8307 check_added_monitors!(nodes[1], 1);
8309 // We should fail the payment back
8310 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8311 match events.pop().unwrap() {
8312 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8313 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8314 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8316 _ => panic!("Unexpected event"),
8321 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8322 // Error data is the HTLC value (100,000) and current block height
8323 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8325 // Send a payment with the right payment hash but the wrong payment secret
8326 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
8327 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8328 handle_unknown_invalid_payment_data!(our_payment_hash);
8329 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8331 // Send a payment with a random payment hash, but the right payment secret
8332 nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8333 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8334 handle_unknown_invalid_payment_data!(random_payment_hash);
8335 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8337 // Send a payment with a random payment hash and random payment secret
8338 nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8339 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8340 handle_unknown_invalid_payment_data!(random_payment_hash);
8341 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8345 fn test_update_err_monitor_lockdown() {
8346 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8347 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8348 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8351 // This scenario may happen in a watchtower setup, where watchtower process a block height
8352 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8353 // commitment at same time.
8355 let chanmon_cfgs = create_chanmon_cfgs(2);
8356 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8357 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8358 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8360 // Create some initial channel
8361 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8362 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8364 // Rebalance the network to generate htlc in the two directions
8365 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8367 // Route a HTLC from node 0 to node 1 (but don't settle)
8368 let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8370 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8371 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8372 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8373 let persister = test_utils::TestPersister::new();
8376 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8377 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8378 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8379 assert!(new_monitor == *monitor);
8382 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);
8383 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8386 let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8387 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8388 // transaction lock time requirements here.
8389 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 200));
8390 watchtower.chain_monitor.block_connected(&block, 200);
8392 // Try to update ChannelMonitor
8393 nodes[1].node.claim_funds(preimage);
8394 check_added_monitors!(nodes[1], 1);
8395 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8397 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8398 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8399 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8401 let mut node_0_per_peer_lock;
8402 let mut node_0_peer_state_lock;
8403 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) {
8404 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8405 assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8406 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8407 } else { assert!(false); }
8412 // Our local monitor is in-sync and hasn't processed yet timeout
8413 check_added_monitors!(nodes[0], 1);
8414 let events = nodes[0].node.get_and_clear_pending_events();
8415 assert_eq!(events.len(), 1);
8419 fn test_concurrent_monitor_claim() {
8420 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8421 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8422 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8423 // state N+1 confirms. Alice claims output from state N+1.
8425 let chanmon_cfgs = create_chanmon_cfgs(2);
8426 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8427 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8428 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8430 // Create some initial channel
8431 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8432 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8434 // Rebalance the network to generate htlc in the two directions
8435 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8437 // Route a HTLC from node 0 to node 1 (but don't settle)
8438 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8440 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8441 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8442 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8443 let persister = test_utils::TestPersister::new();
8444 let alice_broadcaster = test_utils::TestBroadcaster::with_blocks(
8445 Arc::new(Mutex::new(nodes[0].blocks.lock().unwrap().clone())),
8447 let watchtower_alice = {
8449 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8450 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8451 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8452 assert!(new_monitor == *monitor);
8455 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &alice_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8456 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8459 let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8460 // Make Alice aware of enough blocks that it doesn't think we're violating transaction lock time
8461 // requirements here.
8462 const HTLC_TIMEOUT_BROADCAST: u32 = CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS;
8463 alice_broadcaster.blocks.lock().unwrap().resize((HTLC_TIMEOUT_BROADCAST) as usize, (block.clone(), HTLC_TIMEOUT_BROADCAST));
8464 watchtower_alice.chain_monitor.block_connected(&block, HTLC_TIMEOUT_BROADCAST);
8466 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8468 let mut txn = alice_broadcaster.txn_broadcast();
8469 assert_eq!(txn.len(), 2);
8473 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8474 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8475 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8476 let persister = test_utils::TestPersister::new();
8477 let bob_broadcaster = test_utils::TestBroadcaster::with_blocks(Arc::clone(&alice_broadcaster.blocks));
8478 let watchtower_bob = {
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), &bob_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8487 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8490 watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST - 1);
8492 // Route another payment to generate another update with still previous HTLC pending
8493 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8494 nodes[1].node.send_payment_with_route(&route, payment_hash,
8495 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8496 check_added_monitors!(nodes[1], 1);
8498 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8499 assert_eq!(updates.update_add_htlcs.len(), 1);
8500 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8502 let mut node_0_per_peer_lock;
8503 let mut node_0_peer_state_lock;
8504 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) {
8505 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8506 // Watchtower Alice should already have seen the block and reject the update
8507 assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8508 assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8509 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8510 } else { assert!(false); }
8515 // Our local monitor is in-sync and hasn't processed yet timeout
8516 check_added_monitors!(nodes[0], 1);
8518 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8519 watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST);
8521 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8524 let mut txn = bob_broadcaster.txn_broadcast();
8525 assert_eq!(txn.len(), 2);
8526 bob_state_y = txn.remove(0);
8529 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8530 let height = HTLC_TIMEOUT_BROADCAST + 1;
8531 connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
8532 check_closed_broadcast(&nodes[0], 1, true);
8533 check_closed_event!(&nodes[0], 1, ClosureReason::CommitmentTxConfirmed, false,
8534 [nodes[1].node.get_our_node_id()], 100000);
8535 watchtower_alice.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, vec![bob_state_y.clone()]), height);
8536 check_added_monitors(&nodes[0], 1);
8538 let htlc_txn = alice_broadcaster.txn_broadcast();
8539 assert_eq!(htlc_txn.len(), 2);
8540 check_spends!(htlc_txn[0], bob_state_y);
8541 // Alice doesn't clean up the old HTLC claim since it hasn't seen a conflicting spend for
8542 // it. However, she should, because it now has an invalid parent.
8543 check_spends!(htlc_txn[1], alice_state);
8548 fn test_pre_lockin_no_chan_closed_update() {
8549 // Test that if a peer closes a channel in response to a funding_created message we don't
8550 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8553 // Doing so would imply a channel monitor update before the initial channel monitor
8554 // registration, violating our API guarantees.
8556 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8557 // then opening a second channel with the same funding output as the first (which is not
8558 // rejected because the first channel does not exist in the ChannelManager) and closing it
8559 // before receiving funding_signed.
8560 let chanmon_cfgs = create_chanmon_cfgs(2);
8561 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8562 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8563 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8565 // Create an initial channel
8566 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8567 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8568 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8569 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8570 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8572 // Move the first channel through the funding flow...
8573 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8575 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8576 check_added_monitors!(nodes[0], 0);
8578 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8579 let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8580 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8581 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8582 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("Hi".to_string()) }, true,
8583 [nodes[1].node.get_our_node_id(); 2], 100000);
8587 fn test_htlc_no_detection() {
8588 // This test is a mutation to underscore the detection logic bug we had
8589 // before #653. HTLC value routed is above the remaining balance, thus
8590 // inverting HTLC and `to_remote` output. HTLC will come second and
8591 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8592 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8593 // outputs order detection for correct spending children filtring.
8595 let chanmon_cfgs = create_chanmon_cfgs(2);
8596 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8597 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8598 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8600 // Create some initial channels
8601 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8603 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8604 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8605 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8606 assert_eq!(local_txn[0].input.len(), 1);
8607 assert_eq!(local_txn[0].output.len(), 3);
8608 check_spends!(local_txn[0], chan_1.3);
8610 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8611 let block = create_dummy_block(nodes[0].best_block_hash(), 42, vec![local_txn[0].clone()]);
8612 connect_block(&nodes[0], &block);
8613 // We deliberately connect the local tx twice as this should provoke a failure calling
8614 // this test before #653 fix.
8615 chain::Listen::block_connected(&nodes[0].chain_monitor.chain_monitor, &block, nodes[0].best_block_info().1 + 1);
8616 check_closed_broadcast!(nodes[0], true);
8617 check_added_monitors!(nodes[0], 1);
8618 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
8619 connect_blocks(&nodes[0], TEST_FINAL_CLTV);
8621 let htlc_timeout = {
8622 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8623 assert_eq!(node_txn.len(), 1);
8624 assert_eq!(node_txn[0].input.len(), 1);
8625 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8626 check_spends!(node_txn[0], local_txn[0]);
8630 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![htlc_timeout.clone()]));
8631 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8632 expect_payment_failed!(nodes[0], our_payment_hash, false);
8635 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8636 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8637 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8638 // Carol, Alice would be the upstream node, and Carol the downstream.)
8640 // Steps of the test:
8641 // 1) Alice sends a HTLC to Carol through Bob.
8642 // 2) Carol doesn't settle the HTLC.
8643 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8644 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8645 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8646 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8647 // 5) Carol release the preimage to Bob off-chain.
8648 // 6) Bob claims the offered output on the broadcasted commitment.
8649 let chanmon_cfgs = create_chanmon_cfgs(3);
8650 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8651 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8652 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8654 // Create some initial channels
8655 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8656 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8658 // Steps (1) and (2):
8659 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8660 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8662 // Check that Alice's commitment transaction now contains an output for this HTLC.
8663 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8664 check_spends!(alice_txn[0], chan_ab.3);
8665 assert_eq!(alice_txn[0].output.len(), 2);
8666 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8667 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8668 assert_eq!(alice_txn.len(), 2);
8670 // Steps (3) and (4):
8671 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8672 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8673 let mut force_closing_node = 0; // Alice force-closes
8674 let mut counterparty_node = 1; // Bob if Alice force-closes
8677 if !broadcast_alice {
8678 force_closing_node = 1;
8679 counterparty_node = 0;
8681 nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8682 check_closed_broadcast!(nodes[force_closing_node], true);
8683 check_added_monitors!(nodes[force_closing_node], 1);
8684 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed, [nodes[counterparty_node].node.get_our_node_id()], 100000);
8685 if go_onchain_before_fulfill {
8686 let txn_to_broadcast = match broadcast_alice {
8687 true => alice_txn.clone(),
8688 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8690 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8691 if broadcast_alice {
8692 check_closed_broadcast!(nodes[1], true);
8693 check_added_monitors!(nodes[1], 1);
8694 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
8699 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8700 // process of removing the HTLC from their commitment transactions.
8701 nodes[2].node.claim_funds(payment_preimage);
8702 check_added_monitors!(nodes[2], 1);
8703 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8705 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8706 assert!(carol_updates.update_add_htlcs.is_empty());
8707 assert!(carol_updates.update_fail_htlcs.is_empty());
8708 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8709 assert!(carol_updates.update_fee.is_none());
8710 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8712 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8713 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
8714 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8715 if !go_onchain_before_fulfill && broadcast_alice {
8716 let events = nodes[1].node.get_and_clear_pending_msg_events();
8717 assert_eq!(events.len(), 1);
8719 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8720 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8722 _ => panic!("Unexpected event"),
8725 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8726 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8727 // Carol<->Bob's updated commitment transaction info.
8728 check_added_monitors!(nodes[1], 2);
8730 let events = nodes[1].node.get_and_clear_pending_msg_events();
8731 assert_eq!(events.len(), 2);
8732 let bob_revocation = match events[0] {
8733 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8734 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8737 _ => panic!("Unexpected event"),
8739 let bob_updates = match events[1] {
8740 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8741 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8744 _ => panic!("Unexpected event"),
8747 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8748 check_added_monitors!(nodes[2], 1);
8749 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8750 check_added_monitors!(nodes[2], 1);
8752 let events = nodes[2].node.get_and_clear_pending_msg_events();
8753 assert_eq!(events.len(), 1);
8754 let carol_revocation = match events[0] {
8755 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8756 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8759 _ => panic!("Unexpected event"),
8761 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8762 check_added_monitors!(nodes[1], 1);
8764 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8765 // here's where we put said channel's commitment tx on-chain.
8766 let mut txn_to_broadcast = alice_txn.clone();
8767 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8768 if !go_onchain_before_fulfill {
8769 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8770 // If Bob was the one to force-close, he will have already passed these checks earlier.
8771 if broadcast_alice {
8772 check_closed_broadcast!(nodes[1], true);
8773 check_added_monitors!(nodes[1], 1);
8774 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
8776 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8777 if broadcast_alice {
8778 assert_eq!(bob_txn.len(), 1);
8779 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8781 assert_eq!(bob_txn.len(), 2);
8782 check_spends!(bob_txn[0], chan_ab.3);
8787 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8788 // broadcasted commitment transaction.
8790 let script_weight = match broadcast_alice {
8791 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8792 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8794 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8795 // Bob force-closed and broadcasts the commitment transaction along with a
8796 // HTLC-output-claiming transaction.
8797 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8798 if broadcast_alice {
8799 assert_eq!(bob_txn.len(), 1);
8800 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8801 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8803 assert_eq!(bob_txn.len(), 2);
8804 check_spends!(bob_txn[1], txn_to_broadcast[0]);
8805 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8811 fn test_onchain_htlc_settlement_after_close() {
8812 do_test_onchain_htlc_settlement_after_close(true, true);
8813 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8814 do_test_onchain_htlc_settlement_after_close(true, false);
8815 do_test_onchain_htlc_settlement_after_close(false, false);
8819 fn test_duplicate_temporary_channel_id_from_different_peers() {
8820 // Tests that we can accept two different `OpenChannel` requests with the same
8821 // `temporary_channel_id`, as long as they are from different peers.
8822 let chanmon_cfgs = create_chanmon_cfgs(3);
8823 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8824 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8825 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8827 // Create an first channel channel
8828 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8829 let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8831 // Create an second channel
8832 nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None).unwrap();
8833 let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8835 // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8836 // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8837 open_chan_msg_chan_2_0.temporary_channel_id = open_chan_msg_chan_1_0.temporary_channel_id;
8839 // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8840 // `temporary_channel_id` as they are from different peers.
8841 nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
8843 let events = nodes[0].node.get_and_clear_pending_msg_events();
8844 assert_eq!(events.len(), 1);
8846 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8847 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8848 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8850 _ => panic!("Unexpected event"),
8854 nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
8856 let events = nodes[0].node.get_and_clear_pending_msg_events();
8857 assert_eq!(events.len(), 1);
8859 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8860 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
8861 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8863 _ => panic!("Unexpected event"),
8869 fn test_duplicate_chan_id() {
8870 // Test that if a given peer tries to open a channel with the same channel_id as one that is
8871 // already open we reject it and keep the old channel.
8873 // Previously, full_stack_target managed to figure out that if you tried to open two channels
8874 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8875 // the existing channel when we detect the duplicate new channel, screwing up our monitor
8876 // updating logic for the existing channel.
8877 let chanmon_cfgs = create_chanmon_cfgs(2);
8878 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8879 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8880 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8882 // Create an initial channel
8883 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8884 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8885 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8886 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()));
8888 // Try to create a second channel with the same temporary_channel_id as the first and check
8889 // that it is rejected.
8890 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8892 let events = nodes[1].node.get_and_clear_pending_msg_events();
8893 assert_eq!(events.len(), 1);
8895 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8896 // Technically, at this point, nodes[1] would be justified in thinking both the
8897 // first (valid) and second (invalid) channels are closed, given they both have
8898 // the same non-temporary channel_id. However, currently we do not, so we just
8899 // move forward with it.
8900 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8901 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8903 _ => panic!("Unexpected event"),
8907 // Move the first channel through the funding flow...
8908 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8910 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8911 check_added_monitors!(nodes[0], 0);
8913 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8914 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8916 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8917 assert_eq!(added_monitors.len(), 1);
8918 assert_eq!(added_monitors[0].0, funding_output);
8919 added_monitors.clear();
8921 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
8923 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8925 let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8926 let channel_id = funding_outpoint.to_channel_id();
8928 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8931 // First try to open a second channel with a temporary channel id equal to the txid-based one.
8932 // Technically this is allowed by the spec, but we don't support it and there's little reason
8933 // to. Still, it shouldn't cause any other issues.
8934 open_chan_msg.temporary_channel_id = channel_id;
8935 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8937 let events = nodes[1].node.get_and_clear_pending_msg_events();
8938 assert_eq!(events.len(), 1);
8940 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8941 // Technically, at this point, nodes[1] would be justified in thinking both
8942 // channels are closed, but currently we do not, so we just move forward with it.
8943 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8944 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8946 _ => panic!("Unexpected event"),
8950 // Now try to create a second channel which has a duplicate funding output.
8951 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8952 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8953 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
8954 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()));
8955 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
8957 let (_, funding_created) = {
8958 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
8959 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
8960 // Once we call `get_funding_created` the channel has a duplicate channel_id as
8961 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
8962 // try to create another channel. Instead, we drop the channel entirely here (leaving the
8963 // channelmanager in a possibly nonsense state instead).
8964 match a_peer_state.channel_by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap() {
8965 ChannelPhase::UnfundedOutboundV1(chan) => {
8966 let logger = test_utils::TestLogger::new();
8967 chan.get_funding_created(tx.clone(), funding_outpoint, &&logger).map_err(|_| ()).unwrap()
8969 _ => panic!("Unexpected ChannelPhase variant"),
8972 check_added_monitors!(nodes[0], 0);
8973 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8974 // At this point we'll look up if the channel_id is present and immediately fail the channel
8975 // without trying to persist the `ChannelMonitor`.
8976 check_added_monitors!(nodes[1], 0);
8978 // ...still, nodes[1] will reject the duplicate channel.
8980 let events = nodes[1].node.get_and_clear_pending_msg_events();
8981 assert_eq!(events.len(), 1);
8983 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8984 // Technically, at this point, nodes[1] would be justified in thinking both
8985 // channels are closed, but currently we do not, so we just move forward with it.
8986 assert_eq!(msg.channel_id, channel_id);
8987 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8989 _ => panic!("Unexpected event"),
8993 // finally, finish creating the original channel and send a payment over it to make sure
8994 // everything is functional.
8995 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8997 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8998 assert_eq!(added_monitors.len(), 1);
8999 assert_eq!(added_monitors[0].0, funding_output);
9000 added_monitors.clear();
9002 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9004 let events_4 = nodes[0].node.get_and_clear_pending_events();
9005 assert_eq!(events_4.len(), 0);
9006 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9007 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9009 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9010 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9011 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9013 send_payment(&nodes[0], &[&nodes[1]], 8000000);
9017 fn test_error_chans_closed() {
9018 // Test that we properly handle error messages, closing appropriate channels.
9020 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9021 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9022 // we can test various edge cases around it to ensure we don't regress.
9023 let chanmon_cfgs = create_chanmon_cfgs(3);
9024 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9025 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9026 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9028 // Create some initial channels
9029 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9030 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9031 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
9033 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9034 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9035 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9037 // Closing a channel from a different peer has no effect
9038 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9039 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9041 // Closing one channel doesn't impact others
9042 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9043 check_added_monitors!(nodes[0], 1);
9044 check_closed_broadcast!(nodes[0], false);
9045 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) },
9046 [nodes[1].node.get_our_node_id()], 100000);
9047 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9048 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9049 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);
9050 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);
9052 // A null channel ID should close all channels
9053 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9054 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: ChannelId::new_zero(), data: "ERR".to_owned() });
9055 check_added_monitors!(nodes[0], 2);
9056 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) },
9057 [nodes[1].node.get_our_node_id(); 2], 100000);
9058 let events = nodes[0].node.get_and_clear_pending_msg_events();
9059 assert_eq!(events.len(), 2);
9061 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9062 assert_eq!(msg.contents.flags & 2, 2);
9064 _ => panic!("Unexpected event"),
9067 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9068 assert_eq!(msg.contents.flags & 2, 2);
9070 _ => panic!("Unexpected event"),
9072 // Note that at this point users of a standard PeerHandler will end up calling
9073 // peer_disconnected.
9074 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9075 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9077 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9078 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9079 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9083 fn test_invalid_funding_tx() {
9084 // Test that we properly handle invalid funding transactions sent to us from a peer.
9086 // Previously, all other major lightning implementations had failed to properly sanitize
9087 // funding transactions from their counterparties, leading to a multi-implementation critical
9088 // security vulnerability (though we always sanitized properly, we've previously had
9089 // un-released crashes in the sanitization process).
9091 // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9092 // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9093 // gave up on it. We test this here by generating such a transaction.
9094 let chanmon_cfgs = create_chanmon_cfgs(2);
9095 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9096 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9097 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9099 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9100 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()));
9101 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()));
9103 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9105 // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9106 // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9107 // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9109 let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9110 let wit_program_script: Script = wit_program.into();
9111 for output in tx.output.iter_mut() {
9112 // Make the confirmed funding transaction have a bogus script_pubkey
9113 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9116 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9117 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()));
9118 check_added_monitors!(nodes[1], 1);
9119 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9121 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()));
9122 check_added_monitors!(nodes[0], 1);
9123 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9125 let events_1 = nodes[0].node.get_and_clear_pending_events();
9126 assert_eq!(events_1.len(), 0);
9128 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9129 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9130 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9132 let expected_err = "funding tx had wrong script/value or output index";
9133 confirm_transaction_at(&nodes[1], &tx, 1);
9134 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() },
9135 [nodes[0].node.get_our_node_id()], 100000);
9136 check_added_monitors!(nodes[1], 1);
9137 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9138 assert_eq!(events_2.len(), 1);
9139 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9140 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9141 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9142 assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9143 } else { panic!(); }
9144 } else { panic!(); }
9145 assert_eq!(nodes[1].node.list_channels().len(), 0);
9147 // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9148 // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9149 // as its not 32 bytes long.
9150 let mut spend_tx = Transaction {
9151 version: 2i32, lock_time: PackedLockTime::ZERO,
9152 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9153 previous_output: BitcoinOutPoint {
9157 script_sig: Script::new(),
9158 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9159 witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9161 output: vec![TxOut {
9163 script_pubkey: Script::new(),
9166 check_spends!(spend_tx, tx);
9167 mine_transaction(&nodes[1], &spend_tx);
9171 fn test_coinbase_funding_tx() {
9172 // Miners are able to fund channels directly from coinbase transactions, however
9173 // by consensus rules, outputs of a coinbase transaction are encumbered by a 100
9174 // block maturity timelock. To ensure that a (non-0conf) channel like this is enforceable
9175 // on-chain, the minimum depth is updated to 100 blocks for coinbase funding transactions.
9177 // Note that 0conf channels with coinbase funding transactions are unaffected and are
9178 // immediately operational after opening.
9179 let chanmon_cfgs = create_chanmon_cfgs(2);
9180 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9181 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9182 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9184 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9185 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9187 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9188 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9190 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9192 // Create the coinbase funding transaction.
9193 let (temporary_channel_id, tx, _) = create_coinbase_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9195 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9196 check_added_monitors!(nodes[0], 0);
9197 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9199 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9200 check_added_monitors!(nodes[1], 1);
9201 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9203 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9205 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
9206 check_added_monitors!(nodes[0], 1);
9208 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9209 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
9211 // Starting at height 0, we "confirm" the coinbase at height 1.
9212 confirm_transaction_at(&nodes[0], &tx, 1);
9213 // We connect 98 more blocks to have 99 confirmations for the coinbase transaction.
9214 connect_blocks(&nodes[0], COINBASE_MATURITY - 2);
9215 // Check that we have no pending message events (we have not queued a `channel_ready` yet).
9216 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
9217 // Now connect one more block which results in 100 confirmations of the coinbase transaction.
9218 connect_blocks(&nodes[0], 1);
9219 // There should now be a `channel_ready` which can be handled.
9220 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()));
9222 confirm_transaction_at(&nodes[1], &tx, 1);
9223 connect_blocks(&nodes[1], COINBASE_MATURITY - 2);
9224 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9225 connect_blocks(&nodes[1], 1);
9226 expect_channel_ready_event(&nodes[1], &nodes[0].node.get_our_node_id());
9227 create_chan_between_nodes_with_value_confirm_second(&nodes[0], &nodes[1]);
9230 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9231 // In the first version of the chain::Confirm interface, after a refactor was made to not
9232 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9233 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9234 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9235 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9236 // spending transaction until height N+1 (or greater). This was due to the way
9237 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9238 // spending transaction at the height the input transaction was confirmed at, not whether we
9239 // should broadcast a spending transaction at the current height.
9240 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9241 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9242 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9243 // until we learned about an additional block.
9245 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9246 // aren't broadcasting transactions too early (ie not broadcasting them at all).
9247 let chanmon_cfgs = create_chanmon_cfgs(3);
9248 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9249 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9250 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9251 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9253 create_announced_chan_between_nodes(&nodes, 0, 1);
9254 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
9255 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9256 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
9257 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9259 nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9260 check_closed_broadcast!(nodes[1], true);
9261 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[2].node.get_our_node_id()], 100000);
9262 check_added_monitors!(nodes[1], 1);
9263 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9264 assert_eq!(node_txn.len(), 1);
9266 let conf_height = nodes[1].best_block_info().1;
9267 if !test_height_before_timelock {
9268 connect_blocks(&nodes[1], 24 * 6);
9270 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9271 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9272 if test_height_before_timelock {
9273 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9274 // generate any events or broadcast any transactions
9275 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9276 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9278 // We should broadcast an HTLC transaction spending our funding transaction first
9279 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9280 assert_eq!(spending_txn.len(), 2);
9281 assert_eq!(spending_txn[0].txid(), node_txn[0].txid());
9282 check_spends!(spending_txn[1], node_txn[0]);
9283 // We should also generate a SpendableOutputs event with the to_self output (as its
9285 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9286 assert_eq!(descriptor_spend_txn.len(), 1);
9288 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9289 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9290 // additional block built on top of the current chain.
9291 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9292 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9293 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 }]);
9294 check_added_monitors!(nodes[1], 1);
9296 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9297 assert!(updates.update_add_htlcs.is_empty());
9298 assert!(updates.update_fulfill_htlcs.is_empty());
9299 assert_eq!(updates.update_fail_htlcs.len(), 1);
9300 assert!(updates.update_fail_malformed_htlcs.is_empty());
9301 assert!(updates.update_fee.is_none());
9302 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9303 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9304 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9309 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9310 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9311 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9314 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9315 let chanmon_cfgs = create_chanmon_cfgs(2);
9316 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9317 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9318 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9320 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9322 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9323 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
9324 let route = get_route!(nodes[0], payment_params, 10_000).unwrap();
9326 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9329 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9330 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9331 check_added_monitors!(nodes[0], 1);
9332 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9333 assert_eq!(events.len(), 1);
9334 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9335 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9336 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9338 expect_pending_htlcs_forwardable!(nodes[1]);
9339 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9342 // Note that we use a different PaymentId here to allow us to duplicativly pay
9343 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9344 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9345 check_added_monitors!(nodes[0], 1);
9346 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9347 assert_eq!(events.len(), 1);
9348 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9349 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9350 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9351 // At this point, nodes[1] would notice it has too much value for the payment. It will
9352 // assume the second is a privacy attack (no longer particularly relevant
9353 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9354 // the first HTLC delivered above.
9357 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9358 nodes[1].node.process_pending_htlc_forwards();
9360 if test_for_second_fail_panic {
9361 // Now we go fail back the first HTLC from the user end.
9362 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9364 let expected_destinations = vec![
9365 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9366 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9368 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], expected_destinations);
9369 nodes[1].node.process_pending_htlc_forwards();
9371 check_added_monitors!(nodes[1], 1);
9372 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9373 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9375 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9376 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9377 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9379 let failure_events = nodes[0].node.get_and_clear_pending_events();
9380 assert_eq!(failure_events.len(), 4);
9381 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9382 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9383 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9384 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9386 // Let the second HTLC fail and claim the first
9387 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9388 nodes[1].node.process_pending_htlc_forwards();
9390 check_added_monitors!(nodes[1], 1);
9391 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9392 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9393 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9395 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9397 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9402 fn test_dup_htlc_second_fail_panic() {
9403 // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9404 // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9405 // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9406 // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9407 do_test_dup_htlc_second_rejected(true);
9411 fn test_dup_htlc_second_rejected() {
9412 // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9413 // simply reject the second HTLC but are still able to claim the first HTLC.
9414 do_test_dup_htlc_second_rejected(false);
9418 fn test_inconsistent_mpp_params() {
9419 // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9420 // such HTLC and allow the second to stay.
9421 let chanmon_cfgs = create_chanmon_cfgs(4);
9422 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9423 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9424 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9426 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9427 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9428 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9429 let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9431 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9432 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
9433 let mut route = get_route!(nodes[0], payment_params, 15_000_000).unwrap();
9434 assert_eq!(route.paths.len(), 2);
9435 route.paths.sort_by(|path_a, _| {
9436 // Sort the path so that the path through nodes[1] comes first
9437 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9438 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9441 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9443 let cur_height = nodes[0].best_block_info().1;
9444 let payment_id = PaymentId([42; 32]);
9446 let session_privs = {
9447 // We create a fake route here so that we start with three pending HTLCs, which we'll
9448 // ultimately have, just not right away.
9449 let mut dup_route = route.clone();
9450 dup_route.paths.push(route.paths[1].clone());
9451 nodes[0].node.test_add_new_pending_payment(our_payment_hash,
9452 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &dup_route).unwrap()
9454 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
9455 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9456 &None, session_privs[0]).unwrap();
9457 check_added_monitors!(nodes[0], 1);
9460 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9461 assert_eq!(events.len(), 1);
9462 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9464 assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9466 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9467 RecipientOnionFields::secret_only(our_payment_secret), 14_000_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9468 check_added_monitors!(nodes[0], 1);
9471 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9472 assert_eq!(events.len(), 1);
9473 let payment_event = SendEvent::from_event(events.pop().unwrap());
9475 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9476 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9478 expect_pending_htlcs_forwardable!(nodes[2]);
9479 check_added_monitors!(nodes[2], 1);
9481 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9482 assert_eq!(events.len(), 1);
9483 let payment_event = SendEvent::from_event(events.pop().unwrap());
9485 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9486 check_added_monitors!(nodes[3], 0);
9487 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9489 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9490 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9491 // post-payment_secrets) and fail back the new HTLC.
9493 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9494 nodes[3].node.process_pending_htlc_forwards();
9495 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9496 nodes[3].node.process_pending_htlc_forwards();
9498 check_added_monitors!(nodes[3], 1);
9500 let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9501 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9502 commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9504 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 }]);
9505 check_added_monitors!(nodes[2], 1);
9507 let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9508 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9509 commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9511 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9513 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9514 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9515 &None, session_privs[2]).unwrap();
9516 check_added_monitors!(nodes[0], 1);
9518 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9519 assert_eq!(events.len(), 1);
9520 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9522 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9523 expect_payment_sent(&nodes[0], our_payment_preimage, Some(None), true, true);
9527 fn test_double_partial_claim() {
9528 // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9529 // time out, the sender resends only some of the MPP parts, then the user processes the
9530 // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9532 let chanmon_cfgs = create_chanmon_cfgs(4);
9533 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9534 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9535 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9537 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9538 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9539 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9540 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9542 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9543 assert_eq!(route.paths.len(), 2);
9544 route.paths.sort_by(|path_a, _| {
9545 // Sort the path so that the path through nodes[1] comes first
9546 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9547 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9550 send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9551 // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9552 // amount of time to respond to.
9554 // Connect some blocks to time out the payment
9555 connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9556 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9558 let failed_destinations = vec![
9559 HTLCDestination::FailedPayment { payment_hash },
9560 HTLCDestination::FailedPayment { payment_hash },
9562 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9564 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
9566 // nodes[1] now retries one of the two paths...
9567 nodes[0].node.send_payment_with_route(&route, payment_hash,
9568 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9569 check_added_monitors!(nodes[0], 2);
9571 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9572 assert_eq!(events.len(), 2);
9573 let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
9574 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9576 // At this point nodes[3] has received one half of the payment, and the user goes to handle
9577 // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9578 nodes[3].node.claim_funds(payment_preimage);
9579 check_added_monitors!(nodes[3], 0);
9580 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9583 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9584 #[derive(Clone, Copy, PartialEq)]
9585 enum ExposureEvent {
9586 /// Breach occurs at HTLC forwarding (see `send_htlc`)
9588 /// Breach occurs at HTLC reception (see `update_add_htlc`)
9590 /// Breach occurs at outbound update_fee (see `send_update_fee`)
9591 AtUpdateFeeOutbound,
9594 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool, multiplier_dust_limit: bool) {
9595 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9598 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9599 // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9600 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9601 // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9602 // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9603 // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9604 // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9605 // might be available again for HTLC processing once the dust bandwidth has cleared up.
9607 let chanmon_cfgs = create_chanmon_cfgs(2);
9608 let mut config = test_default_channel_config();
9609 config.channel_config.max_dust_htlc_exposure = if multiplier_dust_limit {
9610 // Default test fee estimator rate is 253 sat/kw, so we set the multiplier to 5_000_000 / 253
9611 // to get roughly the same initial value as the default setting when this test was
9612 // originally written.
9613 MaxDustHTLCExposure::FeeRateMultiplier(5_000_000 / 253)
9614 } else { MaxDustHTLCExposure::FixedLimitMsat(5_000_000) }; // initial default setting value
9615 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9616 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9617 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9619 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9620 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9621 open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9622 open_channel.max_accepted_htlcs = 60;
9624 open_channel.dust_limit_satoshis = 546;
9626 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9627 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9628 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9630 let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
9632 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9635 let mut node_0_per_peer_lock;
9636 let mut node_0_peer_state_lock;
9637 match get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, temporary_channel_id) {
9638 ChannelPhase::UnfundedOutboundV1(chan) => {
9639 chan.context.holder_dust_limit_satoshis = 546;
9641 _ => panic!("Unexpected ChannelPhase variant"),
9645 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9646 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()));
9647 check_added_monitors!(nodes[1], 1);
9648 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9650 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()));
9651 check_added_monitors!(nodes[0], 1);
9652 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9654 let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9655 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9656 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9658 // Fetch a route in advance as we will be unable to once we're unable to send.
9659 let (mut route, payment_hash, _, payment_secret) =
9660 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
9662 let (dust_buffer_feerate, max_dust_htlc_exposure_msat) = {
9663 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9664 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9665 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
9666 (chan.context().get_dust_buffer_feerate(None) as u64,
9667 chan.context().get_max_dust_htlc_exposure_msat(&LowerBoundedFeeEstimator(nodes[0].fee_estimator)))
9669 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;
9670 let dust_outbound_htlc_on_holder_tx: u64 = max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9672 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;
9673 let dust_inbound_htlc_on_holder_tx: u64 = max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9675 let dust_htlc_on_counterparty_tx: u64 = 4;
9676 let dust_htlc_on_counterparty_tx_msat: u64 = max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9679 if dust_outbound_balance {
9680 // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9681 // Outbound dust balance: 4372 sats
9682 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9683 for _ in 0..dust_outbound_htlc_on_holder_tx {
9684 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9685 nodes[0].node.send_payment_with_route(&route, payment_hash,
9686 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9689 // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9690 // Inbound dust balance: 4372 sats
9691 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9692 for _ in 0..dust_inbound_htlc_on_holder_tx {
9693 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9697 if dust_outbound_balance {
9698 // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9699 // Outbound dust balance: 5000 sats
9700 for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9701 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9702 nodes[0].node.send_payment_with_route(&route, payment_hash,
9703 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9706 // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9707 // Inbound dust balance: 5000 sats
9708 for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9709 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9714 if exposure_breach_event == ExposureEvent::AtHTLCForward {
9715 route.paths[0].hops.last_mut().unwrap().fee_msat =
9716 if on_holder_tx { dust_outbound_htlc_on_holder_tx_msat } else { dust_htlc_on_counterparty_tx_msat + 1 };
9717 // With default dust exposure: 5000 sats
9719 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9720 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9721 ), true, APIError::ChannelUnavailable { .. }, {});
9723 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9724 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9725 ), true, APIError::ChannelUnavailable { .. }, {});
9727 } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9728 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 });
9729 nodes[1].node.send_payment_with_route(&route, payment_hash,
9730 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9731 check_added_monitors!(nodes[1], 1);
9732 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9733 assert_eq!(events.len(), 1);
9734 let payment_event = SendEvent::from_event(events.remove(0));
9735 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9736 // With default dust exposure: 5000 sats
9738 // Outbound dust balance: 6399 sats
9739 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9740 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9741 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on holder commitment tx", if dust_outbound_balance { dust_outbound_overflow } else { dust_inbound_overflow }, max_dust_htlc_exposure_msat), 1);
9743 // Outbound dust balance: 5200 sats
9744 nodes[0].logger.assert_log("lightning::ln::channel".to_string(),
9745 format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx",
9746 dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx - 1) + dust_htlc_on_counterparty_tx_msat + 4,
9747 max_dust_htlc_exposure_msat), 1);
9749 } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9750 route.paths[0].hops.last_mut().unwrap().fee_msat = 2_500_000;
9751 // For the multiplier dust exposure limit, since it scales with feerate,
9752 // we need to add a lot of HTLCs that will become dust at the new feerate
9753 // to cross the threshold.
9755 let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[1], Some(1_000), None);
9756 nodes[0].node.send_payment_with_route(&route, payment_hash,
9757 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9760 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9761 *feerate_lock = *feerate_lock * 10;
9763 nodes[0].node.timer_tick_occurred();
9764 check_added_monitors!(nodes[0], 1);
9765 nodes[0].logger.assert_log_contains("lightning::ln::channel", "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure", 1);
9768 let _ = nodes[0].node.get_and_clear_pending_msg_events();
9769 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9770 added_monitors.clear();
9773 fn do_test_max_dust_htlc_exposure_by_threshold_type(multiplier_dust_limit: bool) {
9774 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true, multiplier_dust_limit);
9775 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true, multiplier_dust_limit);
9776 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true, multiplier_dust_limit);
9777 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false, multiplier_dust_limit);
9778 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false, multiplier_dust_limit);
9779 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false, multiplier_dust_limit);
9780 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true, multiplier_dust_limit);
9781 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false, multiplier_dust_limit);
9782 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true, multiplier_dust_limit);
9783 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false, multiplier_dust_limit);
9784 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false, multiplier_dust_limit);
9785 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true, multiplier_dust_limit);
9789 fn test_max_dust_htlc_exposure() {
9790 do_test_max_dust_htlc_exposure_by_threshold_type(false);
9791 do_test_max_dust_htlc_exposure_by_threshold_type(true);
9795 fn test_non_final_funding_tx() {
9796 let chanmon_cfgs = create_chanmon_cfgs(2);
9797 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9798 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9799 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9801 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9802 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9803 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9804 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9805 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
9807 let best_height = nodes[0].node.best_block.read().unwrap().height();
9809 let chan_id = *nodes[0].network_chan_count.borrow();
9810 let events = nodes[0].node.get_and_clear_pending_events();
9811 let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
9812 assert_eq!(events.len(), 1);
9813 let mut tx = match events[0] {
9814 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9815 // Timelock the transaction _beyond_ the best client height + 1.
9816 Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 2), input: vec![input], output: vec![TxOut {
9817 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9820 _ => panic!("Unexpected event"),
9822 // Transaction should fail as it's evaluated as non-final for propagation.
9823 match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
9824 Err(APIError::APIMisuseError { err }) => {
9825 assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
9830 // However, transaction should be accepted if it's in a +1 headroom from best block.
9831 tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
9832 assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
9833 get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9837 fn accept_busted_but_better_fee() {
9838 // If a peer sends us a fee update that is too low, but higher than our previous channel
9839 // feerate, we should accept it. In the future we may want to consider closing the channel
9840 // later, but for now we only accept the update.
9841 let mut chanmon_cfgs = create_chanmon_cfgs(2);
9842 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9843 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9844 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9846 create_chan_between_nodes(&nodes[0], &nodes[1]);
9848 // Set nodes[1] to expect 5,000 sat/kW.
9850 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
9851 *feerate_lock = 5000;
9854 // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
9856 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9857 *feerate_lock = 1000;
9859 nodes[0].node.timer_tick_occurred();
9860 check_added_monitors!(nodes[0], 1);
9862 let events = nodes[0].node.get_and_clear_pending_msg_events();
9863 assert_eq!(events.len(), 1);
9865 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9866 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9867 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9869 _ => panic!("Unexpected event"),
9872 // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
9875 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9876 *feerate_lock = 2000;
9878 nodes[0].node.timer_tick_occurred();
9879 check_added_monitors!(nodes[0], 1);
9881 let events = nodes[0].node.get_and_clear_pending_msg_events();
9882 assert_eq!(events.len(), 1);
9884 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9885 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9886 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9888 _ => panic!("Unexpected event"),
9891 // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
9894 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9895 *feerate_lock = 1000;
9897 nodes[0].node.timer_tick_occurred();
9898 check_added_monitors!(nodes[0], 1);
9900 let events = nodes[0].node.get_and_clear_pending_msg_events();
9901 assert_eq!(events.len(), 1);
9903 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
9904 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9905 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
9906 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000 (- 250)".to_owned() },
9907 [nodes[0].node.get_our_node_id()], 100000);
9908 check_closed_broadcast!(nodes[1], true);
9909 check_added_monitors!(nodes[1], 1);
9911 _ => panic!("Unexpected event"),
9915 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
9916 let mut chanmon_cfgs = create_chanmon_cfgs(2);
9917 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9918 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9919 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9920 let min_final_cltv_expiry_delta = 120;
9921 let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
9922 min_final_cltv_expiry_delta - 2 };
9923 let recv_value = 100_000;
9925 create_chan_between_nodes(&nodes[0], &nodes[1]);
9927 let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), final_cltv_expiry_delta as u32);
9928 let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
9929 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
9930 Some(recv_value), Some(min_final_cltv_expiry_delta));
9931 (payment_hash, payment_preimage, payment_secret)
9933 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
9934 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
9936 let route = get_route!(nodes[0], payment_parameters, recv_value).unwrap();
9937 nodes[0].node.send_payment_with_route(&route, payment_hash,
9938 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9939 check_added_monitors!(nodes[0], 1);
9940 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9941 assert_eq!(events.len(), 1);
9942 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9943 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9944 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9945 expect_pending_htlcs_forwardable!(nodes[1]);
9948 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
9949 None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
9951 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9953 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
9955 check_added_monitors!(nodes[1], 1);
9957 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9958 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
9959 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
9961 expect_payment_failed!(nodes[0], payment_hash, true);
9966 fn test_payment_with_custom_min_cltv_expiry_delta() {
9967 do_payment_with_custom_min_final_cltv_expiry(false, false);
9968 do_payment_with_custom_min_final_cltv_expiry(false, true);
9969 do_payment_with_custom_min_final_cltv_expiry(true, false);
9970 do_payment_with_custom_min_final_cltv_expiry(true, true);
9974 fn test_disconnects_peer_awaiting_response_ticks() {
9975 // Tests that nodes which are awaiting on a response critical for channel responsiveness
9976 // disconnect their counterparty after `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
9977 let mut chanmon_cfgs = create_chanmon_cfgs(2);
9978 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9979 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9980 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9982 // Asserts a disconnect event is queued to the user.
9983 let check_disconnect_event = |node: &Node, should_disconnect: bool| {
9984 let disconnect_event = node.node.get_and_clear_pending_msg_events().iter().find_map(|event|
9985 if let MessageSendEvent::HandleError { action, .. } = event {
9986 if let msgs::ErrorAction::DisconnectPeerWithWarning { .. } = action {
9995 assert_eq!(disconnect_event.is_some(), should_disconnect);
9998 // Fires timer ticks ensuring we only attempt to disconnect peers after reaching
9999 // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10000 let check_disconnect = |node: &Node| {
10001 // No disconnect without any timer ticks.
10002 check_disconnect_event(node, false);
10004 // No disconnect with 1 timer tick less than required.
10005 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS - 1 {
10006 node.node.timer_tick_occurred();
10007 check_disconnect_event(node, false);
10010 // Disconnect after reaching the required ticks.
10011 node.node.timer_tick_occurred();
10012 check_disconnect_event(node, true);
10014 // Disconnect again on the next tick if the peer hasn't been disconnected yet.
10015 node.node.timer_tick_occurred();
10016 check_disconnect_event(node, true);
10019 create_chan_between_nodes(&nodes[0], &nodes[1]);
10021 // We'll start by performing a fee update with Alice (nodes[0]) on the channel.
10022 *nodes[0].fee_estimator.sat_per_kw.lock().unwrap() *= 2;
10023 nodes[0].node.timer_tick_occurred();
10024 check_added_monitors!(&nodes[0], 1);
10025 let alice_fee_update = get_htlc_update_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
10026 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), alice_fee_update.update_fee.as_ref().unwrap());
10027 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &alice_fee_update.commitment_signed);
10028 check_added_monitors!(&nodes[1], 1);
10030 // This will prompt Bob (nodes[1]) to respond with his `CommitmentSigned` and `RevokeAndACK`.
10031 let (bob_revoke_and_ack, bob_commitment_signed) = get_revoke_commit_msgs!(&nodes[1], nodes[0].node.get_our_node_id());
10032 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revoke_and_ack);
10033 check_added_monitors!(&nodes[0], 1);
10034 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_commitment_signed);
10035 check_added_monitors(&nodes[0], 1);
10037 // Alice then needs to send her final `RevokeAndACK` to complete the commitment dance. We
10038 // pretend Bob hasn't received the message and check whether he'll disconnect Alice after
10039 // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10040 let alice_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
10041 check_disconnect(&nodes[1]);
10043 // Now, we'll reconnect them to test awaiting a `ChannelReestablish` message.
10045 // Note that since the commitment dance didn't complete above, Alice is expected to resend her
10046 // final `RevokeAndACK` to Bob to complete it.
10047 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
10048 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10049 let bob_init = msgs::Init {
10050 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
10052 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &bob_init, true).unwrap();
10053 let alice_init = msgs::Init {
10054 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
10056 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &alice_init, true).unwrap();
10058 // Upon reconnection, Alice sends her `ChannelReestablish` to Bob. Alice, however, hasn't
10059 // received Bob's yet, so she should disconnect him after reaching
10060 // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10061 let alice_channel_reestablish = get_event_msg!(
10062 nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id()
10064 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &alice_channel_reestablish);
10065 check_disconnect(&nodes[0]);
10067 // Bob now sends his `ChannelReestablish` to Alice to resume the channel and consider it "live".
10068 let bob_channel_reestablish = nodes[1].node.get_and_clear_pending_msg_events().iter().find_map(|event|
10069 if let MessageSendEvent::SendChannelReestablish { node_id, msg } = event {
10070 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
10076 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bob_channel_reestablish);
10078 // Sanity check that Alice won't disconnect Bob since she's no longer waiting for any messages.
10079 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
10080 nodes[0].node.timer_tick_occurred();
10081 check_disconnect_event(&nodes[0], false);
10084 // However, Bob is still waiting on Alice's `RevokeAndACK`, so he should disconnect her after
10085 // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10086 check_disconnect(&nodes[1]);
10088 // Finally, have Bob process the last message.
10089 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &alice_revoke_and_ack);
10090 check_added_monitors(&nodes[1], 1);
10092 // At this point, neither node should attempt to disconnect each other, since they aren't
10093 // waiting on any messages.
10094 for node in &nodes {
10095 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
10096 node.node.timer_tick_occurred();
10097 check_disconnect_event(node, false);
10103 fn test_remove_expired_outbound_unfunded_channels() {
10104 let chanmon_cfgs = create_chanmon_cfgs(2);
10105 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10106 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10107 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10109 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10110 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10111 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10112 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10113 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10115 let events = nodes[0].node.get_and_clear_pending_events();
10116 assert_eq!(events.len(), 1);
10118 Event::FundingGenerationReady { .. } => (),
10119 _ => panic!("Unexpected event"),
10122 // Asserts the outbound channel has been removed from a nodes[0]'s peer state map.
10123 let check_outbound_channel_existence = |should_exist: bool| {
10124 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
10125 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
10126 assert_eq!(chan_lock.channel_by_id.contains_key(&temp_channel_id), should_exist);
10129 // Channel should exist without any timer ticks.
10130 check_outbound_channel_existence(true);
10132 // Channel should exist with 1 timer tick less than required.
10133 for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS - 1 {
10134 nodes[0].node.timer_tick_occurred();
10135 check_outbound_channel_existence(true)
10138 // Remove channel after reaching the required ticks.
10139 nodes[0].node.timer_tick_occurred();
10140 check_outbound_channel_existence(false);
10142 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
10143 assert_eq!(msg_events.len(), 1);
10144 match msg_events[0] {
10145 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
10146 assert_eq!(msg.data, "Force-closing pending channel due to timeout awaiting establishment handshake");
10148 _ => panic!("Unexpected event"),
10150 check_closed_event(&nodes[0], 1, ClosureReason::HolderForceClosed, false, &[nodes[1].node.get_our_node_id()], 100000);
10154 fn test_remove_expired_inbound_unfunded_channels() {
10155 let chanmon_cfgs = create_chanmon_cfgs(2);
10156 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10157 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10158 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10160 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10161 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10162 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10163 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10164 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10166 let events = nodes[0].node.get_and_clear_pending_events();
10167 assert_eq!(events.len(), 1);
10169 Event::FundingGenerationReady { .. } => (),
10170 _ => panic!("Unexpected event"),
10173 // Asserts the inbound channel has been removed from a nodes[1]'s peer state map.
10174 let check_inbound_channel_existence = |should_exist: bool| {
10175 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
10176 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
10177 assert_eq!(chan_lock.channel_by_id.contains_key(&temp_channel_id), should_exist);
10180 // Channel should exist without any timer ticks.
10181 check_inbound_channel_existence(true);
10183 // Channel should exist with 1 timer tick less than required.
10184 for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS - 1 {
10185 nodes[1].node.timer_tick_occurred();
10186 check_inbound_channel_existence(true)
10189 // Remove channel after reaching the required ticks.
10190 nodes[1].node.timer_tick_occurred();
10191 check_inbound_channel_existence(false);
10193 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
10194 assert_eq!(msg_events.len(), 1);
10195 match msg_events[0] {
10196 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
10197 assert_eq!(msg.data, "Force-closing pending channel due to timeout awaiting establishment handshake");
10199 _ => panic!("Unexpected event"),
10201 check_closed_event(&nodes[1], 1, ClosureReason::HolderForceClosed, false, &[nodes[0].node.get_our_node_id()], 100000);
10204 fn do_test_multi_post_event_actions(do_reload: bool) {
10205 // Tests handling multiple post-Event actions at once.
10206 // There is specific code in ChannelManager to handle channels where multiple post-Event
10207 // `ChannelMonitorUpdates` are pending at once. This test exercises that code.
10209 // Specifically, we test calling `get_and_clear_pending_events` while there are two
10210 // PaymentSents from different channels and one channel has two pending `ChannelMonitorUpdate`s
10211 // - one from an RAA and one from an inbound commitment_signed.
10212 let chanmon_cfgs = create_chanmon_cfgs(3);
10213 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10214 let (persister, chain_monitor);
10215 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10216 let nodes_0_deserialized;
10217 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10219 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
10220 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 0, 2).2;
10222 send_payment(&nodes[0], &[&nodes[1]], 1_000_000);
10223 send_payment(&nodes[0], &[&nodes[2]], 1_000_000);
10225 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
10226 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[2]], 1_000_000);
10228 nodes[1].node.claim_funds(our_payment_preimage);
10229 check_added_monitors!(nodes[1], 1);
10230 expect_payment_claimed!(nodes[1], our_payment_hash, 1_000_000);
10232 nodes[2].node.claim_funds(payment_preimage_2);
10233 check_added_monitors!(nodes[2], 1);
10234 expect_payment_claimed!(nodes[2], payment_hash_2, 1_000_000);
10236 for dest in &[1, 2] {
10237 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[*dest], nodes[0].node.get_our_node_id());
10238 nodes[0].node.handle_update_fulfill_htlc(&nodes[*dest].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
10239 commitment_signed_dance!(nodes[0], nodes[*dest], htlc_fulfill_updates.commitment_signed, false);
10240 check_added_monitors(&nodes[0], 0);
10243 let (route, payment_hash_3, _, payment_secret_3) =
10244 get_route_and_payment_hash!(nodes[1], nodes[0], 100_000);
10245 let payment_id = PaymentId(payment_hash_3.0);
10246 nodes[1].node.send_payment_with_route(&route, payment_hash_3,
10247 RecipientOnionFields::secret_only(payment_secret_3), payment_id).unwrap();
10248 check_added_monitors(&nodes[1], 1);
10250 let send_event = SendEvent::from_node(&nodes[1]);
10251 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event.msgs[0]);
10252 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_event.commitment_msg);
10253 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
10256 let nodes_0_serialized = nodes[0].node.encode();
10257 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
10258 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_2).encode();
10259 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);
10261 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10262 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10264 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
10265 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[2]));
10268 let events = nodes[0].node.get_and_clear_pending_events();
10269 assert_eq!(events.len(), 4);
10270 if let Event::PaymentSent { payment_preimage, .. } = events[0] {
10271 assert!(payment_preimage == our_payment_preimage || payment_preimage == payment_preimage_2);
10272 } else { panic!(); }
10273 if let Event::PaymentSent { payment_preimage, .. } = events[1] {
10274 assert!(payment_preimage == our_payment_preimage || payment_preimage == payment_preimage_2);
10275 } else { panic!(); }
10276 if let Event::PaymentPathSuccessful { .. } = events[2] {} else { panic!(); }
10277 if let Event::PaymentPathSuccessful { .. } = events[3] {} else { panic!(); }
10279 // After the events are processed, the ChannelMonitorUpdates will be released and, upon their
10280 // completion, we'll respond to nodes[1] with an RAA + CS.
10281 get_revoke_commit_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
10282 check_added_monitors(&nodes[0], 3);
10286 fn test_multi_post_event_actions() {
10287 do_test_multi_post_event_actions(true);
10288 do_test_multi_post_event_actions(false);