1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
15 use crate::chain::{ChannelMonitorUpdateStatus, Confirm, Listen, Watch};
16 use crate::chain::chaininterface::LowerBoundedFeeEstimator;
17 use crate::chain::channelmonitor;
18 use crate::chain::channelmonitor::{CLOSED_CHANNEL_UPDATE_ID, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
19 use crate::chain::transaction::OutPoint;
20 use crate::sign::{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,
1040 maybe_announced_channel: true,
1042 hops.push(RouteHop {
1043 pubkey: nodes[3].node.get_our_node_id(),
1044 node_features: NodeFeatures::empty(),
1045 short_channel_id: chan_3.0.contents.short_channel_id,
1046 channel_features: ChannelFeatures::empty(),
1048 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32,
1049 maybe_announced_channel: true,
1051 hops.push(RouteHop {
1052 pubkey: nodes[1].node.get_our_node_id(),
1053 node_features: nodes[1].node.node_features(),
1054 short_channel_id: chan_4.0.contents.short_channel_id,
1055 channel_features: nodes[1].node.channel_features(),
1057 cltv_expiry_delta: TEST_FINAL_CLTV,
1058 maybe_announced_channel: true,
1060 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;
1061 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;
1062 let payment_preimage_1 = send_along_route(&nodes[1],
1063 Route { paths: vec![Path { hops, blinded_tail: None }], route_params: None },
1064 &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1066 let mut hops = Vec::with_capacity(3);
1067 hops.push(RouteHop {
1068 pubkey: nodes[3].node.get_our_node_id(),
1069 node_features: NodeFeatures::empty(),
1070 short_channel_id: chan_4.0.contents.short_channel_id,
1071 channel_features: ChannelFeatures::empty(),
1073 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32,
1074 maybe_announced_channel: true,
1076 hops.push(RouteHop {
1077 pubkey: nodes[2].node.get_our_node_id(),
1078 node_features: NodeFeatures::empty(),
1079 short_channel_id: chan_3.0.contents.short_channel_id,
1080 channel_features: ChannelFeatures::empty(),
1082 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32,
1083 maybe_announced_channel: true,
1085 hops.push(RouteHop {
1086 pubkey: nodes[1].node.get_our_node_id(),
1087 node_features: nodes[1].node.node_features(),
1088 short_channel_id: chan_2.0.contents.short_channel_id,
1089 channel_features: nodes[1].node.channel_features(),
1091 cltv_expiry_delta: TEST_FINAL_CLTV,
1092 maybe_announced_channel: true,
1094 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;
1095 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;
1096 let payment_hash_2 = send_along_route(&nodes[1],
1097 Route { paths: vec![Path { hops, blinded_tail: None }], route_params: None },
1098 &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1100 // Claim the rebalances...
1101 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1102 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1104 // Close down the channels...
1105 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1106 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1107 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
1108 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1109 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[2].node.get_our_node_id()], 100000);
1110 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1111 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1112 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure, [nodes[3].node.get_our_node_id()], 100000);
1113 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure, [nodes[2].node.get_our_node_id()], 100000);
1114 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1115 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[3].node.get_our_node_id()], 100000);
1116 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1120 fn holding_cell_htlc_counting() {
1121 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1122 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1123 // commitment dance rounds.
1124 let chanmon_cfgs = create_chanmon_cfgs(3);
1125 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1126 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1127 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1128 create_announced_chan_between_nodes(&nodes, 0, 1);
1129 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1131 // Fetch a route in advance as we will be unable to once we're unable to send.
1132 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1134 let mut payments = Vec::new();
1136 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1137 nodes[1].node.send_payment_with_route(&route, payment_hash,
1138 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1139 payments.push((payment_preimage, payment_hash));
1141 check_added_monitors!(nodes[1], 1);
1143 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1144 assert_eq!(events.len(), 1);
1145 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1146 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1148 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1149 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1152 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, payment_hash_1,
1153 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)
1154 ), true, APIError::ChannelUnavailable { .. }, {});
1155 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1158 // This should also be true if we try to forward a payment.
1159 let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1161 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1162 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1163 check_added_monitors!(nodes[0], 1);
1166 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1167 assert_eq!(events.len(), 1);
1168 let payment_event = SendEvent::from_event(events.pop().unwrap());
1169 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1171 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1172 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1173 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1174 // fails), the second will process the resulting failure and fail the HTLC backward.
1175 expect_pending_htlcs_forwardable!(nodes[1]);
1176 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 }]);
1177 check_added_monitors!(nodes[1], 1);
1179 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1180 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1181 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1183 expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1185 // Now forward all the pending HTLCs and claim them back
1186 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1187 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1188 check_added_monitors!(nodes[2], 1);
1190 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1191 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1192 check_added_monitors!(nodes[1], 1);
1193 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1195 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1196 check_added_monitors!(nodes[1], 1);
1197 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1199 for ref update in as_updates.update_add_htlcs.iter() {
1200 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1202 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1203 check_added_monitors!(nodes[2], 1);
1204 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1205 check_added_monitors!(nodes[2], 1);
1206 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1208 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1209 check_added_monitors!(nodes[1], 1);
1210 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1211 check_added_monitors!(nodes[1], 1);
1212 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1214 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1215 check_added_monitors!(nodes[2], 1);
1217 expect_pending_htlcs_forwardable!(nodes[2]);
1219 let events = nodes[2].node.get_and_clear_pending_events();
1220 assert_eq!(events.len(), payments.len());
1221 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1223 &Event::PaymentClaimable { ref payment_hash, .. } => {
1224 assert_eq!(*payment_hash, *hash);
1226 _ => panic!("Unexpected event"),
1230 for (preimage, _) in payments.drain(..) {
1231 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1234 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1238 fn duplicate_htlc_test() {
1239 // Test that we accept duplicate payment_hash HTLCs across the network and that
1240 // claiming/failing them are all separate and don't affect each other
1241 let chanmon_cfgs = create_chanmon_cfgs(6);
1242 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1243 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1244 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1246 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1247 create_announced_chan_between_nodes(&nodes, 0, 3);
1248 create_announced_chan_between_nodes(&nodes, 1, 3);
1249 create_announced_chan_between_nodes(&nodes, 2, 3);
1250 create_announced_chan_between_nodes(&nodes, 3, 4);
1251 create_announced_chan_between_nodes(&nodes, 3, 5);
1253 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1255 *nodes[0].network_payment_count.borrow_mut() -= 1;
1256 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1258 *nodes[0].network_payment_count.borrow_mut() -= 1;
1259 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1261 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1262 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1263 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1267 fn test_duplicate_htlc_different_direction_onchain() {
1268 // Test that ChannelMonitor doesn't generate 2 preimage txn
1269 // when we have 2 HTLCs with same preimage that go across a node
1270 // in opposite directions, even with the same payment secret.
1271 let chanmon_cfgs = create_chanmon_cfgs(2);
1272 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1273 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1274 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1276 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1279 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1281 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1283 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1284 let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
1285 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1287 // Provide preimage to node 0 by claiming payment
1288 nodes[0].node.claim_funds(payment_preimage);
1289 expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1290 check_added_monitors!(nodes[0], 1);
1292 // Broadcast node 1 commitment txn
1293 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1295 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1296 let mut has_both_htlcs = 0; // check htlcs match ones committed
1297 for outp in remote_txn[0].output.iter() {
1298 if outp.value == 800_000 / 1000 {
1299 has_both_htlcs += 1;
1300 } else if outp.value == 900_000 / 1000 {
1301 has_both_htlcs += 1;
1304 assert_eq!(has_both_htlcs, 2);
1306 mine_transaction(&nodes[0], &remote_txn[0]);
1307 check_added_monitors!(nodes[0], 1);
1308 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
1309 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
1311 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1312 assert_eq!(claim_txn.len(), 3);
1314 check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1315 check_spends!(claim_txn[1], remote_txn[0]);
1316 check_spends!(claim_txn[2], remote_txn[0]);
1317 let preimage_tx = &claim_txn[0];
1318 let (preimage_bump_tx, timeout_tx) = if claim_txn[1].input[0].previous_output == preimage_tx.input[0].previous_output {
1319 (&claim_txn[1], &claim_txn[2])
1321 (&claim_txn[2], &claim_txn[1])
1324 assert_eq!(preimage_tx.input.len(), 1);
1325 assert_eq!(preimage_bump_tx.input.len(), 1);
1327 assert_eq!(preimage_tx.input.len(), 1);
1328 assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1329 assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1331 assert_eq!(timeout_tx.input.len(), 1);
1332 assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1333 check_spends!(timeout_tx, remote_txn[0]);
1334 assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1336 let events = nodes[0].node.get_and_clear_pending_msg_events();
1337 assert_eq!(events.len(), 3);
1340 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1341 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1342 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1343 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1345 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, .. } } => {
1346 assert!(update_add_htlcs.is_empty());
1347 assert!(update_fail_htlcs.is_empty());
1348 assert_eq!(update_fulfill_htlcs.len(), 1);
1349 assert!(update_fail_malformed_htlcs.is_empty());
1350 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1352 _ => panic!("Unexpected event"),
1358 fn test_basic_channel_reserve() {
1359 let chanmon_cfgs = create_chanmon_cfgs(2);
1360 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1361 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1362 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1363 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1365 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1366 let channel_reserve = chan_stat.channel_reserve_msat;
1368 // The 2* and +1 are for the fee spike reserve.
1369 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));
1370 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1371 let (mut route, our_payment_hash, _, our_payment_secret) =
1372 get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
1373 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1374 let err = nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1375 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1377 PaymentSendFailure::AllFailedResendSafe(ref fails) => {
1378 if let &APIError::ChannelUnavailable { .. } = &fails[0] {}
1379 else { panic!("Unexpected error variant"); }
1381 _ => panic!("Unexpected error variant"),
1383 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1385 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1389 fn test_fee_spike_violation_fails_htlc() {
1390 let chanmon_cfgs = create_chanmon_cfgs(2);
1391 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1392 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1393 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1394 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1396 let (mut route, payment_hash, _, payment_secret) =
1397 get_route_and_payment_hash!(nodes[0], nodes[1], 3460000);
1398 route.paths[0].hops[0].fee_msat += 1;
1399 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1400 let secp_ctx = Secp256k1::new();
1401 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1403 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1405 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1406 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1407 3460001, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1408 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1409 let msg = msgs::UpdateAddHTLC {
1412 amount_msat: htlc_msat,
1413 payment_hash: payment_hash,
1414 cltv_expiry: htlc_cltv,
1415 onion_routing_packet: onion_packet,
1416 skimmed_fee_msat: None,
1419 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1421 // Now manually create the commitment_signed message corresponding to the update_add
1422 // nodes[0] just sent. In the code for construction of this message, "local" refers
1423 // to the sender of the message, and "remote" refers to the receiver.
1425 let feerate_per_kw = get_feerate!(nodes[0], nodes[1], chan.2);
1427 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1429 // Get the TestChannelSigner for each channel, which will be used to (1) get the keys
1430 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1431 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1432 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1433 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1434 let local_chan = chan_lock.channel_by_id.get(&chan.2).map(
1435 |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
1436 ).flatten().unwrap();
1437 let chan_signer = local_chan.get_signer();
1438 // Make the signer believe we validated another commitment, so we can release the secret
1439 chan_signer.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
1441 let pubkeys = chan_signer.as_ref().pubkeys();
1442 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1443 chan_signer.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1444 chan_signer.as_ref().get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1445 chan_signer.as_ref().pubkeys().funding_pubkey)
1447 let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1448 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
1449 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
1450 let remote_chan = chan_lock.channel_by_id.get(&chan.2).map(
1451 |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
1452 ).flatten().unwrap();
1453 let chan_signer = remote_chan.get_signer();
1454 let pubkeys = chan_signer.as_ref().pubkeys();
1455 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1456 chan_signer.as_ref().get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1457 chan_signer.as_ref().pubkeys().funding_pubkey)
1460 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1461 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1462 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
1464 // Build the remote commitment transaction so we can sign it, and then later use the
1465 // signature for the commitment_signed message.
1466 let local_chan_balance = 1313;
1468 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1470 amount_msat: 3460001,
1471 cltv_expiry: htlc_cltv,
1473 transaction_output_index: Some(1),
1476 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1479 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1480 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1481 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).map(
1482 |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
1483 ).flatten().unwrap();
1484 let local_chan_signer = local_chan.get_signer();
1485 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1489 local_funding, remote_funding,
1490 commit_tx_keys.clone(),
1492 &mut vec![(accepted_htlc_info, ())],
1493 &local_chan.context.channel_transaction_parameters.as_counterparty_broadcastable()
1495 local_chan_signer.as_ecdsa().unwrap().sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1498 let commit_signed_msg = msgs::CommitmentSigned {
1501 htlc_signatures: res.1,
1503 partial_signature_with_nonce: None,
1506 // Send the commitment_signed message to the nodes[1].
1507 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1508 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1510 // Send the RAA to nodes[1].
1511 let raa_msg = msgs::RevokeAndACK {
1513 per_commitment_secret: local_secret,
1514 next_per_commitment_point: next_local_point,
1516 next_local_nonce: None,
1518 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1520 let events = nodes[1].node.get_and_clear_pending_msg_events();
1521 assert_eq!(events.len(), 1);
1522 // Make sure the HTLC failed in the way we expect.
1524 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1525 assert_eq!(update_fail_htlcs.len(), 1);
1526 update_fail_htlcs[0].clone()
1528 _ => panic!("Unexpected event"),
1530 nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1531 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", raa_msg.channel_id), 1);
1533 check_added_monitors!(nodes[1], 2);
1537 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1538 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1539 // Set the fee rate for the channel very high, to the point where the fundee
1540 // sending any above-dust amount would result in a channel reserve violation.
1541 // In this test we check that we would be prevented from sending an HTLC in
1543 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1544 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1545 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1546 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1547 let default_config = UserConfig::default();
1548 let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1550 let mut push_amt = 100_000_000;
1551 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1553 push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1555 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1557 // Fetch a route in advance as we will be unable to once we're unable to send.
1558 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1559 // Sending exactly enough to hit the reserve amount should be accepted
1560 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1561 route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1564 // However one more HTLC should be significantly over the reserve amount and fail.
1565 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1566 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1567 ), true, APIError::ChannelUnavailable { .. }, {});
1568 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1572 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1573 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1574 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1575 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1576 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1577 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1578 let default_config = UserConfig::default();
1579 let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1581 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1582 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1583 // transaction fee with 0 HTLCs (183 sats)).
1584 let mut push_amt = 100_000_000;
1585 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1586 push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1587 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1589 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1590 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1591 route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1594 let (mut route, payment_hash, _, payment_secret) =
1595 get_route_and_payment_hash!(nodes[1], nodes[0], 1000);
1596 route.paths[0].hops[0].fee_msat = 700_000;
1597 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1598 let secp_ctx = Secp256k1::new();
1599 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1600 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1601 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1602 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1603 700_000, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1604 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1605 let msg = msgs::UpdateAddHTLC {
1607 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1608 amount_msat: htlc_msat,
1609 payment_hash: payment_hash,
1610 cltv_expiry: htlc_cltv,
1611 onion_routing_packet: onion_packet,
1612 skimmed_fee_msat: None,
1615 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1616 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1617 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);
1618 assert_eq!(nodes[0].node.list_channels().len(), 0);
1619 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1620 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1621 check_added_monitors!(nodes[0], 1);
1622 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() },
1623 [nodes[1].node.get_our_node_id()], 100000);
1627 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1628 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1629 // calculating our commitment transaction fee (this was previously broken).
1630 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1631 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1633 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1634 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1635 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1636 let default_config = UserConfig::default();
1637 let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1639 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1640 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1641 // transaction fee with 0 HTLCs (183 sats)).
1642 let mut push_amt = 100_000_000;
1643 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1644 push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1645 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt);
1647 let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1648 + feerate_per_kw as u64 * htlc_success_tx_weight(&channel_type_features) / 1000 * 1000 - 1;
1649 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1650 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1651 // commitment transaction fee.
1652 route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1654 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1655 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1656 route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1659 // One more than the dust amt should fail, however.
1660 let (mut route, our_payment_hash, _, our_payment_secret) =
1661 get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt);
1662 route.paths[0].hops[0].fee_msat += 1;
1663 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1664 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1665 ), true, APIError::ChannelUnavailable { .. }, {});
1669 fn test_chan_init_feerate_unaffordability() {
1670 // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1671 // channel reserve and feerate requirements.
1672 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1673 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1674 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1675 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1676 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1677 let default_config = UserConfig::default();
1678 let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1680 // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1682 let mut push_amt = 100_000_000;
1683 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1684 assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1685 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1687 // During open, we don't have a "counterparty channel reserve" to check against, so that
1688 // requirement only comes into play on the open_channel handling side.
1689 push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1690 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1691 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1692 open_channel_msg.push_msat += 1;
1693 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
1695 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1696 assert_eq!(msg_events.len(), 1);
1697 match msg_events[0] {
1698 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1699 assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1701 _ => panic!("Unexpected event"),
1706 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1707 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1708 // calculating our counterparty's commitment transaction fee (this was previously broken).
1709 let chanmon_cfgs = create_chanmon_cfgs(2);
1710 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1711 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1712 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1713 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000);
1715 let payment_amt = 46000; // Dust amount
1716 // In the previous code, these first four payments would succeed.
1717 route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1718 route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1719 route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1720 route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1722 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1723 route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1724 route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1725 route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1726 route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1727 route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1729 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1730 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1731 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1732 route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1736 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1737 let chanmon_cfgs = create_chanmon_cfgs(3);
1738 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1739 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1740 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1741 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1742 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
1745 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1746 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1747 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
1748 let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
1750 // Add a 2* and +1 for the fee spike reserve.
1751 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features);
1752 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;
1753 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1755 // Add a pending HTLC.
1756 let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1757 let payment_event_1 = {
1758 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1759 RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1760 check_added_monitors!(nodes[0], 1);
1762 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1763 assert_eq!(events.len(), 1);
1764 SendEvent::from_event(events.remove(0))
1766 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1768 // Attempt to trigger a channel reserve violation --> payment failure.
1769 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, &channel_type_features);
1770 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;
1771 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1772 let mut route_2 = route_1.clone();
1773 route_2.paths[0].hops.last_mut().unwrap().fee_msat = amt_msat_2;
1775 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1776 let secp_ctx = Secp256k1::new();
1777 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1778 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1779 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1780 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
1781 &route_2.paths[0], recv_value_2, RecipientOnionFields::spontaneous_empty(), cur_height, &None).unwrap();
1782 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1).unwrap();
1783 let msg = msgs::UpdateAddHTLC {
1786 amount_msat: htlc_msat + 1,
1787 payment_hash: our_payment_hash_1,
1788 cltv_expiry: htlc_cltv,
1789 onion_routing_packet: onion_packet,
1790 skimmed_fee_msat: None,
1793 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1794 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1795 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1796 assert_eq!(nodes[1].node.list_channels().len(), 1);
1797 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1798 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1799 check_added_monitors!(nodes[1], 1);
1800 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() },
1801 [nodes[0].node.get_our_node_id()], 100000);
1805 fn test_inbound_outbound_capacity_is_not_zero() {
1806 let chanmon_cfgs = create_chanmon_cfgs(2);
1807 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1808 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1809 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1810 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1811 let channels0 = node_chanmgrs[0].list_channels();
1812 let channels1 = node_chanmgrs[1].list_channels();
1813 let default_config = UserConfig::default();
1814 assert_eq!(channels0.len(), 1);
1815 assert_eq!(channels1.len(), 1);
1817 let reserve = get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1818 assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1819 assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1821 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1822 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1825 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, channel_type_features: &ChannelTypeFeatures) -> u64 {
1826 (commitment_tx_base_weight(channel_type_features) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1830 fn test_channel_reserve_holding_cell_htlcs() {
1831 let chanmon_cfgs = create_chanmon_cfgs(3);
1832 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1833 // When this test was written, the default base fee floated based on the HTLC count.
1834 // It is now fixed, so we simply set the fee to the expected value here.
1835 let mut config = test_default_channel_config();
1836 config.channel_config.forwarding_fee_base_msat = 239;
1837 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1838 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1839 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001);
1840 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001);
1842 let mut stat01 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1843 let mut stat11 = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
1845 let mut stat12 = get_channel_value_stat!(nodes[1], nodes[2], chan_2.2);
1846 let mut stat22 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
1848 macro_rules! expect_forward {
1850 let mut events = $node.node.get_and_clear_pending_msg_events();
1851 assert_eq!(events.len(), 1);
1852 check_added_monitors!($node, 1);
1853 let payment_event = SendEvent::from_event(events.remove(0));
1858 let feemsat = 239; // set above
1859 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1860 let feerate = get_feerate!(nodes[0], nodes[1], chan_1.2);
1861 let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_1.2);
1863 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1865 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1867 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1868 .with_bolt11_features(nodes[2].node.invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1869 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, recv_value_0);
1870 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1871 assert!(route.paths[0].hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1873 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1874 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1875 ), true, APIError::ChannelUnavailable { .. }, {});
1876 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1879 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1880 // nodes[0]'s wealth
1882 let amt_msat = recv_value_0 + total_fee_msat;
1883 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1884 // Also, ensure that each payment has enough to be over the dust limit to
1885 // ensure it'll be included in each commit tx fee calculation.
1886 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, &channel_type_features);
1887 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1888 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1892 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1893 .with_bolt11_features(nodes[2].node.invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1894 let route = get_route!(nodes[0], payment_params, recv_value_0).unwrap();
1895 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1896 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1898 let (stat01_, stat11_, stat12_, stat22_) = (
1899 get_channel_value_stat!(nodes[0], nodes[1], chan_1.2),
1900 get_channel_value_stat!(nodes[1], nodes[0], chan_1.2),
1901 get_channel_value_stat!(nodes[1], nodes[2], chan_2.2),
1902 get_channel_value_stat!(nodes[2], nodes[1], chan_2.2),
1905 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1906 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1907 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1908 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1909 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1912 // adding pending output.
1913 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1914 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1915 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1916 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1917 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1918 // cases where 1 msat over X amount will cause a payment failure, but anything less than
1919 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1920 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1921 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1923 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features);
1924 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1925 let amt_msat_1 = recv_value_1 + total_fee_msat;
1927 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);
1928 let payment_event_1 = {
1929 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1930 RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1931 check_added_monitors!(nodes[0], 1);
1933 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1934 assert_eq!(events.len(), 1);
1935 SendEvent::from_event(events.remove(0))
1937 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1939 // channel reserve test with htlc pending output > 0
1940 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1942 let mut route = route_1.clone();
1943 route.paths[0].hops.last_mut().unwrap().fee_msat = recv_value_2 + 1;
1944 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
1945 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1946 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1947 ), true, APIError::ChannelUnavailable { .. }, {});
1948 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1951 // split the rest to test holding cell
1952 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, &channel_type_features);
1953 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1954 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1955 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1957 let stat = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1958 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);
1961 // now see if they go through on both sides
1962 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);
1963 // but this will stuck in the holding cell
1964 nodes[0].node.send_payment_with_route(&route_21, our_payment_hash_21,
1965 RecipientOnionFields::secret_only(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
1966 check_added_monitors!(nodes[0], 0);
1967 let events = nodes[0].node.get_and_clear_pending_events();
1968 assert_eq!(events.len(), 0);
1970 // test with outbound holding cell amount > 0
1972 let (mut route, our_payment_hash, _, our_payment_secret) =
1973 get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22);
1974 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1975 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1976 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1977 ), true, APIError::ChannelUnavailable { .. }, {});
1978 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1981 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);
1982 // this will also stuck in the holding cell
1983 nodes[0].node.send_payment_with_route(&route_22, our_payment_hash_22,
1984 RecipientOnionFields::secret_only(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
1985 check_added_monitors!(nodes[0], 0);
1986 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1987 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1989 // flush the pending htlc
1990 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1991 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1992 check_added_monitors!(nodes[1], 1);
1994 // the pending htlc should be promoted to committed
1995 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1996 check_added_monitors!(nodes[0], 1);
1997 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1999 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
2000 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2001 // No commitment_signed so get_event_msg's assert(len == 1) passes
2002 check_added_monitors!(nodes[0], 1);
2004 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
2005 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2006 check_added_monitors!(nodes[1], 1);
2008 expect_pending_htlcs_forwardable!(nodes[1]);
2010 let ref payment_event_11 = expect_forward!(nodes[1]);
2011 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
2012 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
2014 expect_pending_htlcs_forwardable!(nodes[2]);
2015 expect_payment_claimable!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
2017 // flush the htlcs in the holding cell
2018 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
2019 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
2020 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
2021 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
2022 expect_pending_htlcs_forwardable!(nodes[1]);
2024 let ref payment_event_3 = expect_forward!(nodes[1]);
2025 assert_eq!(payment_event_3.msgs.len(), 2);
2026 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
2027 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
2029 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2030 expect_pending_htlcs_forwardable!(nodes[2]);
2032 let events = nodes[2].node.get_and_clear_pending_events();
2033 assert_eq!(events.len(), 2);
2035 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2036 assert_eq!(our_payment_hash_21, *payment_hash);
2037 assert_eq!(recv_value_21, amount_msat);
2038 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2039 assert_eq!(via_channel_id, Some(chan_2.2));
2041 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2042 assert!(payment_preimage.is_none());
2043 assert_eq!(our_payment_secret_21, *payment_secret);
2045 _ => panic!("expected PaymentPurpose::InvoicePayment")
2048 _ => panic!("Unexpected event"),
2051 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2052 assert_eq!(our_payment_hash_22, *payment_hash);
2053 assert_eq!(recv_value_22, amount_msat);
2054 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2055 assert_eq!(via_channel_id, Some(chan_2.2));
2057 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2058 assert!(payment_preimage.is_none());
2059 assert_eq!(our_payment_secret_22, *payment_secret);
2061 _ => panic!("expected PaymentPurpose::InvoicePayment")
2064 _ => panic!("Unexpected event"),
2067 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2068 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2069 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2071 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, &channel_type_features);
2072 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2073 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2075 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
2076 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);
2077 let stat0 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
2078 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2079 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2081 let stat2 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
2082 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2086 fn channel_reserve_in_flight_removes() {
2087 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2088 // can send to its counterparty, but due to update ordering, the other side may not yet have
2089 // considered those HTLCs fully removed.
2090 // This tests that we don't count HTLCs which will not be included in the next remote
2091 // commitment transaction towards the reserve value (as it implies no commitment transaction
2092 // will be generated which violates the remote reserve value).
2093 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2095 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2096 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2097 // you only consider the value of the first HTLC, it may not),
2098 // * start routing a third HTLC from A to B,
2099 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2100 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2101 // * deliver the first fulfill from B
2102 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2104 // * deliver A's response CS and RAA.
2105 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2106 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
2107 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2108 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2109 let chanmon_cfgs = create_chanmon_cfgs(2);
2110 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2111 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2112 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2113 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2115 let b_chan_values = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
2116 // Route the first two HTLCs.
2117 let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2118 let (payment_preimage_1, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2119 let (payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2121 // Start routing the third HTLC (this is just used to get everyone in the right state).
2122 let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2124 nodes[0].node.send_payment_with_route(&route, payment_hash_3,
2125 RecipientOnionFields::secret_only(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2126 check_added_monitors!(nodes[0], 1);
2127 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2128 assert_eq!(events.len(), 1);
2129 SendEvent::from_event(events.remove(0))
2132 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2133 // initial fulfill/CS.
2134 nodes[1].node.claim_funds(payment_preimage_1);
2135 expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2136 check_added_monitors!(nodes[1], 1);
2137 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2139 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2140 // remove the second HTLC when we send the HTLC back from B to A.
2141 nodes[1].node.claim_funds(payment_preimage_2);
2142 expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2143 check_added_monitors!(nodes[1], 1);
2144 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2146 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2147 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2148 check_added_monitors!(nodes[0], 1);
2149 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2150 expect_payment_sent(&nodes[0], payment_preimage_1, None, false, false);
2152 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2153 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2154 check_added_monitors!(nodes[1], 1);
2155 // B is already AwaitingRAA, so cant generate a CS here
2156 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2158 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2159 check_added_monitors!(nodes[1], 1);
2160 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2162 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2163 check_added_monitors!(nodes[0], 1);
2164 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2166 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2167 check_added_monitors!(nodes[1], 1);
2168 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2170 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2171 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2172 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2173 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2174 // on-chain as necessary).
2175 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2176 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2177 check_added_monitors!(nodes[0], 1);
2178 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2179 expect_payment_sent(&nodes[0], payment_preimage_2, None, false, false);
2181 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2182 check_added_monitors!(nodes[1], 1);
2183 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2185 expect_pending_htlcs_forwardable!(nodes[1]);
2186 expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2188 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2189 // resolve the second HTLC from A's point of view.
2190 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2191 check_added_monitors!(nodes[0], 1);
2192 expect_payment_path_successful!(nodes[0]);
2193 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2195 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2196 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2197 let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2199 nodes[1].node.send_payment_with_route(&route, payment_hash_4,
2200 RecipientOnionFields::secret_only(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2201 check_added_monitors!(nodes[1], 1);
2202 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2203 assert_eq!(events.len(), 1);
2204 SendEvent::from_event(events.remove(0))
2207 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2208 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2209 check_added_monitors!(nodes[0], 1);
2210 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2212 // Now just resolve all the outstanding messages/HTLCs for completeness...
2214 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2215 check_added_monitors!(nodes[1], 1);
2216 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2218 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2219 check_added_monitors!(nodes[1], 1);
2221 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2222 check_added_monitors!(nodes[0], 1);
2223 expect_payment_path_successful!(nodes[0]);
2224 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2226 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2227 check_added_monitors!(nodes[1], 1);
2228 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2230 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2231 check_added_monitors!(nodes[0], 1);
2233 expect_pending_htlcs_forwardable!(nodes[0]);
2234 expect_payment_claimable!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2236 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2237 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2241 fn channel_monitor_network_test() {
2242 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2243 // tests that ChannelMonitor is able to recover from various states.
2244 let chanmon_cfgs = create_chanmon_cfgs(5);
2245 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2246 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2247 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2249 // Create some initial channels
2250 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2251 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2252 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2253 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
2255 // Make sure all nodes are at the same starting height
2256 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2257 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2258 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2259 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2260 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2262 // Rebalance the network a bit by relaying one payment through all the channels...
2263 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2264 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2265 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2266 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2268 // Simple case with no pending HTLCs:
2269 nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2270 check_added_monitors!(nodes[1], 1);
2271 check_closed_broadcast!(nodes[1], true);
2273 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2274 assert_eq!(node_txn.len(), 1);
2275 mine_transaction(&nodes[0], &node_txn[0]);
2276 check_added_monitors!(nodes[0], 1);
2277 test_txn_broadcast(&nodes[0], &chan_1, Some(node_txn[0].clone()), HTLCType::NONE);
2279 check_closed_broadcast!(nodes[0], true);
2280 assert_eq!(nodes[0].node.list_channels().len(), 0);
2281 assert_eq!(nodes[1].node.list_channels().len(), 1);
2282 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2283 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[0].node.get_our_node_id()], 100000);
2285 // One pending HTLC is discarded by the force-close:
2286 let (payment_preimage_1, payment_hash_1, ..) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2288 // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2289 // broadcasted until we reach the timelock time).
2290 nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2291 check_closed_broadcast!(nodes[1], true);
2292 check_added_monitors!(nodes[1], 1);
2294 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2295 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2296 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2297 mine_transaction(&nodes[2], &node_txn[0]);
2298 check_added_monitors!(nodes[2], 1);
2299 test_txn_broadcast(&nodes[2], &chan_2, Some(node_txn[0].clone()), HTLCType::NONE);
2301 check_closed_broadcast!(nodes[2], true);
2302 assert_eq!(nodes[1].node.list_channels().len(), 0);
2303 assert_eq!(nodes[2].node.list_channels().len(), 1);
2304 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[2].node.get_our_node_id()], 100000);
2305 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2307 macro_rules! claim_funds {
2308 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2310 $node.node.claim_funds($preimage);
2311 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2312 check_added_monitors!($node, 1);
2314 let events = $node.node.get_and_clear_pending_msg_events();
2315 assert_eq!(events.len(), 1);
2317 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2318 assert!(update_add_htlcs.is_empty());
2319 assert!(update_fail_htlcs.is_empty());
2320 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2322 _ => panic!("Unexpected event"),
2328 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2329 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2330 nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2331 check_added_monitors!(nodes[2], 1);
2332 check_closed_broadcast!(nodes[2], true);
2333 let node2_commitment_txid;
2335 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2336 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2337 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2338 node2_commitment_txid = node_txn[0].txid();
2340 // Claim the payment on nodes[3], giving it knowledge of the preimage
2341 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2342 mine_transaction(&nodes[3], &node_txn[0]);
2343 check_added_monitors!(nodes[3], 1);
2344 check_preimage_claim(&nodes[3], &node_txn);
2346 check_closed_broadcast!(nodes[3], true);
2347 assert_eq!(nodes[2].node.list_channels().len(), 0);
2348 assert_eq!(nodes[3].node.list_channels().len(), 1);
2349 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed, [nodes[3].node.get_our_node_id()], 100000);
2350 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
2352 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2353 // confusing us in the following tests.
2354 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2356 // One pending HTLC to time out:
2357 let (payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2358 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2361 let (close_chan_update_1, close_chan_update_2) = {
2362 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2363 let events = nodes[3].node.get_and_clear_pending_msg_events();
2364 assert_eq!(events.len(), 2);
2365 let close_chan_update_1 = match events[0] {
2366 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2369 _ => panic!("Unexpected event"),
2372 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2373 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2375 _ => panic!("Unexpected event"),
2377 check_added_monitors!(nodes[3], 1);
2379 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2381 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2382 node_txn.retain(|tx| {
2383 if tx.input[0].previous_output.txid == node2_commitment_txid {
2389 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2391 // Claim the payment on nodes[4], giving it knowledge of the preimage
2392 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2394 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2395 let events = nodes[4].node.get_and_clear_pending_msg_events();
2396 assert_eq!(events.len(), 2);
2397 let close_chan_update_2 = match events[0] {
2398 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2401 _ => panic!("Unexpected event"),
2404 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2405 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2407 _ => panic!("Unexpected event"),
2409 check_added_monitors!(nodes[4], 1);
2410 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2411 check_closed_event!(nodes[4], 1, ClosureReason::HolderForceClosed, [nodes[3].node.get_our_node_id()], 100000);
2413 mine_transaction(&nodes[4], &node_txn[0]);
2414 check_preimage_claim(&nodes[4], &node_txn);
2415 (close_chan_update_1, close_chan_update_2)
2417 nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2418 nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2419 assert_eq!(nodes[3].node.list_channels().len(), 0);
2420 assert_eq!(nodes[4].node.list_channels().len(), 0);
2422 assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2423 Ok(ChannelMonitorUpdateStatus::Completed));
2424 check_closed_event!(nodes[3], 1, ClosureReason::HolderForceClosed, [nodes[4].node.get_our_node_id()], 100000);
2428 fn test_justice_tx_htlc_timeout() {
2429 // Test justice txn built on revoked HTLC-Timeout tx, against both sides
2430 let mut alice_config = UserConfig::default();
2431 alice_config.channel_handshake_config.announced_channel = true;
2432 alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2433 alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2434 let mut bob_config = UserConfig::default();
2435 bob_config.channel_handshake_config.announced_channel = true;
2436 bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2437 bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2438 let user_cfgs = [Some(alice_config), Some(bob_config)];
2439 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2440 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2441 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2442 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2443 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2444 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2445 // Create some new channels:
2446 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
2448 // A pending HTLC which will be revoked:
2449 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2450 // Get the will-be-revoked local txn from nodes[0]
2451 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2452 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2453 assert_eq!(revoked_local_txn[0].input.len(), 1);
2454 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2455 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2456 assert_eq!(revoked_local_txn[1].input.len(), 1);
2457 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2458 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2459 // Revoke the old state
2460 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2463 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2465 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2466 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2467 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2468 check_spends!(node_txn[0], revoked_local_txn[0]);
2469 node_txn.swap_remove(0);
2471 check_added_monitors!(nodes[1], 1);
2472 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2473 test_txn_broadcast(&nodes[1], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2475 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2476 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2477 // Verify broadcast of revoked HTLC-timeout
2478 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2479 check_added_monitors!(nodes[0], 1);
2480 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2481 // Broadcast revoked HTLC-timeout on node 1
2482 mine_transaction(&nodes[1], &node_txn[1]);
2483 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2485 get_announce_close_broadcast_events(&nodes, 0, 1);
2486 assert_eq!(nodes[0].node.list_channels().len(), 0);
2487 assert_eq!(nodes[1].node.list_channels().len(), 0);
2491 fn test_justice_tx_htlc_success() {
2492 // Test justice txn built on revoked HTLC-Success tx, against both sides
2493 let mut alice_config = UserConfig::default();
2494 alice_config.channel_handshake_config.announced_channel = true;
2495 alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2496 alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2497 let mut bob_config = UserConfig::default();
2498 bob_config.channel_handshake_config.announced_channel = true;
2499 bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2500 bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2501 let user_cfgs = [Some(alice_config), Some(bob_config)];
2502 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2503 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2504 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2505 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2506 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2507 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2508 // Create some new channels:
2509 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
2511 // A pending HTLC which will be revoked:
2512 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2513 // Get the will-be-revoked local txn from B
2514 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2515 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2516 assert_eq!(revoked_local_txn[0].input.len(), 1);
2517 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2518 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2519 // Revoke the old state
2520 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2522 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2524 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2525 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2526 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2528 check_spends!(node_txn[0], revoked_local_txn[0]);
2529 node_txn.swap_remove(0);
2531 check_added_monitors!(nodes[0], 1);
2532 test_txn_broadcast(&nodes[0], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2534 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2535 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2536 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2537 check_added_monitors!(nodes[1], 1);
2538 mine_transaction(&nodes[0], &node_txn[1]);
2539 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2540 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2542 get_announce_close_broadcast_events(&nodes, 0, 1);
2543 assert_eq!(nodes[0].node.list_channels().len(), 0);
2544 assert_eq!(nodes[1].node.list_channels().len(), 0);
2548 fn revoked_output_claim() {
2549 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2550 // transaction is broadcast by its counterparty
2551 let chanmon_cfgs = create_chanmon_cfgs(2);
2552 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2553 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2554 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2555 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2556 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2557 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2558 assert_eq!(revoked_local_txn.len(), 1);
2559 // Only output is the full channel value back to nodes[0]:
2560 assert_eq!(revoked_local_txn[0].output.len(), 1);
2561 // Send a payment through, updating everyone's latest commitment txn
2562 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2564 // Inform nodes[1] that nodes[0] broadcast a stale tx
2565 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2566 check_added_monitors!(nodes[1], 1);
2567 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2568 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2569 assert_eq!(node_txn.len(), 1); // ChannelMonitor: justice tx against revoked to_local output
2571 check_spends!(node_txn[0], revoked_local_txn[0]);
2573 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2574 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2575 get_announce_close_broadcast_events(&nodes, 0, 1);
2576 check_added_monitors!(nodes[0], 1);
2577 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2581 fn test_forming_justice_tx_from_monitor_updates() {
2582 do_test_forming_justice_tx_from_monitor_updates(true);
2583 do_test_forming_justice_tx_from_monitor_updates(false);
2586 fn do_test_forming_justice_tx_from_monitor_updates(broadcast_initial_commitment: bool) {
2587 // Simple test to make sure that the justice tx formed in WatchtowerPersister
2588 // is properly formed and can be broadcasted/confirmed successfully in the event
2589 // that a revoked commitment transaction is broadcasted
2590 // (Similar to `revoked_output_claim` test but we get the justice tx + broadcast manually)
2591 let chanmon_cfgs = create_chanmon_cfgs(2);
2592 let destination_script0 = chanmon_cfgs[0].keys_manager.get_destination_script().unwrap();
2593 let destination_script1 = chanmon_cfgs[1].keys_manager.get_destination_script().unwrap();
2594 let persisters = vec![WatchtowerPersister::new(destination_script0),
2595 WatchtowerPersister::new(destination_script1)];
2596 let node_cfgs = create_node_cfgs_with_persisters(2, &chanmon_cfgs, persisters.iter().collect());
2597 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2598 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2599 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
2600 let funding_txo = OutPoint { txid: funding_tx.txid(), index: 0 };
2602 if !broadcast_initial_commitment {
2603 // Send a payment to move the channel forward
2604 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5_000_000);
2607 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output.
2608 // We'll keep this commitment transaction to broadcast once it's revoked.
2609 let revoked_local_txn = get_local_commitment_txn!(nodes[0], channel_id);
2610 assert_eq!(revoked_local_txn.len(), 1);
2611 let revoked_commitment_tx = &revoked_local_txn[0];
2613 // Send another payment, now revoking the previous commitment tx
2614 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5_000_000);
2616 let justice_tx = persisters[1].justice_tx(funding_txo, &revoked_commitment_tx.txid()).unwrap();
2617 check_spends!(justice_tx, revoked_commitment_tx);
2619 mine_transactions(&nodes[1], &[revoked_commitment_tx, &justice_tx]);
2620 mine_transactions(&nodes[0], &[revoked_commitment_tx, &justice_tx]);
2622 check_added_monitors!(nodes[1], 1);
2623 check_closed_event(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false,
2624 &[nodes[0].node.get_our_node_id()], 100_000);
2625 get_announce_close_broadcast_events(&nodes, 1, 0);
2627 check_added_monitors!(nodes[0], 1);
2628 check_closed_event(&nodes[0], 1, ClosureReason::CommitmentTxConfirmed, false,
2629 &[nodes[1].node.get_our_node_id()], 100_000);
2631 // Check that the justice tx has sent the revoked output value to nodes[1]
2632 let monitor = get_monitor!(nodes[1], channel_id);
2633 let total_claimable_balance = monitor.get_claimable_balances().iter().fold(0, |sum, balance| {
2635 channelmonitor::Balance::ClaimableAwaitingConfirmations { amount_satoshis, .. } => sum + amount_satoshis,
2636 _ => panic!("Unexpected balance type"),
2639 // On the first commitment, node[1]'s balance was below dust so it didn't have an output
2640 let node1_channel_balance = if broadcast_initial_commitment { 0 } else { revoked_commitment_tx.output[0].value };
2641 let expected_claimable_balance = node1_channel_balance + justice_tx.output[0].value;
2642 assert_eq!(total_claimable_balance, expected_claimable_balance);
2647 fn claim_htlc_outputs_shared_tx() {
2648 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2649 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2650 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2651 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2652 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2653 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2655 // Create some new channel:
2656 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2658 // Rebalance the network to generate htlc in the two directions
2659 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2660 // 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
2661 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2662 let (_payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2664 // Get the will-be-revoked local txn from node[0]
2665 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2666 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2667 assert_eq!(revoked_local_txn[0].input.len(), 1);
2668 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2669 assert_eq!(revoked_local_txn[1].input.len(), 1);
2670 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2671 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2672 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2674 //Revoke the old state
2675 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2678 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2679 check_added_monitors!(nodes[0], 1);
2680 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2681 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2682 check_added_monitors!(nodes[1], 1);
2683 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2684 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2685 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2687 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2688 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2690 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2691 check_spends!(node_txn[0], revoked_local_txn[0]);
2693 let mut witness_lens = BTreeSet::new();
2694 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2695 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2696 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2697 assert_eq!(witness_lens.len(), 3);
2698 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2699 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2700 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2702 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2703 // ANTI_REORG_DELAY confirmations.
2704 mine_transaction(&nodes[1], &node_txn[0]);
2705 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2706 expect_payment_failed!(nodes[1], payment_hash_2, false);
2708 get_announce_close_broadcast_events(&nodes, 0, 1);
2709 assert_eq!(nodes[0].node.list_channels().len(), 0);
2710 assert_eq!(nodes[1].node.list_channels().len(), 0);
2714 fn claim_htlc_outputs_single_tx() {
2715 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2716 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2717 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2718 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2719 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2720 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2722 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2724 // Rebalance the network to generate htlc in the two directions
2725 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2726 // 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
2727 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2728 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2729 let (_payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2731 // Get the will-be-revoked local txn from node[0]
2732 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2734 //Revoke the old state
2735 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2738 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2739 check_added_monitors!(nodes[0], 1);
2740 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2741 check_added_monitors!(nodes[1], 1);
2742 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2743 let mut events = nodes[0].node.get_and_clear_pending_events();
2744 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2745 match events.last().unwrap() {
2746 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2747 _ => panic!("Unexpected event"),
2750 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2751 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2753 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcast();
2755 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2756 assert_eq!(node_txn[0].input.len(), 1);
2757 check_spends!(node_txn[0], chan_1.3);
2758 assert_eq!(node_txn[1].input.len(), 1);
2759 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2760 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2761 check_spends!(node_txn[1], node_txn[0]);
2763 // Filter out any non justice transactions.
2764 node_txn.retain(|tx| tx.input[0].previous_output.txid == revoked_local_txn[0].txid());
2765 assert!(node_txn.len() > 3);
2767 assert_eq!(node_txn[0].input.len(), 1);
2768 assert_eq!(node_txn[1].input.len(), 1);
2769 assert_eq!(node_txn[2].input.len(), 1);
2771 check_spends!(node_txn[0], revoked_local_txn[0]);
2772 check_spends!(node_txn[1], revoked_local_txn[0]);
2773 check_spends!(node_txn[2], revoked_local_txn[0]);
2775 let mut witness_lens = BTreeSet::new();
2776 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2777 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2778 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2779 assert_eq!(witness_lens.len(), 3);
2780 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2781 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2782 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2784 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2785 // ANTI_REORG_DELAY confirmations.
2786 mine_transaction(&nodes[1], &node_txn[0]);
2787 mine_transaction(&nodes[1], &node_txn[1]);
2788 mine_transaction(&nodes[1], &node_txn[2]);
2789 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2790 expect_payment_failed!(nodes[1], payment_hash_2, false);
2792 get_announce_close_broadcast_events(&nodes, 0, 1);
2793 assert_eq!(nodes[0].node.list_channels().len(), 0);
2794 assert_eq!(nodes[1].node.list_channels().len(), 0);
2798 fn test_htlc_on_chain_success() {
2799 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2800 // the preimage backward accordingly. So here we test that ChannelManager is
2801 // broadcasting the right event to other nodes in payment path.
2802 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2803 // A --------------------> B ----------------------> C (preimage)
2804 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2805 // commitment transaction was broadcast.
2806 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2808 // B should be able to claim via preimage if A then broadcasts its local tx.
2809 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2810 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2811 // PaymentSent event).
2813 let chanmon_cfgs = create_chanmon_cfgs(3);
2814 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2815 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2816 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2818 // Create some initial channels
2819 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2820 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2822 // Ensure all nodes are at the same height
2823 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2824 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2825 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2826 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2828 // Rebalance the network a bit by relaying one payment through all the channels...
2829 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2830 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2832 let (our_payment_preimage, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2833 let (our_payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2835 // Broadcast legit commitment tx from C on B's chain
2836 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2837 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2838 assert_eq!(commitment_tx.len(), 1);
2839 check_spends!(commitment_tx[0], chan_2.3);
2840 nodes[2].node.claim_funds(our_payment_preimage);
2841 expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2842 nodes[2].node.claim_funds(our_payment_preimage_2);
2843 expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2844 check_added_monitors!(nodes[2], 2);
2845 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2846 assert!(updates.update_add_htlcs.is_empty());
2847 assert!(updates.update_fail_htlcs.is_empty());
2848 assert!(updates.update_fail_malformed_htlcs.is_empty());
2849 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2851 mine_transaction(&nodes[2], &commitment_tx[0]);
2852 check_closed_broadcast!(nodes[2], true);
2853 check_added_monitors!(nodes[2], 1);
2854 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2855 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 2 (2 * HTLC-Success tx)
2856 assert_eq!(node_txn.len(), 2);
2857 check_spends!(node_txn[0], commitment_tx[0]);
2858 check_spends!(node_txn[1], commitment_tx[0]);
2859 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2860 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2861 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2862 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2863 assert_eq!(node_txn[0].lock_time.0, 0);
2864 assert_eq!(node_txn[1].lock_time.0, 0);
2866 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2867 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()]));
2868 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2870 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2871 assert_eq!(added_monitors.len(), 1);
2872 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2873 added_monitors.clear();
2875 let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2876 assert_eq!(forwarded_events.len(), 3);
2877 match forwarded_events[0] {
2878 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2879 _ => panic!("Unexpected event"),
2881 let chan_id = Some(chan_1.2);
2882 match forwarded_events[1] {
2883 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2884 assert_eq!(fee_earned_msat, Some(1000));
2885 assert_eq!(prev_channel_id, chan_id);
2886 assert_eq!(claim_from_onchain_tx, true);
2887 assert_eq!(next_channel_id, Some(chan_2.2));
2888 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2892 match forwarded_events[2] {
2893 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2894 assert_eq!(fee_earned_msat, Some(1000));
2895 assert_eq!(prev_channel_id, chan_id);
2896 assert_eq!(claim_from_onchain_tx, true);
2897 assert_eq!(next_channel_id, Some(chan_2.2));
2898 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2902 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2904 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2905 assert_eq!(added_monitors.len(), 2);
2906 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2907 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2908 added_monitors.clear();
2910 assert_eq!(events.len(), 3);
2912 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
2913 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
2915 match nodes_2_event {
2916 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2917 _ => panic!("Unexpected event"),
2920 match nodes_0_event {
2921 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, .. } } => {
2922 assert!(update_add_htlcs.is_empty());
2923 assert!(update_fail_htlcs.is_empty());
2924 assert_eq!(update_fulfill_htlcs.len(), 1);
2925 assert!(update_fail_malformed_htlcs.is_empty());
2926 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2928 _ => panic!("Unexpected event"),
2931 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
2933 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2934 _ => panic!("Unexpected event"),
2937 macro_rules! check_tx_local_broadcast {
2938 ($node: expr, $htlc_offered: expr, $commitment_tx: expr) => { {
2939 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2940 assert_eq!(node_txn.len(), 2);
2941 // Node[1]: 2 * HTLC-timeout tx
2942 // Node[0]: 2 * HTLC-timeout tx
2943 check_spends!(node_txn[0], $commitment_tx);
2944 check_spends!(node_txn[1], $commitment_tx);
2945 assert_ne!(node_txn[0].lock_time.0, 0);
2946 assert_ne!(node_txn[1].lock_time.0, 0);
2948 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2949 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2950 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2951 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2953 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2954 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2955 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2956 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2961 // nodes[1] now broadcasts its own timeout-claim of the output that nodes[2] just claimed via success.
2962 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0]);
2964 // Broadcast legit commitment tx from A on B's chain
2965 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2966 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2967 check_spends!(node_a_commitment_tx[0], chan_1.3);
2968 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2969 check_closed_broadcast!(nodes[1], true);
2970 check_added_monitors!(nodes[1], 1);
2971 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2972 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2973 assert!(node_txn.len() == 1 || node_txn.len() == 3); // HTLC-Success, 2* RBF bumps of above HTLC txn
2974 let commitment_spend =
2975 if node_txn.len() == 1 {
2978 // Certain `ConnectStyle`s will cause RBF bumps of the previous HTLC transaction to be broadcast.
2979 // FullBlockViaListen
2980 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2981 check_spends!(node_txn[1], commitment_tx[0]);
2982 check_spends!(node_txn[2], commitment_tx[0]);
2983 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2986 check_spends!(node_txn[0], commitment_tx[0]);
2987 check_spends!(node_txn[1], commitment_tx[0]);
2988 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2993 check_spends!(commitment_spend, node_a_commitment_tx[0]);
2994 assert_eq!(commitment_spend.input.len(), 2);
2995 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2996 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2997 assert_eq!(commitment_spend.lock_time.0, nodes[1].best_block_info().1);
2998 assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2999 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
3000 // we already checked the same situation with A.
3002 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
3003 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()]));
3004 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
3005 check_closed_broadcast!(nodes[0], true);
3006 check_added_monitors!(nodes[0], 1);
3007 let events = nodes[0].node.get_and_clear_pending_events();
3008 assert_eq!(events.len(), 5);
3009 let mut first_claimed = false;
3010 for event in events {
3012 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3013 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
3014 assert!(!first_claimed);
3015 first_claimed = true;
3017 assert_eq!(payment_preimage, our_payment_preimage_2);
3018 assert_eq!(payment_hash, payment_hash_2);
3021 Event::PaymentPathSuccessful { .. } => {},
3022 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
3023 _ => panic!("Unexpected event"),
3026 check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0]);
3029 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
3030 // Test that in case of a unilateral close onchain, we detect the state of output and
3031 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
3032 // broadcasting the right event to other nodes in payment path.
3033 // A ------------------> B ----------------------> C (timeout)
3034 // B's commitment tx C's commitment tx
3036 // B's HTLC timeout tx B's timeout tx
3038 let chanmon_cfgs = create_chanmon_cfgs(3);
3039 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3040 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3041 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3042 *nodes[0].connect_style.borrow_mut() = connect_style;
3043 *nodes[1].connect_style.borrow_mut() = connect_style;
3044 *nodes[2].connect_style.borrow_mut() = connect_style;
3046 // Create some intial channels
3047 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
3048 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3050 // Rebalance the network a bit by relaying one payment thorugh all the channels...
3051 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
3052 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
3054 let (_payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
3056 // Broadcast legit commitment tx from C on B's chain
3057 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
3058 check_spends!(commitment_tx[0], chan_2.3);
3059 nodes[2].node.fail_htlc_backwards(&payment_hash);
3060 check_added_monitors!(nodes[2], 0);
3061 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
3062 check_added_monitors!(nodes[2], 1);
3064 let events = nodes[2].node.get_and_clear_pending_msg_events();
3065 assert_eq!(events.len(), 1);
3067 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, .. } } => {
3068 assert!(update_add_htlcs.is_empty());
3069 assert!(!update_fail_htlcs.is_empty());
3070 assert!(update_fulfill_htlcs.is_empty());
3071 assert!(update_fail_malformed_htlcs.is_empty());
3072 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
3074 _ => panic!("Unexpected event"),
3076 mine_transaction(&nodes[2], &commitment_tx[0]);
3077 check_closed_broadcast!(nodes[2], true);
3078 check_added_monitors!(nodes[2], 1);
3079 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
3080 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
3081 assert_eq!(node_txn.len(), 0);
3083 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
3084 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
3085 mine_transaction(&nodes[1], &commitment_tx[0]);
3086 check_closed_event!(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false
3087 , [nodes[2].node.get_our_node_id()], 100000);
3088 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
3090 let mut txn = nodes[1].tx_broadcaster.txn_broadcast();
3091 if nodes[1].connect_style.borrow().skips_blocks() {
3092 assert_eq!(txn.len(), 1);
3094 assert_eq!(txn.len(), 3); // Two extra fee bumps for timeout transaction
3096 txn.iter().for_each(|tx| check_spends!(tx, commitment_tx[0]));
3097 assert_eq!(txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3101 mine_transaction(&nodes[1], &timeout_tx);
3102 check_added_monitors!(nodes[1], 1);
3103 check_closed_broadcast!(nodes[1], true);
3105 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3107 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 }]);
3108 check_added_monitors!(nodes[1], 1);
3109 let events = nodes[1].node.get_and_clear_pending_msg_events();
3110 assert_eq!(events.len(), 1);
3112 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, .. } } => {
3113 assert!(update_add_htlcs.is_empty());
3114 assert!(!update_fail_htlcs.is_empty());
3115 assert!(update_fulfill_htlcs.is_empty());
3116 assert!(update_fail_malformed_htlcs.is_empty());
3117 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3119 _ => panic!("Unexpected event"),
3122 // Broadcast legit commitment tx from B on A's chain
3123 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3124 check_spends!(commitment_tx[0], chan_1.3);
3126 mine_transaction(&nodes[0], &commitment_tx[0]);
3127 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
3129 check_closed_broadcast!(nodes[0], true);
3130 check_added_monitors!(nodes[0], 1);
3131 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
3132 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // 1 timeout tx
3133 assert_eq!(node_txn.len(), 1);
3134 check_spends!(node_txn[0], commitment_tx[0]);
3135 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3139 fn test_htlc_on_chain_timeout() {
3140 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3141 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3142 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3146 fn test_simple_commitment_revoked_fail_backward() {
3147 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3148 // and fail backward accordingly.
3150 let chanmon_cfgs = create_chanmon_cfgs(3);
3151 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3152 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3153 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3155 // Create some initial channels
3156 create_announced_chan_between_nodes(&nodes, 0, 1);
3157 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3159 let (payment_preimage, _payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3160 // Get the will-be-revoked local txn from nodes[2]
3161 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3162 // Revoke the old state
3163 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3165 let (_, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3167 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3168 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
3169 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3170 check_added_monitors!(nodes[1], 1);
3171 check_closed_broadcast!(nodes[1], true);
3173 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 }]);
3174 check_added_monitors!(nodes[1], 1);
3175 let events = nodes[1].node.get_and_clear_pending_msg_events();
3176 assert_eq!(events.len(), 1);
3178 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, .. } } => {
3179 assert!(update_add_htlcs.is_empty());
3180 assert_eq!(update_fail_htlcs.len(), 1);
3181 assert!(update_fulfill_htlcs.is_empty());
3182 assert!(update_fail_malformed_htlcs.is_empty());
3183 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3185 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3186 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3187 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3189 _ => panic!("Unexpected event"),
3193 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3194 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3195 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3196 // commitment transaction anymore.
3197 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3198 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3199 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3200 // technically disallowed and we should probably handle it reasonably.
3201 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3202 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3204 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3205 // commitment_signed (implying it will be in the latest remote commitment transaction).
3206 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3207 // and once they revoke the previous commitment transaction (allowing us to send a new
3208 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3209 let chanmon_cfgs = create_chanmon_cfgs(3);
3210 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3211 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3212 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3214 // Create some initial channels
3215 create_announced_chan_between_nodes(&nodes, 0, 1);
3216 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3218 let (payment_preimage, _payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3219 // Get the will-be-revoked local txn from nodes[2]
3220 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3221 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3222 // Revoke the old state
3223 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3225 let value = if use_dust {
3226 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3227 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3228 nodes[2].node.per_peer_state.read().unwrap().get(&nodes[1].node.get_our_node_id())
3229 .unwrap().lock().unwrap().channel_by_id.get(&chan_2.2).unwrap().context().holder_dust_limit_satoshis * 1000
3232 let (_, first_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3233 let (_, second_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3234 let (_, third_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3236 nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3237 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3238 check_added_monitors!(nodes[2], 1);
3239 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3240 assert!(updates.update_add_htlcs.is_empty());
3241 assert!(updates.update_fulfill_htlcs.is_empty());
3242 assert!(updates.update_fail_malformed_htlcs.is_empty());
3243 assert_eq!(updates.update_fail_htlcs.len(), 1);
3244 assert!(updates.update_fee.is_none());
3245 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3246 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3247 // Drop the last RAA from 3 -> 2
3249 nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3250 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3251 check_added_monitors!(nodes[2], 1);
3252 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3253 assert!(updates.update_add_htlcs.is_empty());
3254 assert!(updates.update_fulfill_htlcs.is_empty());
3255 assert!(updates.update_fail_malformed_htlcs.is_empty());
3256 assert_eq!(updates.update_fail_htlcs.len(), 1);
3257 assert!(updates.update_fee.is_none());
3258 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3259 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3260 check_added_monitors!(nodes[1], 1);
3261 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3262 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3263 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3264 check_added_monitors!(nodes[2], 1);
3266 nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3267 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3268 check_added_monitors!(nodes[2], 1);
3269 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3270 assert!(updates.update_add_htlcs.is_empty());
3271 assert!(updates.update_fulfill_htlcs.is_empty());
3272 assert!(updates.update_fail_malformed_htlcs.is_empty());
3273 assert_eq!(updates.update_fail_htlcs.len(), 1);
3274 assert!(updates.update_fee.is_none());
3275 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3276 // At this point first_payment_hash has dropped out of the latest two commitment
3277 // transactions that nodes[1] is tracking...
3278 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3279 check_added_monitors!(nodes[1], 1);
3280 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3281 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3282 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3283 check_added_monitors!(nodes[2], 1);
3285 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3286 // on nodes[2]'s RAA.
3287 let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3288 nodes[1].node.send_payment_with_route(&route, fourth_payment_hash,
3289 RecipientOnionFields::secret_only(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3290 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3291 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3292 check_added_monitors!(nodes[1], 0);
3295 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3296 // One monitor for the new revocation preimage, no second on as we won't generate a new
3297 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3298 check_added_monitors!(nodes[1], 1);
3299 let events = nodes[1].node.get_and_clear_pending_events();
3300 assert_eq!(events.len(), 2);
3302 Event::PendingHTLCsForwardable { .. } => { },
3303 _ => panic!("Unexpected event"),
3306 Event::HTLCHandlingFailed { .. } => { },
3307 _ => panic!("Unexpected event"),
3309 // Deliberately don't process the pending fail-back so they all fail back at once after
3310 // block connection just like the !deliver_bs_raa case
3313 let mut failed_htlcs = HashSet::new();
3314 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3316 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3317 check_added_monitors!(nodes[1], 1);
3318 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3320 let events = nodes[1].node.get_and_clear_pending_events();
3321 assert_eq!(events.len(), if deliver_bs_raa { 3 + nodes.len() - 1 } else { 4 + nodes.len() });
3323 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3324 _ => panic!("Unexepected event"),
3327 Event::PaymentPathFailed { ref payment_hash, .. } => {
3328 assert_eq!(*payment_hash, fourth_payment_hash);
3330 _ => panic!("Unexpected event"),
3333 Event::PaymentFailed { ref payment_hash, .. } => {
3334 assert_eq!(*payment_hash, fourth_payment_hash);
3336 _ => panic!("Unexpected event"),
3339 nodes[1].node.process_pending_htlc_forwards();
3340 check_added_monitors!(nodes[1], 1);
3342 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
3343 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3346 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3347 match nodes_2_event {
3348 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, .. } } => {
3349 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3350 assert_eq!(update_add_htlcs.len(), 1);
3351 assert!(update_fulfill_htlcs.is_empty());
3352 assert!(update_fail_htlcs.is_empty());
3353 assert!(update_fail_malformed_htlcs.is_empty());
3355 _ => panic!("Unexpected event"),
3359 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3360 match nodes_2_event {
3361 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3362 assert_eq!(channel_id, chan_2.2);
3363 assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3365 _ => panic!("Unexpected event"),
3368 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
3369 match nodes_0_event {
3370 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, .. } } => {
3371 assert!(update_add_htlcs.is_empty());
3372 assert_eq!(update_fail_htlcs.len(), 3);
3373 assert!(update_fulfill_htlcs.is_empty());
3374 assert!(update_fail_malformed_htlcs.is_empty());
3375 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3377 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3378 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3379 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3381 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3383 let events = nodes[0].node.get_and_clear_pending_events();
3384 assert_eq!(events.len(), 6);
3386 Event::PaymentPathFailed { ref payment_hash, ref failure, .. } => {
3387 assert!(failed_htlcs.insert(payment_hash.0));
3388 // If we delivered B's RAA we got an unknown preimage error, not something
3389 // that we should update our routing table for.
3390 if !deliver_bs_raa {
3391 if let PathFailure::OnPath { network_update: Some(_) } = failure { } else { panic!("Unexpected path failure") }
3394 _ => panic!("Unexpected event"),
3397 Event::PaymentFailed { ref payment_hash, .. } => {
3398 assert_eq!(*payment_hash, first_payment_hash);
3400 _ => panic!("Unexpected event"),
3403 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3404 assert!(failed_htlcs.insert(payment_hash.0));
3406 _ => panic!("Unexpected event"),
3409 Event::PaymentFailed { ref payment_hash, .. } => {
3410 assert_eq!(*payment_hash, second_payment_hash);
3412 _ => panic!("Unexpected event"),
3415 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3416 assert!(failed_htlcs.insert(payment_hash.0));
3418 _ => panic!("Unexpected event"),
3421 Event::PaymentFailed { ref payment_hash, .. } => {
3422 assert_eq!(*payment_hash, third_payment_hash);
3424 _ => panic!("Unexpected event"),
3427 _ => panic!("Unexpected event"),
3430 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
3432 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3433 _ => panic!("Unexpected event"),
3436 assert!(failed_htlcs.contains(&first_payment_hash.0));
3437 assert!(failed_htlcs.contains(&second_payment_hash.0));
3438 assert!(failed_htlcs.contains(&third_payment_hash.0));
3442 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3443 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3444 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3445 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3446 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3450 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3451 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3452 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3453 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3454 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3458 fn fail_backward_pending_htlc_upon_channel_failure() {
3459 let chanmon_cfgs = create_chanmon_cfgs(2);
3460 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3461 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3462 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3463 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
3465 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3467 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3468 nodes[0].node.send_payment_with_route(&route, payment_hash, RecipientOnionFields::secret_only(payment_secret),
3469 PaymentId(payment_hash.0)).unwrap();
3470 check_added_monitors!(nodes[0], 1);
3472 let payment_event = {
3473 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3474 assert_eq!(events.len(), 1);
3475 SendEvent::from_event(events.remove(0))
3477 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3478 assert_eq!(payment_event.msgs.len(), 1);
3481 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3482 let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3484 nodes[0].node.send_payment_with_route(&route, failed_payment_hash,
3485 RecipientOnionFields::secret_only(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3486 check_added_monitors!(nodes[0], 0);
3488 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3491 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3493 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3495 let secp_ctx = Secp256k1::new();
3496 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3497 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3498 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(
3499 &route.paths[0], 50_000, RecipientOnionFields::secret_only(payment_secret), current_height, &None).unwrap();
3500 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3501 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
3503 // Send a 0-msat update_add_htlc to fail the channel.
3504 let update_add_htlc = msgs::UpdateAddHTLC {
3510 onion_routing_packet,
3511 skimmed_fee_msat: None,
3513 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3515 let events = nodes[0].node.get_and_clear_pending_events();
3516 assert_eq!(events.len(), 3);
3517 // Check that Alice fails backward the pending HTLC from the second payment.
3519 Event::PaymentPathFailed { payment_hash, .. } => {
3520 assert_eq!(payment_hash, failed_payment_hash);
3522 _ => panic!("Unexpected event"),
3525 Event::PaymentFailed { payment_hash, .. } => {
3526 assert_eq!(payment_hash, failed_payment_hash);
3528 _ => panic!("Unexpected event"),
3531 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3532 assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3534 _ => panic!("Unexpected event {:?}", events[1]),
3536 check_closed_broadcast!(nodes[0], true);
3537 check_added_monitors!(nodes[0], 1);
3541 fn test_htlc_ignore_latest_remote_commitment() {
3542 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3543 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3544 let chanmon_cfgs = create_chanmon_cfgs(2);
3545 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3546 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3547 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3548 if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3549 // We rely on the ability to connect a block redundantly, which isn't allowed via
3550 // `chain::Listen`, so we never run the test if we randomly get assigned that
3554 create_announced_chan_between_nodes(&nodes, 0, 1);
3556 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3557 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3558 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3559 check_closed_broadcast!(nodes[0], true);
3560 check_added_monitors!(nodes[0], 1);
3561 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
3563 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3564 assert_eq!(node_txn.len(), 3);
3565 assert_eq!(node_txn[0].txid(), node_txn[1].txid());
3567 let block = create_dummy_block(nodes[1].best_block_hash(), 42, vec![node_txn[0].clone(), node_txn[1].clone()]);
3568 connect_block(&nodes[1], &block);
3569 check_closed_broadcast!(nodes[1], true);
3570 check_added_monitors!(nodes[1], 1);
3571 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
3573 // Duplicate the connect_block call since this may happen due to other listeners
3574 // registering new transactions
3575 connect_block(&nodes[1], &block);
3579 fn test_force_close_fail_back() {
3580 // Check which HTLCs are failed-backwards on channel force-closure
3581 let chanmon_cfgs = create_chanmon_cfgs(3);
3582 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3583 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3584 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3585 create_announced_chan_between_nodes(&nodes, 0, 1);
3586 create_announced_chan_between_nodes(&nodes, 1, 2);
3588 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3590 let mut payment_event = {
3591 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
3592 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3593 check_added_monitors!(nodes[0], 1);
3595 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3596 assert_eq!(events.len(), 1);
3597 SendEvent::from_event(events.remove(0))
3600 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3601 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3603 expect_pending_htlcs_forwardable!(nodes[1]);
3605 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3606 assert_eq!(events_2.len(), 1);
3607 payment_event = SendEvent::from_event(events_2.remove(0));
3608 assert_eq!(payment_event.msgs.len(), 1);
3610 check_added_monitors!(nodes[1], 1);
3611 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3612 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3613 check_added_monitors!(nodes[2], 1);
3614 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3616 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3617 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3618 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3620 nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3621 check_closed_broadcast!(nodes[2], true);
3622 check_added_monitors!(nodes[2], 1);
3623 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
3625 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3626 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3627 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3628 // back to nodes[1] upon timeout otherwise.
3629 assert_eq!(node_txn.len(), 1);
3633 mine_transaction(&nodes[1], &tx);
3635 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3636 check_closed_broadcast!(nodes[1], true);
3637 check_added_monitors!(nodes[1], 1);
3638 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
3640 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3642 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3643 .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);
3645 mine_transaction(&nodes[2], &tx);
3646 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3647 assert_eq!(node_txn.len(), 1);
3648 assert_eq!(node_txn[0].input.len(), 1);
3649 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3650 assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3651 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3653 check_spends!(node_txn[0], tx);
3657 fn test_dup_events_on_peer_disconnect() {
3658 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3659 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3660 // as we used to generate the event immediately upon receipt of the payment preimage in the
3661 // update_fulfill_htlc message.
3663 let chanmon_cfgs = create_chanmon_cfgs(2);
3664 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3665 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3666 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3667 create_announced_chan_between_nodes(&nodes, 0, 1);
3669 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3671 nodes[1].node.claim_funds(payment_preimage);
3672 expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3673 check_added_monitors!(nodes[1], 1);
3674 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3675 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3676 expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
3678 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3679 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3681 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3682 reconnect_args.pending_htlc_claims.0 = 1;
3683 reconnect_nodes(reconnect_args);
3684 expect_payment_path_successful!(nodes[0]);
3688 fn test_peer_disconnected_before_funding_broadcasted() {
3689 // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3690 // before the funding transaction has been broadcasted.
3691 let chanmon_cfgs = create_chanmon_cfgs(2);
3692 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3693 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3694 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3696 // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3697 // broadcasted, even though it's created by `nodes[0]`.
3698 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();
3699 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3700 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
3701 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3702 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
3704 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3705 assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3707 assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3709 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3710 assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3712 // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3713 // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3716 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3719 // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3720 // disconnected before the funding transaction was broadcasted.
3721 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3722 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3724 check_closed_event!(&nodes[0], 2, ClosureReason::DisconnectedPeer, true
3725 , [nodes[1].node.get_our_node_id()], 1000000);
3726 check_closed_event!(&nodes[1], 1, ClosureReason::DisconnectedPeer, false
3727 , [nodes[0].node.get_our_node_id()], 1000000);
3731 fn test_simple_peer_disconnect() {
3732 // Test that we can reconnect when there are no lost messages
3733 let chanmon_cfgs = create_chanmon_cfgs(3);
3734 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3735 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3736 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3737 create_announced_chan_between_nodes(&nodes, 0, 1);
3738 create_announced_chan_between_nodes(&nodes, 1, 2);
3740 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3741 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3742 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3743 reconnect_args.send_channel_ready = (true, true);
3744 reconnect_nodes(reconnect_args);
3746 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3747 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3748 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3749 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3751 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3752 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3753 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3755 let (payment_preimage_3, payment_hash_3, ..) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3756 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3757 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3758 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3760 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3761 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3763 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3764 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3766 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3767 reconnect_args.pending_cell_htlc_fails.0 = 1;
3768 reconnect_args.pending_cell_htlc_claims.0 = 1;
3769 reconnect_nodes(reconnect_args);
3771 let events = nodes[0].node.get_and_clear_pending_events();
3772 assert_eq!(events.len(), 4);
3774 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3775 assert_eq!(payment_preimage, payment_preimage_3);
3776 assert_eq!(payment_hash, payment_hash_3);
3778 _ => panic!("Unexpected event"),
3781 Event::PaymentPathSuccessful { .. } => {},
3782 _ => panic!("Unexpected event"),
3785 Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3786 assert_eq!(payment_hash, payment_hash_5);
3787 assert!(payment_failed_permanently);
3789 _ => panic!("Unexpected event"),
3792 Event::PaymentFailed { payment_hash, .. } => {
3793 assert_eq!(payment_hash, payment_hash_5);
3795 _ => panic!("Unexpected event"),
3798 check_added_monitors(&nodes[0], 1);
3800 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3801 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3804 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3805 // Test that we can reconnect when in-flight HTLC updates get dropped
3806 let chanmon_cfgs = create_chanmon_cfgs(2);
3807 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3808 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3809 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3811 let mut as_channel_ready = None;
3812 let channel_id = if messages_delivered == 0 {
3813 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3814 as_channel_ready = Some(channel_ready);
3815 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3816 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3817 // it before the channel_reestablish message.
3820 create_announced_chan_between_nodes(&nodes, 0, 1).2
3823 let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3825 let payment_event = {
3826 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
3827 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3828 check_added_monitors!(nodes[0], 1);
3830 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3831 assert_eq!(events.len(), 1);
3832 SendEvent::from_event(events.remove(0))
3834 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3836 if messages_delivered < 2 {
3837 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3839 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3840 if messages_delivered >= 3 {
3841 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3842 check_added_monitors!(nodes[1], 1);
3843 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3845 if messages_delivered >= 4 {
3846 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3847 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3848 check_added_monitors!(nodes[0], 1);
3850 if messages_delivered >= 5 {
3851 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3852 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3853 // No commitment_signed so get_event_msg's assert(len == 1) passes
3854 check_added_monitors!(nodes[0], 1);
3856 if messages_delivered >= 6 {
3857 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3858 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3859 check_added_monitors!(nodes[1], 1);
3866 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3867 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3868 if messages_delivered < 3 {
3869 if simulate_broken_lnd {
3870 // lnd has a long-standing bug where they send a channel_ready prior to a
3871 // channel_reestablish if you reconnect prior to channel_ready time.
3873 // Here we simulate that behavior, delivering a channel_ready immediately on
3874 // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3875 // in `reconnect_nodes` but we currently don't fail based on that.
3877 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3878 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3880 // Even if the channel_ready messages get exchanged, as long as nothing further was
3881 // received on either side, both sides will need to resend them.
3882 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3883 reconnect_args.send_channel_ready = (true, true);
3884 reconnect_args.pending_htlc_adds.1 = 1;
3885 reconnect_nodes(reconnect_args);
3886 } else if messages_delivered == 3 {
3887 // nodes[0] still wants its RAA + commitment_signed
3888 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3889 reconnect_args.pending_responding_commitment_signed.0 = true;
3890 reconnect_args.pending_raa.0 = true;
3891 reconnect_nodes(reconnect_args);
3892 } else if messages_delivered == 4 {
3893 // nodes[0] still wants its commitment_signed
3894 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3895 reconnect_args.pending_responding_commitment_signed.0 = true;
3896 reconnect_nodes(reconnect_args);
3897 } else if messages_delivered == 5 {
3898 // nodes[1] still wants its final RAA
3899 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3900 reconnect_args.pending_raa.1 = true;
3901 reconnect_nodes(reconnect_args);
3902 } else if messages_delivered == 6 {
3903 // Everything was delivered...
3904 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3907 let events_1 = nodes[1].node.get_and_clear_pending_events();
3908 if messages_delivered == 0 {
3909 assert_eq!(events_1.len(), 2);
3911 Event::ChannelReady { .. } => { },
3912 _ => panic!("Unexpected event"),
3915 Event::PendingHTLCsForwardable { .. } => { },
3916 _ => panic!("Unexpected event"),
3919 assert_eq!(events_1.len(), 1);
3921 Event::PendingHTLCsForwardable { .. } => { },
3922 _ => panic!("Unexpected event"),
3926 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3927 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3928 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3930 nodes[1].node.process_pending_htlc_forwards();
3932 let events_2 = nodes[1].node.get_and_clear_pending_events();
3933 assert_eq!(events_2.len(), 1);
3935 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
3936 assert_eq!(payment_hash_1, *payment_hash);
3937 assert_eq!(amount_msat, 1_000_000);
3938 assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3939 assert_eq!(via_channel_id, Some(channel_id));
3941 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3942 assert!(payment_preimage.is_none());
3943 assert_eq!(payment_secret_1, *payment_secret);
3945 _ => panic!("expected PaymentPurpose::InvoicePayment")
3948 _ => panic!("Unexpected event"),
3951 nodes[1].node.claim_funds(payment_preimage_1);
3952 check_added_monitors!(nodes[1], 1);
3953 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3955 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3956 assert_eq!(events_3.len(), 1);
3957 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3958 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3959 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3960 assert!(updates.update_add_htlcs.is_empty());
3961 assert!(updates.update_fail_htlcs.is_empty());
3962 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3963 assert!(updates.update_fail_malformed_htlcs.is_empty());
3964 assert!(updates.update_fee.is_none());
3965 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3967 _ => panic!("Unexpected event"),
3970 if messages_delivered >= 1 {
3971 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3973 let events_4 = nodes[0].node.get_and_clear_pending_events();
3974 assert_eq!(events_4.len(), 1);
3976 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3977 assert_eq!(payment_preimage_1, *payment_preimage);
3978 assert_eq!(payment_hash_1, *payment_hash);
3980 _ => panic!("Unexpected event"),
3983 if messages_delivered >= 2 {
3984 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3985 check_added_monitors!(nodes[0], 1);
3986 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3988 if messages_delivered >= 3 {
3989 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3990 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3991 check_added_monitors!(nodes[1], 1);
3993 if messages_delivered >= 4 {
3994 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3995 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3996 // No commitment_signed so get_event_msg's assert(len == 1) passes
3997 check_added_monitors!(nodes[1], 1);
3999 if messages_delivered >= 5 {
4000 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4001 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4002 check_added_monitors!(nodes[0], 1);
4009 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4010 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4011 if messages_delivered < 2 {
4012 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4013 reconnect_args.pending_htlc_claims.0 = 1;
4014 reconnect_nodes(reconnect_args);
4015 if messages_delivered < 1 {
4016 expect_payment_sent!(nodes[0], payment_preimage_1);
4018 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4020 } else if messages_delivered == 2 {
4021 // nodes[0] still wants its RAA + commitment_signed
4022 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4023 reconnect_args.pending_responding_commitment_signed.1 = true;
4024 reconnect_args.pending_raa.1 = true;
4025 reconnect_nodes(reconnect_args);
4026 } else if messages_delivered == 3 {
4027 // nodes[0] still wants its commitment_signed
4028 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4029 reconnect_args.pending_responding_commitment_signed.1 = true;
4030 reconnect_nodes(reconnect_args);
4031 } else if messages_delivered == 4 {
4032 // nodes[1] still wants its final RAA
4033 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4034 reconnect_args.pending_raa.0 = true;
4035 reconnect_nodes(reconnect_args);
4036 } else if messages_delivered == 5 {
4037 // Everything was delivered...
4038 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
4041 if messages_delivered == 1 || messages_delivered == 2 {
4042 expect_payment_path_successful!(nodes[0]);
4044 if messages_delivered <= 5 {
4045 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4046 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4048 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
4050 if messages_delivered > 2 {
4051 expect_payment_path_successful!(nodes[0]);
4054 // Channel should still work fine...
4055 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4056 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
4057 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4061 fn test_drop_messages_peer_disconnect_a() {
4062 do_test_drop_messages_peer_disconnect(0, true);
4063 do_test_drop_messages_peer_disconnect(0, false);
4064 do_test_drop_messages_peer_disconnect(1, false);
4065 do_test_drop_messages_peer_disconnect(2, false);
4069 fn test_drop_messages_peer_disconnect_b() {
4070 do_test_drop_messages_peer_disconnect(3, false);
4071 do_test_drop_messages_peer_disconnect(4, false);
4072 do_test_drop_messages_peer_disconnect(5, false);
4073 do_test_drop_messages_peer_disconnect(6, false);
4077 fn test_channel_ready_without_best_block_updated() {
4078 // Previously, if we were offline when a funding transaction was locked in, and then we came
4079 // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
4080 // generate a channel_ready until a later best_block_updated. This tests that we generate the
4081 // channel_ready immediately instead.
4082 let chanmon_cfgs = create_chanmon_cfgs(2);
4083 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4084 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4085 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4086 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
4088 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
4090 let conf_height = nodes[0].best_block_info().1 + 1;
4091 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4092 let block_txn = [funding_tx];
4093 let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
4094 let conf_block_header = nodes[0].get_block_header(conf_height);
4095 nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
4097 // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4098 let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4099 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4103 fn test_channel_monitor_skipping_block_when_channel_manager_is_leading() {
4104 let chanmon_cfgs = create_chanmon_cfgs(2);
4105 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4106 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4107 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4109 // Let channel_manager get ahead of chain_monitor by 1 block.
4110 // This is to emulate race-condition where newly added channel_monitor skips processing 1 block,
4111 // in case where client calls block_connect on channel_manager first and then on chain_monitor.
4112 let height_1 = nodes[0].best_block_info().1 + 1;
4113 let mut block_1 = create_dummy_block(nodes[0].best_block_hash(), height_1, Vec::new());
4115 nodes[0].blocks.lock().unwrap().push((block_1.clone(), height_1));
4116 nodes[0].node.block_connected(&block_1, height_1);
4118 // Create channel, and it gets added to chain_monitor in funding_created.
4119 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
4121 // Now, newly added channel_monitor in chain_monitor hasn't processed block_1,
4122 // but it's best_block is block_1, since that was populated by channel_manager, and channel_manager
4123 // was running ahead of chain_monitor at the time of funding_created.
4124 // Later on, subsequent blocks are connected to both channel_manager and chain_monitor.
4125 // Hence, this channel's channel_monitor skipped block_1, directly tries to process subsequent blocks.
4126 confirm_transaction_at(&nodes[0], &funding_tx, nodes[0].best_block_info().1 + 1);
4127 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4129 // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4130 let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4131 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4135 fn test_channel_monitor_skipping_block_when_channel_manager_is_lagging() {
4136 let chanmon_cfgs = create_chanmon_cfgs(2);
4137 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4138 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4139 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4141 // Let chain_monitor get ahead of channel_manager by 1 block.
4142 // This is to emulate race-condition where newly added channel_monitor skips processing 1 block,
4143 // in case where client calls block_connect on chain_monitor first and then on channel_manager.
4144 let height_1 = nodes[0].best_block_info().1 + 1;
4145 let mut block_1 = create_dummy_block(nodes[0].best_block_hash(), height_1, Vec::new());
4147 nodes[0].blocks.lock().unwrap().push((block_1.clone(), height_1));
4148 nodes[0].chain_monitor.chain_monitor.block_connected(&block_1, height_1);
4150 // Create channel, and it gets added to chain_monitor in funding_created.
4151 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
4153 // channel_manager can't really skip block_1, it should get it eventually.
4154 nodes[0].node.block_connected(&block_1, height_1);
4156 // Now, newly added channel_monitor in chain_monitor hasn't processed block_1, it's best_block is
4157 // the block before block_1, since that was populated by channel_manager, and channel_manager was
4158 // running behind at the time of funding_created.
4159 // Later on, subsequent blocks are connected to both channel_manager and chain_monitor.
4160 // Hence, this channel's channel_monitor skipped block_1, directly tries to process subsequent blocks.
4161 confirm_transaction_at(&nodes[0], &funding_tx, nodes[0].best_block_info().1 + 1);
4162 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4164 // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4165 let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4166 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4170 fn test_drop_messages_peer_disconnect_dual_htlc() {
4171 // Test that we can handle reconnecting when both sides of a channel have pending
4172 // commitment_updates when we disconnect.
4173 let chanmon_cfgs = create_chanmon_cfgs(2);
4174 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4175 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4176 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4177 create_announced_chan_between_nodes(&nodes, 0, 1);
4179 let (payment_preimage_1, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
4181 // Now try to send a second payment which will fail to send
4182 let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4183 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
4184 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
4185 check_added_monitors!(nodes[0], 1);
4187 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4188 assert_eq!(events_1.len(), 1);
4190 MessageSendEvent::UpdateHTLCs { .. } => {},
4191 _ => panic!("Unexpected event"),
4194 nodes[1].node.claim_funds(payment_preimage_1);
4195 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4196 check_added_monitors!(nodes[1], 1);
4198 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4199 assert_eq!(events_2.len(), 1);
4201 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 } } => {
4202 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4203 assert!(update_add_htlcs.is_empty());
4204 assert_eq!(update_fulfill_htlcs.len(), 1);
4205 assert!(update_fail_htlcs.is_empty());
4206 assert!(update_fail_malformed_htlcs.is_empty());
4207 assert!(update_fee.is_none());
4209 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4210 let events_3 = nodes[0].node.get_and_clear_pending_events();
4211 assert_eq!(events_3.len(), 1);
4213 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4214 assert_eq!(*payment_preimage, payment_preimage_1);
4215 assert_eq!(*payment_hash, payment_hash_1);
4217 _ => panic!("Unexpected event"),
4220 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4221 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4222 // No commitment_signed so get_event_msg's assert(len == 1) passes
4223 check_added_monitors!(nodes[0], 1);
4225 _ => panic!("Unexpected event"),
4228 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4229 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4231 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
4232 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
4234 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4235 assert_eq!(reestablish_1.len(), 1);
4236 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
4237 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
4239 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4240 assert_eq!(reestablish_2.len(), 1);
4242 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4243 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4244 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4245 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4247 assert!(as_resp.0.is_none());
4248 assert!(bs_resp.0.is_none());
4250 assert!(bs_resp.1.is_none());
4251 assert!(bs_resp.2.is_none());
4253 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4255 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4256 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4257 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4258 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4259 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4260 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4261 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4262 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4263 // No commitment_signed so get_event_msg's assert(len == 1) passes
4264 check_added_monitors!(nodes[1], 1);
4266 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4267 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4268 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4269 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4270 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4271 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4272 assert!(bs_second_commitment_signed.update_fee.is_none());
4273 check_added_monitors!(nodes[1], 1);
4275 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4276 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4277 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4278 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4279 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4280 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4281 assert!(as_commitment_signed.update_fee.is_none());
4282 check_added_monitors!(nodes[0], 1);
4284 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4285 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4286 // No commitment_signed so get_event_msg's assert(len == 1) passes
4287 check_added_monitors!(nodes[0], 1);
4289 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4290 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4291 // No commitment_signed so get_event_msg's assert(len == 1) passes
4292 check_added_monitors!(nodes[1], 1);
4294 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4295 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4296 check_added_monitors!(nodes[1], 1);
4298 expect_pending_htlcs_forwardable!(nodes[1]);
4300 let events_5 = nodes[1].node.get_and_clear_pending_events();
4301 assert_eq!(events_5.len(), 1);
4303 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4304 assert_eq!(payment_hash_2, *payment_hash);
4306 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4307 assert!(payment_preimage.is_none());
4308 assert_eq!(payment_secret_2, *payment_secret);
4310 _ => panic!("expected PaymentPurpose::InvoicePayment")
4313 _ => panic!("Unexpected event"),
4316 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4317 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4318 check_added_monitors!(nodes[0], 1);
4320 expect_payment_path_successful!(nodes[0]);
4321 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4324 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4325 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4326 // to avoid our counterparty failing the channel.
4327 let chanmon_cfgs = create_chanmon_cfgs(2);
4328 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4329 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4330 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4332 create_announced_chan_between_nodes(&nodes, 0, 1);
4334 let our_payment_hash = if send_partial_mpp {
4335 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4336 // Use the utility function send_payment_along_path to send the payment with MPP data which
4337 // indicates there are more HTLCs coming.
4338 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.
4339 let payment_id = PaymentId([42; 32]);
4340 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
4341 RecipientOnionFields::secret_only(payment_secret), payment_id, &route).unwrap();
4342 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
4343 RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id,
4344 &None, session_privs[0]).unwrap();
4345 check_added_monitors!(nodes[0], 1);
4346 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4347 assert_eq!(events.len(), 1);
4348 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4349 // hop should *not* yet generate any PaymentClaimable event(s).
4350 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4353 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4356 let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
4357 connect_block(&nodes[0], &block);
4358 connect_block(&nodes[1], &block);
4359 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4360 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4361 block.header.prev_blockhash = block.block_hash();
4362 connect_block(&nodes[0], &block);
4363 connect_block(&nodes[1], &block);
4366 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4368 check_added_monitors!(nodes[1], 1);
4369 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4370 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4371 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4372 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4373 assert!(htlc_timeout_updates.update_fee.is_none());
4375 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4376 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4377 // 100_000 msat as u64, followed by the height at which we failed back above
4378 let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4379 expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4380 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4384 fn test_htlc_timeout() {
4385 do_test_htlc_timeout(true);
4386 do_test_htlc_timeout(false);
4389 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4390 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4391 let chanmon_cfgs = create_chanmon_cfgs(3);
4392 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4393 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4394 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4395 create_announced_chan_between_nodes(&nodes, 0, 1);
4396 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4398 // Make sure all nodes are at the same starting height
4399 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4400 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4401 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4403 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4404 let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4405 nodes[1].node.send_payment_with_route(&route, first_payment_hash,
4406 RecipientOnionFields::secret_only(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4407 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4408 check_added_monitors!(nodes[1], 1);
4410 // Now attempt to route a second payment, which should be placed in the holding cell
4411 let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4412 let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4413 sending_node.node.send_payment_with_route(&route, second_payment_hash,
4414 RecipientOnionFields::secret_only(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4416 check_added_monitors!(nodes[0], 1);
4417 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4418 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4419 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4420 expect_pending_htlcs_forwardable!(nodes[1]);
4422 check_added_monitors!(nodes[1], 0);
4424 connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4425 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4426 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4427 connect_blocks(&nodes[1], 1);
4430 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 }]);
4431 check_added_monitors!(nodes[1], 1);
4432 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4433 assert_eq!(fail_commit.len(), 1);
4434 match fail_commit[0] {
4435 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4436 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4437 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4439 _ => unreachable!(),
4441 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4443 expect_payment_failed!(nodes[1], second_payment_hash, false);
4448 fn test_holding_cell_htlc_add_timeouts() {
4449 do_test_holding_cell_htlc_add_timeouts(false);
4450 do_test_holding_cell_htlc_add_timeouts(true);
4453 macro_rules! check_spendable_outputs {
4454 ($node: expr, $keysinterface: expr) => {
4456 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4457 let mut txn = Vec::new();
4458 let mut all_outputs = Vec::new();
4459 let secp_ctx = Secp256k1::new();
4460 for event in events.drain(..) {
4462 Event::SpendableOutputs { mut outputs, channel_id: _ } => {
4463 for outp in outputs.drain(..) {
4464 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());
4465 all_outputs.push(outp);
4468 _ => panic!("Unexpected event"),
4471 if all_outputs.len() > 1 {
4472 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) {
4482 fn test_claim_sizeable_push_msat() {
4483 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4484 let chanmon_cfgs = create_chanmon_cfgs(2);
4485 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4486 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4487 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4489 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4490 nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4491 check_closed_broadcast!(nodes[1], true);
4492 check_added_monitors!(nodes[1], 1);
4493 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[0].node.get_our_node_id()], 100000);
4494 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4495 assert_eq!(node_txn.len(), 1);
4496 check_spends!(node_txn[0], chan.3);
4497 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
4499 mine_transaction(&nodes[1], &node_txn[0]);
4500 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4502 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4503 assert_eq!(spend_txn.len(), 1);
4504 assert_eq!(spend_txn[0].input.len(), 1);
4505 check_spends!(spend_txn[0], node_txn[0]);
4506 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4510 fn test_claim_on_remote_sizeable_push_msat() {
4511 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4512 // to_remote output is encumbered by a P2WPKH
4513 let chanmon_cfgs = create_chanmon_cfgs(2);
4514 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4515 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4516 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4518 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4519 nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4520 check_closed_broadcast!(nodes[0], true);
4521 check_added_monitors!(nodes[0], 1);
4522 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
4524 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4525 assert_eq!(node_txn.len(), 1);
4526 check_spends!(node_txn[0], chan.3);
4527 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
4529 mine_transaction(&nodes[1], &node_txn[0]);
4530 check_closed_broadcast!(nodes[1], true);
4531 check_added_monitors!(nodes[1], 1);
4532 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4533 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4535 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4536 assert_eq!(spend_txn.len(), 1);
4537 check_spends!(spend_txn[0], node_txn[0]);
4541 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4542 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4543 // to_remote output is encumbered by a P2WPKH
4545 let chanmon_cfgs = create_chanmon_cfgs(2);
4546 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4547 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4548 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4550 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4551 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4552 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4553 assert_eq!(revoked_local_txn[0].input.len(), 1);
4554 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4556 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4557 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4558 check_closed_broadcast!(nodes[1], true);
4559 check_added_monitors!(nodes[1], 1);
4560 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4562 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4563 mine_transaction(&nodes[1], &node_txn[0]);
4564 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4566 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4567 assert_eq!(spend_txn.len(), 3);
4568 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4569 check_spends!(spend_txn[1], node_txn[0]);
4570 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4574 fn test_static_spendable_outputs_preimage_tx() {
4575 let chanmon_cfgs = create_chanmon_cfgs(2);
4576 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4577 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4578 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4580 // Create some initial channels
4581 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4583 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4585 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4586 assert_eq!(commitment_tx[0].input.len(), 1);
4587 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4589 // Settle A's commitment tx on B's chain
4590 nodes[1].node.claim_funds(payment_preimage);
4591 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4592 check_added_monitors!(nodes[1], 1);
4593 mine_transaction(&nodes[1], &commitment_tx[0]);
4594 check_added_monitors!(nodes[1], 1);
4595 let events = nodes[1].node.get_and_clear_pending_msg_events();
4597 MessageSendEvent::UpdateHTLCs { .. } => {},
4598 _ => panic!("Unexpected event"),
4601 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4602 _ => panic!("Unexepected event"),
4605 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4606 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4607 assert_eq!(node_txn.len(), 1);
4608 check_spends!(node_txn[0], commitment_tx[0]);
4609 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4611 mine_transaction(&nodes[1], &node_txn[0]);
4612 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4613 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4615 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4616 assert_eq!(spend_txn.len(), 1);
4617 check_spends!(spend_txn[0], node_txn[0]);
4621 fn test_static_spendable_outputs_timeout_tx() {
4622 let chanmon_cfgs = create_chanmon_cfgs(2);
4623 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4624 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4625 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4627 // Create some initial channels
4628 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4630 // Rebalance the network a bit by relaying one payment through all the channels ...
4631 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4633 let (_, our_payment_hash, ..) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4635 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4636 assert_eq!(commitment_tx[0].input.len(), 1);
4637 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4639 // Settle A's commitment tx on B' chain
4640 mine_transaction(&nodes[1], &commitment_tx[0]);
4641 check_added_monitors!(nodes[1], 1);
4642 let events = nodes[1].node.get_and_clear_pending_msg_events();
4644 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4645 _ => panic!("Unexpected event"),
4647 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4649 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4650 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4651 assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4652 check_spends!(node_txn[0], commitment_tx[0].clone());
4653 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4655 mine_transaction(&nodes[1], &node_txn[0]);
4656 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4657 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4658 expect_payment_failed!(nodes[1], our_payment_hash, false);
4660 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4661 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4662 check_spends!(spend_txn[0], commitment_tx[0]);
4663 check_spends!(spend_txn[1], node_txn[0]);
4664 check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4668 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4669 let chanmon_cfgs = create_chanmon_cfgs(2);
4670 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4671 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4672 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4674 // Create some initial channels
4675 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4677 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4678 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4679 assert_eq!(revoked_local_txn[0].input.len(), 1);
4680 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4682 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4684 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4685 check_closed_broadcast!(nodes[1], true);
4686 check_added_monitors!(nodes[1], 1);
4687 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4689 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4690 assert_eq!(node_txn.len(), 1);
4691 assert_eq!(node_txn[0].input.len(), 2);
4692 check_spends!(node_txn[0], revoked_local_txn[0]);
4694 mine_transaction(&nodes[1], &node_txn[0]);
4695 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4697 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4698 assert_eq!(spend_txn.len(), 1);
4699 check_spends!(spend_txn[0], node_txn[0]);
4703 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4704 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4705 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4706 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4707 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4708 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4710 // Create some initial channels
4711 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4713 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4714 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4715 assert_eq!(revoked_local_txn[0].input.len(), 1);
4716 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4718 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4720 // A will generate HTLC-Timeout from revoked commitment tx
4721 mine_transaction(&nodes[0], &revoked_local_txn[0]);
4722 check_closed_broadcast!(nodes[0], true);
4723 check_added_monitors!(nodes[0], 1);
4724 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4725 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4727 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4728 assert_eq!(revoked_htlc_txn.len(), 1);
4729 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4730 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4731 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4732 assert_ne!(revoked_htlc_txn[0].lock_time.0, 0); // HTLC-Timeout
4734 // B will generate justice tx from A's revoked commitment/HTLC tx
4735 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4736 check_closed_broadcast!(nodes[1], true);
4737 check_added_monitors!(nodes[1], 1);
4738 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4740 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4741 assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4742 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4743 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4744 // transactions next...
4745 assert_eq!(node_txn[0].input.len(), 3);
4746 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4748 assert_eq!(node_txn[1].input.len(), 2);
4749 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4750 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4751 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4753 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4754 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4757 mine_transaction(&nodes[1], &node_txn[1]);
4758 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4760 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4761 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4762 assert_eq!(spend_txn.len(), 1);
4763 assert_eq!(spend_txn[0].input.len(), 1);
4764 check_spends!(spend_txn[0], node_txn[1]);
4768 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4769 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4770 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4771 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4772 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4773 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4775 // Create some initial channels
4776 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4778 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4779 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4780 assert_eq!(revoked_local_txn[0].input.len(), 1);
4781 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4783 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4784 assert_eq!(revoked_local_txn[0].output.len(), 2);
4786 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4788 // B will generate HTLC-Success from revoked commitment tx
4789 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4790 check_closed_broadcast!(nodes[1], true);
4791 check_added_monitors!(nodes[1], 1);
4792 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4793 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4795 assert_eq!(revoked_htlc_txn.len(), 1);
4796 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4797 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4798 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4800 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4801 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4802 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4804 // A will generate justice tx from B's revoked commitment/HTLC tx
4805 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4806 check_closed_broadcast!(nodes[0], true);
4807 check_added_monitors!(nodes[0], 1);
4808 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4810 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4811 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4813 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4814 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4815 // transactions next...
4816 assert_eq!(node_txn[0].input.len(), 2);
4817 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4818 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4819 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4821 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4822 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4825 assert_eq!(node_txn[1].input.len(), 1);
4826 check_spends!(node_txn[1], revoked_htlc_txn[0]);
4828 mine_transaction(&nodes[0], &node_txn[1]);
4829 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4831 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4832 // didn't try to generate any new transactions.
4834 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4835 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4836 assert_eq!(spend_txn.len(), 3);
4837 assert_eq!(spend_txn[0].input.len(), 1);
4838 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4839 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4840 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4841 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4845 fn test_onchain_to_onchain_claim() {
4846 // Test that in case of channel closure, we detect the state of output and claim HTLC
4847 // on downstream peer's remote commitment tx.
4848 // First, have C claim an HTLC against its own latest commitment transaction.
4849 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4851 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4854 let chanmon_cfgs = create_chanmon_cfgs(3);
4855 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4856 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4857 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4859 // Create some initial channels
4860 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4861 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4863 // Ensure all nodes are at the same height
4864 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4865 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4866 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4867 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4869 // Rebalance the network a bit by relaying one payment through all the channels ...
4870 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4871 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4873 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4874 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4875 check_spends!(commitment_tx[0], chan_2.3);
4876 nodes[2].node.claim_funds(payment_preimage);
4877 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4878 check_added_monitors!(nodes[2], 1);
4879 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4880 assert!(updates.update_add_htlcs.is_empty());
4881 assert!(updates.update_fail_htlcs.is_empty());
4882 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4883 assert!(updates.update_fail_malformed_htlcs.is_empty());
4885 mine_transaction(&nodes[2], &commitment_tx[0]);
4886 check_closed_broadcast!(nodes[2], true);
4887 check_added_monitors!(nodes[2], 1);
4888 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4890 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4891 assert_eq!(c_txn.len(), 1);
4892 check_spends!(c_txn[0], commitment_tx[0]);
4893 assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4894 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4895 assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
4897 // 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
4898 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![commitment_tx[0].clone(), c_txn[0].clone()]));
4899 check_added_monitors!(nodes[1], 1);
4900 let events = nodes[1].node.get_and_clear_pending_events();
4901 assert_eq!(events.len(), 2);
4903 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4904 _ => panic!("Unexpected event"),
4907 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
4908 assert_eq!(fee_earned_msat, Some(1000));
4909 assert_eq!(prev_channel_id, Some(chan_1.2));
4910 assert_eq!(claim_from_onchain_tx, true);
4911 assert_eq!(next_channel_id, Some(chan_2.2));
4912 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
4914 _ => panic!("Unexpected event"),
4916 check_added_monitors!(nodes[1], 1);
4917 let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4918 assert_eq!(msg_events.len(), 3);
4919 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut msg_events);
4920 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut msg_events);
4922 match nodes_2_event {
4923 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
4924 _ => panic!("Unexpected event"),
4927 match nodes_0_event {
4928 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, .. } } => {
4929 assert!(update_add_htlcs.is_empty());
4930 assert!(update_fail_htlcs.is_empty());
4931 assert_eq!(update_fulfill_htlcs.len(), 1);
4932 assert!(update_fail_malformed_htlcs.is_empty());
4933 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4935 _ => panic!("Unexpected event"),
4938 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
4939 match msg_events[0] {
4940 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4941 _ => panic!("Unexpected event"),
4944 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4945 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4946 mine_transaction(&nodes[1], &commitment_tx[0]);
4947 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4948 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4949 // ChannelMonitor: HTLC-Success tx
4950 assert_eq!(b_txn.len(), 1);
4951 check_spends!(b_txn[0], commitment_tx[0]);
4952 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4953 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4954 assert_eq!(b_txn[0].lock_time.0, nodes[1].best_block_info().1); // Success tx
4956 check_closed_broadcast!(nodes[1], true);
4957 check_added_monitors!(nodes[1], 1);
4961 fn test_duplicate_payment_hash_one_failure_one_success() {
4962 // Topology : A --> B --> C --> D
4963 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4964 // Note that because C will refuse to generate two payment secrets for the same payment hash,
4965 // we forward one of the payments onwards to D.
4966 let chanmon_cfgs = create_chanmon_cfgs(4);
4967 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4968 // When this test was written, the default base fee floated based on the HTLC count.
4969 // It is now fixed, so we simply set the fee to the expected value here.
4970 let mut config = test_default_channel_config();
4971 config.channel_config.forwarding_fee_base_msat = 196;
4972 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4973 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4974 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4976 create_announced_chan_between_nodes(&nodes, 0, 1);
4977 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4978 create_announced_chan_between_nodes(&nodes, 2, 3);
4980 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4981 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4982 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4983 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4984 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4986 let (our_payment_preimage, duplicate_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
4988 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
4989 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4990 // script push size limit so that the below script length checks match
4991 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
4992 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV - 40)
4993 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
4994 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000);
4995 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
4997 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4998 assert_eq!(commitment_txn[0].input.len(), 1);
4999 check_spends!(commitment_txn[0], chan_2.3);
5001 mine_transaction(&nodes[1], &commitment_txn[0]);
5002 check_closed_broadcast!(nodes[1], true);
5003 check_added_monitors!(nodes[1], 1);
5004 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
5005 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
5007 let htlc_timeout_tx;
5008 { // Extract one of the two HTLC-Timeout transaction
5009 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5010 // ChannelMonitor: timeout tx * 2-or-3
5011 assert!(node_txn.len() == 2 || node_txn.len() == 3);
5013 check_spends!(node_txn[0], commitment_txn[0]);
5014 assert_eq!(node_txn[0].input.len(), 1);
5015 assert_eq!(node_txn[0].output.len(), 1);
5017 if node_txn.len() > 2 {
5018 check_spends!(node_txn[1], commitment_txn[0]);
5019 assert_eq!(node_txn[1].input.len(), 1);
5020 assert_eq!(node_txn[1].output.len(), 1);
5021 assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
5023 check_spends!(node_txn[2], commitment_txn[0]);
5024 assert_eq!(node_txn[2].input.len(), 1);
5025 assert_eq!(node_txn[2].output.len(), 1);
5026 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
5028 check_spends!(node_txn[1], commitment_txn[0]);
5029 assert_eq!(node_txn[1].input.len(), 1);
5030 assert_eq!(node_txn[1].output.len(), 1);
5031 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
5034 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5035 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5036 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
5037 // (with value 900 sats) will be claimed in the below `claim_funds` call.
5038 if node_txn.len() > 2 {
5039 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5040 htlc_timeout_tx = if node_txn[2].output[0].value < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
5042 htlc_timeout_tx = if node_txn[0].output[0].value < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
5046 nodes[2].node.claim_funds(our_payment_preimage);
5047 expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
5049 mine_transaction(&nodes[2], &commitment_txn[0]);
5050 check_added_monitors!(nodes[2], 2);
5051 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5052 let events = nodes[2].node.get_and_clear_pending_msg_events();
5054 MessageSendEvent::UpdateHTLCs { .. } => {},
5055 _ => panic!("Unexpected event"),
5058 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5059 _ => panic!("Unexepected event"),
5061 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5062 assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
5063 check_spends!(htlc_success_txn[0], commitment_txn[0]);
5064 check_spends!(htlc_success_txn[1], commitment_txn[0]);
5065 assert_eq!(htlc_success_txn[0].input.len(), 1);
5066 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5067 assert_eq!(htlc_success_txn[1].input.len(), 1);
5068 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5069 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5070 assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5072 mine_transaction(&nodes[1], &htlc_timeout_tx);
5073 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5074 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 }]);
5075 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5076 assert!(htlc_updates.update_add_htlcs.is_empty());
5077 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5078 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5079 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5080 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5081 check_added_monitors!(nodes[1], 1);
5083 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5084 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5086 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5088 expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5090 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5091 mine_transaction(&nodes[1], &htlc_success_txn[1]);
5092 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
5093 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5094 assert!(updates.update_add_htlcs.is_empty());
5095 assert!(updates.update_fail_htlcs.is_empty());
5096 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5097 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5098 assert!(updates.update_fail_malformed_htlcs.is_empty());
5099 check_added_monitors!(nodes[1], 1);
5101 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5102 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5103 expect_payment_sent(&nodes[0], our_payment_preimage, None, true, true);
5107 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5108 let chanmon_cfgs = create_chanmon_cfgs(2);
5109 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5110 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5111 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5113 // Create some initial channels
5114 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5116 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
5117 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5118 assert_eq!(local_txn.len(), 1);
5119 assert_eq!(local_txn[0].input.len(), 1);
5120 check_spends!(local_txn[0], chan_1.3);
5122 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5123 nodes[1].node.claim_funds(payment_preimage);
5124 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
5125 check_added_monitors!(nodes[1], 1);
5127 mine_transaction(&nodes[1], &local_txn[0]);
5128 check_added_monitors!(nodes[1], 1);
5129 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
5130 let events = nodes[1].node.get_and_clear_pending_msg_events();
5132 MessageSendEvent::UpdateHTLCs { .. } => {},
5133 _ => panic!("Unexpected event"),
5136 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5137 _ => panic!("Unexepected event"),
5140 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5141 assert_eq!(node_txn.len(), 1);
5142 assert_eq!(node_txn[0].input.len(), 1);
5143 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5144 check_spends!(node_txn[0], local_txn[0]);
5148 mine_transaction(&nodes[1], &node_tx);
5149 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5151 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5152 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5153 assert_eq!(spend_txn.len(), 1);
5154 assert_eq!(spend_txn[0].input.len(), 1);
5155 check_spends!(spend_txn[0], node_tx);
5156 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5159 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5160 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5161 // unrevoked commitment transaction.
5162 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5163 // a remote RAA before they could be failed backwards (and combinations thereof).
5164 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5165 // use the same payment hashes.
5166 // Thus, we use a six-node network:
5171 // And test where C fails back to A/B when D announces its latest commitment transaction
5172 let chanmon_cfgs = create_chanmon_cfgs(6);
5173 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5174 // When this test was written, the default base fee floated based on the HTLC count.
5175 // It is now fixed, so we simply set the fee to the expected value here.
5176 let mut config = test_default_channel_config();
5177 config.channel_config.forwarding_fee_base_msat = 196;
5178 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5179 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5180 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5182 let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2);
5183 let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5184 let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5185 let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
5186 let chan_3_5 = create_announced_chan_between_nodes(&nodes, 3, 5);
5188 // Rebalance and check output sanity...
5189 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5190 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5191 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
5193 let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
5194 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().context().holder_dust_limit_satoshis;
5196 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
5198 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
5199 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5201 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
5203 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
5205 let (_, payment_hash_3, ..) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5207 let (_, payment_hash_4, ..) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5208 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5210 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());
5212 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());
5215 let (_, payment_hash_5, ..) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5217 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5218 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
5221 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
5223 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5224 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());
5226 // Double-check that six of the new HTLC were added
5227 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5228 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5229 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5230 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5232 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5233 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5234 nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5235 nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5236 nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5237 nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5238 check_added_monitors!(nodes[4], 0);
5240 let failed_destinations = vec![
5241 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5242 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5243 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5244 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5246 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5247 check_added_monitors!(nodes[4], 1);
5249 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5250 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5251 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5252 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5253 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5254 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5256 // Fail 3rd below-dust and 7th above-dust HTLCs
5257 nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5258 nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5259 check_added_monitors!(nodes[5], 0);
5261 let failed_destinations_2 = vec![
5262 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5263 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5265 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5266 check_added_monitors!(nodes[5], 1);
5268 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5269 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5270 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5271 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5273 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5275 // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5276 let failed_destinations_3 = vec![
5277 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5278 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5279 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5280 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5281 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5282 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5284 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5285 check_added_monitors!(nodes[3], 1);
5286 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5287 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5288 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5289 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5290 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5291 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5292 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5293 if deliver_last_raa {
5294 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5296 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5299 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5300 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5301 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5302 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5304 // We now broadcast the latest commitment transaction, which *should* result in failures for
5305 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5306 // the non-broadcast above-dust HTLCs.
5308 // Alternatively, we may broadcast the previous commitment transaction, which should only
5309 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5310 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5312 if announce_latest {
5313 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5315 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5317 let events = nodes[2].node.get_and_clear_pending_events();
5318 let close_event = if deliver_last_raa {
5319 assert_eq!(events.len(), 2 + 6);
5320 events.last().clone().unwrap()
5322 assert_eq!(events.len(), 1);
5323 events.last().clone().unwrap()
5326 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5327 _ => panic!("Unexpected event"),
5330 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5331 check_closed_broadcast!(nodes[2], true);
5332 if deliver_last_raa {
5333 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5335 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();
5336 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5338 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5339 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5341 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5344 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5346 check_added_monitors!(nodes[2], 3);
5348 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5349 assert_eq!(cs_msgs.len(), 2);
5350 let mut a_done = false;
5351 for msg in cs_msgs {
5353 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5354 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5355 // should be failed-backwards here.
5356 let target = if *node_id == nodes[0].node.get_our_node_id() {
5357 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5358 for htlc in &updates.update_fail_htlcs {
5359 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 });
5361 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5366 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5367 for htlc in &updates.update_fail_htlcs {
5368 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5370 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5371 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5374 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5375 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5376 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5377 if announce_latest {
5378 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5379 if *node_id == nodes[0].node.get_our_node_id() {
5380 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5383 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5385 _ => panic!("Unexpected event"),
5389 let as_events = nodes[0].node.get_and_clear_pending_events();
5390 assert_eq!(as_events.len(), if announce_latest { 10 } else { 6 });
5391 let mut as_failds = HashSet::new();
5392 let mut as_updates = 0;
5393 for event in as_events.iter() {
5394 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5395 assert!(as_failds.insert(*payment_hash));
5396 if *payment_hash != payment_hash_2 {
5397 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5399 assert!(!payment_failed_permanently);
5401 if let PathFailure::OnPath { network_update: Some(_) } = failure {
5404 } else if let &Event::PaymentFailed { .. } = event {
5405 } else { panic!("Unexpected event"); }
5407 assert!(as_failds.contains(&payment_hash_1));
5408 assert!(as_failds.contains(&payment_hash_2));
5409 if announce_latest {
5410 assert!(as_failds.contains(&payment_hash_3));
5411 assert!(as_failds.contains(&payment_hash_5));
5413 assert!(as_failds.contains(&payment_hash_6));
5415 let bs_events = nodes[1].node.get_and_clear_pending_events();
5416 assert_eq!(bs_events.len(), if announce_latest { 8 } else { 6 });
5417 let mut bs_failds = HashSet::new();
5418 let mut bs_updates = 0;
5419 for event in bs_events.iter() {
5420 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5421 assert!(bs_failds.insert(*payment_hash));
5422 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5423 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5425 assert!(!payment_failed_permanently);
5427 if let PathFailure::OnPath { network_update: Some(_) } = failure {
5430 } else if let &Event::PaymentFailed { .. } = event {
5431 } else { panic!("Unexpected event"); }
5433 assert!(bs_failds.contains(&payment_hash_1));
5434 assert!(bs_failds.contains(&payment_hash_2));
5435 if announce_latest {
5436 assert!(bs_failds.contains(&payment_hash_4));
5438 assert!(bs_failds.contains(&payment_hash_5));
5440 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5441 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5442 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5443 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5444 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5445 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5449 fn test_fail_backwards_latest_remote_announce_a() {
5450 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5454 fn test_fail_backwards_latest_remote_announce_b() {
5455 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5459 fn test_fail_backwards_previous_remote_announce() {
5460 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5461 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5462 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5466 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5467 let chanmon_cfgs = create_chanmon_cfgs(2);
5468 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5469 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5470 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5472 // Create some initial channels
5473 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5475 let (_, our_payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5476 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5477 assert_eq!(local_txn[0].input.len(), 1);
5478 check_spends!(local_txn[0], chan_1.3);
5480 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5481 mine_transaction(&nodes[0], &local_txn[0]);
5482 check_closed_broadcast!(nodes[0], true);
5483 check_added_monitors!(nodes[0], 1);
5484 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5485 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5487 let htlc_timeout = {
5488 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5489 assert_eq!(node_txn.len(), 1);
5490 assert_eq!(node_txn[0].input.len(), 1);
5491 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5492 check_spends!(node_txn[0], local_txn[0]);
5496 mine_transaction(&nodes[0], &htlc_timeout);
5497 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5498 expect_payment_failed!(nodes[0], our_payment_hash, false);
5500 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5501 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5502 assert_eq!(spend_txn.len(), 3);
5503 check_spends!(spend_txn[0], local_txn[0]);
5504 assert_eq!(spend_txn[1].input.len(), 1);
5505 check_spends!(spend_txn[1], htlc_timeout);
5506 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5507 assert_eq!(spend_txn[2].input.len(), 2);
5508 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5509 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5510 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5514 fn test_key_derivation_params() {
5515 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5516 // manager rotation to test that `channel_keys_id` returned in
5517 // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5518 // then derive a `delayed_payment_key`.
5520 let chanmon_cfgs = create_chanmon_cfgs(3);
5522 // We manually create the node configuration to backup the seed.
5523 let seed = [42; 32];
5524 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5525 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);
5526 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[0].logger));
5527 let scorer = RwLock::new(test_utils::TestScorer::new());
5528 let router = test_utils::TestRouter::new(network_graph.clone(), &scorer);
5529 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)) };
5530 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5531 node_cfgs.remove(0);
5532 node_cfgs.insert(0, node);
5534 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5535 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5537 // Create some initial channels
5538 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5540 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2);
5541 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5542 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5544 // Ensure all nodes are at the same height
5545 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5546 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5547 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5548 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5550 let (_, our_payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5551 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5552 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5553 assert_eq!(local_txn_1[0].input.len(), 1);
5554 check_spends!(local_txn_1[0], chan_1.3);
5556 // We check funding pubkey are unique
5557 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]));
5558 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]));
5559 if from_0_funding_key_0 == from_1_funding_key_0
5560 || from_0_funding_key_0 == from_1_funding_key_1
5561 || from_0_funding_key_1 == from_1_funding_key_0
5562 || from_0_funding_key_1 == from_1_funding_key_1 {
5563 panic!("Funding pubkeys aren't unique");
5566 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5567 mine_transaction(&nodes[0], &local_txn_1[0]);
5568 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5569 check_closed_broadcast!(nodes[0], true);
5570 check_added_monitors!(nodes[0], 1);
5571 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5573 let htlc_timeout = {
5574 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5575 assert_eq!(node_txn.len(), 1);
5576 assert_eq!(node_txn[0].input.len(), 1);
5577 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5578 check_spends!(node_txn[0], local_txn_1[0]);
5582 mine_transaction(&nodes[0], &htlc_timeout);
5583 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5584 expect_payment_failed!(nodes[0], our_payment_hash, false);
5586 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5587 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5588 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5589 assert_eq!(spend_txn.len(), 3);
5590 check_spends!(spend_txn[0], local_txn_1[0]);
5591 assert_eq!(spend_txn[1].input.len(), 1);
5592 check_spends!(spend_txn[1], htlc_timeout);
5593 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5594 assert_eq!(spend_txn[2].input.len(), 2);
5595 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5596 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5597 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5601 fn test_static_output_closing_tx() {
5602 let chanmon_cfgs = create_chanmon_cfgs(2);
5603 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5604 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5605 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5607 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5609 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5610 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5612 mine_transaction(&nodes[0], &closing_tx);
5613 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
5614 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5616 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5617 assert_eq!(spend_txn.len(), 1);
5618 check_spends!(spend_txn[0], closing_tx);
5620 mine_transaction(&nodes[1], &closing_tx);
5621 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
5622 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5624 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5625 assert_eq!(spend_txn.len(), 1);
5626 check_spends!(spend_txn[0], closing_tx);
5629 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5630 let chanmon_cfgs = create_chanmon_cfgs(2);
5631 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5632 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5633 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5634 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5636 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5638 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5639 // present in B's local commitment transaction, but none of A's commitment transactions.
5640 nodes[1].node.claim_funds(payment_preimage);
5641 check_added_monitors!(nodes[1], 1);
5642 expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5644 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5645 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5646 expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
5648 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5649 check_added_monitors!(nodes[0], 1);
5650 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5651 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5652 check_added_monitors!(nodes[1], 1);
5654 let starting_block = nodes[1].best_block_info();
5655 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5656 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5657 connect_block(&nodes[1], &block);
5658 block.header.prev_blockhash = block.block_hash();
5660 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5661 check_closed_broadcast!(nodes[1], true);
5662 check_added_monitors!(nodes[1], 1);
5663 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[0].node.get_our_node_id()], 100000);
5666 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5667 let chanmon_cfgs = create_chanmon_cfgs(2);
5668 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5669 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5670 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5671 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5673 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5674 nodes[0].node.send_payment_with_route(&route, payment_hash,
5675 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
5676 check_added_monitors!(nodes[0], 1);
5678 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5680 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5681 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5682 // to "time out" the HTLC.
5684 let starting_block = nodes[1].best_block_info();
5685 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5687 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5688 connect_block(&nodes[0], &block);
5689 block.header.prev_blockhash = block.block_hash();
5691 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5692 check_closed_broadcast!(nodes[0], true);
5693 check_added_monitors!(nodes[0], 1);
5694 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
5697 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5698 let chanmon_cfgs = create_chanmon_cfgs(3);
5699 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5700 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5701 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5702 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5704 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5705 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5706 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5707 // actually revoked.
5708 let htlc_value = if use_dust { 50000 } else { 3000000 };
5709 let (_, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5710 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5711 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5712 check_added_monitors!(nodes[1], 1);
5714 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5715 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5716 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5717 check_added_monitors!(nodes[0], 1);
5718 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5719 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5720 check_added_monitors!(nodes[1], 1);
5721 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5722 check_added_monitors!(nodes[1], 1);
5723 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5725 if check_revoke_no_close {
5726 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5727 check_added_monitors!(nodes[0], 1);
5730 let starting_block = nodes[1].best_block_info();
5731 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5732 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5733 connect_block(&nodes[0], &block);
5734 block.header.prev_blockhash = block.block_hash();
5736 if !check_revoke_no_close {
5737 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5738 check_closed_broadcast!(nodes[0], true);
5739 check_added_monitors!(nodes[0], 1);
5740 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
5742 expect_payment_failed!(nodes[0], our_payment_hash, true);
5746 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5747 // There are only a few cases to test here:
5748 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5749 // broadcastable commitment transactions result in channel closure,
5750 // * its included in an unrevoked-but-previous remote commitment transaction,
5751 // * its included in the latest remote or local commitment transactions.
5752 // We test each of the three possible commitment transactions individually and use both dust and
5754 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5755 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5756 // tested for at least one of the cases in other tests.
5758 fn htlc_claim_single_commitment_only_a() {
5759 do_htlc_claim_local_commitment_only(true);
5760 do_htlc_claim_local_commitment_only(false);
5762 do_htlc_claim_current_remote_commitment_only(true);
5763 do_htlc_claim_current_remote_commitment_only(false);
5767 fn htlc_claim_single_commitment_only_b() {
5768 do_htlc_claim_previous_remote_commitment_only(true, false);
5769 do_htlc_claim_previous_remote_commitment_only(false, false);
5770 do_htlc_claim_previous_remote_commitment_only(true, true);
5771 do_htlc_claim_previous_remote_commitment_only(false, true);
5776 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5777 let chanmon_cfgs = create_chanmon_cfgs(2);
5778 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5779 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5780 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5781 // Force duplicate randomness for every get-random call
5782 for node in nodes.iter() {
5783 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5786 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5787 let channel_value_satoshis=10000;
5788 let push_msat=10001;
5789 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5790 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5791 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5792 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5794 // Create a second channel with the same random values. This used to panic due to a colliding
5795 // channel_id, but now panics due to a colliding outbound SCID alias.
5796 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5800 fn bolt2_open_channel_sending_node_checks_part2() {
5801 let chanmon_cfgs = create_chanmon_cfgs(2);
5802 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5803 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5804 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5806 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5807 let channel_value_satoshis=2^24;
5808 let push_msat=10001;
5809 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5811 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5812 let channel_value_satoshis=10000;
5813 // Test when push_msat is equal to 1000 * funding_satoshis.
5814 let push_msat=1000*channel_value_satoshis+1;
5815 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5817 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5818 let channel_value_satoshis=10000;
5819 let push_msat=10001;
5820 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
5821 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5822 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5824 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5825 // 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
5826 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5828 // 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.
5829 assert!(BREAKDOWN_TIMEOUT>0);
5830 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5832 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5833 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5834 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5836 // 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.
5837 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5838 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5839 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5840 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5841 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5845 fn bolt2_open_channel_sane_dust_limit() {
5846 let chanmon_cfgs = create_chanmon_cfgs(2);
5847 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5848 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5849 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5851 let channel_value_satoshis=1000000;
5852 let push_msat=10001;
5853 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5854 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5855 node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5856 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5858 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5859 let events = nodes[1].node.get_and_clear_pending_msg_events();
5860 let err_msg = match events[0] {
5861 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5864 _ => panic!("Unexpected event"),
5866 assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5869 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5870 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5871 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5872 // is no longer affordable once it's freed.
5874 fn test_fail_holding_cell_htlc_upon_free() {
5875 let chanmon_cfgs = create_chanmon_cfgs(2);
5876 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5877 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5878 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5879 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5881 // First nodes[0] generates an update_fee, setting the channel's
5882 // pending_update_fee.
5884 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5885 *feerate_lock += 20;
5887 nodes[0].node.timer_tick_occurred();
5888 check_added_monitors!(nodes[0], 1);
5890 let events = nodes[0].node.get_and_clear_pending_msg_events();
5891 assert_eq!(events.len(), 1);
5892 let (update_msg, commitment_signed) = match events[0] {
5893 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5894 (update_fee.as_ref(), commitment_signed)
5896 _ => panic!("Unexpected event"),
5899 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5901 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5902 let channel_reserve = chan_stat.channel_reserve_msat;
5903 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5904 let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
5906 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5907 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
5908 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5910 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5911 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5912 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5913 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5914 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5916 // Flush the pending fee update.
5917 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5918 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5919 check_added_monitors!(nodes[1], 1);
5920 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5921 check_added_monitors!(nodes[0], 1);
5923 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5924 // HTLC, but now that the fee has been raised the payment will now fail, causing
5925 // us to surface its failure to the user.
5926 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5927 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5928 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Freeing holding cell with 1 HTLC updates in channel {}", chan.2), 1);
5930 // Check that the payment failed to be sent out.
5931 let events = nodes[0].node.get_and_clear_pending_events();
5932 assert_eq!(events.len(), 2);
5934 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5935 assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5936 assert_eq!(our_payment_hash.clone(), *payment_hash);
5937 assert_eq!(*payment_failed_permanently, false);
5938 assert_eq!(*short_channel_id, Some(route.paths[0].hops[0].short_channel_id));
5940 _ => panic!("Unexpected event"),
5943 &Event::PaymentFailed { ref payment_hash, .. } => {
5944 assert_eq!(our_payment_hash.clone(), *payment_hash);
5946 _ => panic!("Unexpected event"),
5950 // Test that if multiple HTLCs are released from the holding cell and one is
5951 // valid but the other is no longer valid upon release, the valid HTLC can be
5952 // successfully completed while the other one fails as expected.
5954 fn test_free_and_fail_holding_cell_htlcs() {
5955 let chanmon_cfgs = create_chanmon_cfgs(2);
5956 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5957 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5958 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5959 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5961 // First nodes[0] generates an update_fee, setting the channel's
5962 // pending_update_fee.
5964 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5965 *feerate_lock += 200;
5967 nodes[0].node.timer_tick_occurred();
5968 check_added_monitors!(nodes[0], 1);
5970 let events = nodes[0].node.get_and_clear_pending_msg_events();
5971 assert_eq!(events.len(), 1);
5972 let (update_msg, commitment_signed) = match events[0] {
5973 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5974 (update_fee.as_ref(), commitment_signed)
5976 _ => panic!("Unexpected event"),
5979 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5981 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5982 let channel_reserve = chan_stat.channel_reserve_msat;
5983 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5984 let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
5986 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5988 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features) - amt_1;
5989 let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5990 let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5992 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5993 nodes[0].node.send_payment_with_route(&route_1, payment_hash_1,
5994 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
5995 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5996 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
5997 let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
5998 nodes[0].node.send_payment_with_route(&route_2, payment_hash_2,
5999 RecipientOnionFields::secret_only(payment_secret_2), payment_id_2).unwrap();
6000 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6001 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6003 // Flush the pending fee update.
6004 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6005 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6006 check_added_monitors!(nodes[1], 1);
6007 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6008 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6009 check_added_monitors!(nodes[0], 2);
6011 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6012 // but now that the fee has been raised the second payment will now fail, causing us
6013 // to surface its failure to the user. The first payment should succeed.
6014 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6015 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6016 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Freeing holding cell with 2 HTLC updates in channel {}", chan.2), 1);
6018 // Check that the second payment failed to be sent out.
6019 let events = nodes[0].node.get_and_clear_pending_events();
6020 assert_eq!(events.len(), 2);
6022 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
6023 assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6024 assert_eq!(payment_hash_2.clone(), *payment_hash);
6025 assert_eq!(*payment_failed_permanently, false);
6026 assert_eq!(*short_channel_id, Some(route_2.paths[0].hops[0].short_channel_id));
6028 _ => panic!("Unexpected event"),
6031 &Event::PaymentFailed { ref payment_hash, .. } => {
6032 assert_eq!(payment_hash_2.clone(), *payment_hash);
6034 _ => panic!("Unexpected event"),
6037 // Complete the first payment and the RAA from the fee update.
6038 let (payment_event, send_raa_event) = {
6039 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6040 assert_eq!(msgs.len(), 2);
6041 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6043 let raa = match send_raa_event {
6044 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6045 _ => panic!("Unexpected event"),
6047 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6048 check_added_monitors!(nodes[1], 1);
6049 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6050 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6051 let events = nodes[1].node.get_and_clear_pending_events();
6052 assert_eq!(events.len(), 1);
6054 Event::PendingHTLCsForwardable { .. } => {},
6055 _ => panic!("Unexpected event"),
6057 nodes[1].node.process_pending_htlc_forwards();
6058 let events = nodes[1].node.get_and_clear_pending_events();
6059 assert_eq!(events.len(), 1);
6061 Event::PaymentClaimable { .. } => {},
6062 _ => panic!("Unexpected event"),
6064 nodes[1].node.claim_funds(payment_preimage_1);
6065 check_added_monitors!(nodes[1], 1);
6066 expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
6068 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6069 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6070 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6071 expect_payment_sent!(nodes[0], payment_preimage_1);
6074 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6075 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6076 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6079 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6080 let chanmon_cfgs = create_chanmon_cfgs(3);
6081 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6082 // Avoid having to include routing fees in calculations
6083 let mut config = test_default_channel_config();
6084 config.channel_config.forwarding_fee_base_msat = 0;
6085 config.channel_config.forwarding_fee_proportional_millionths = 0;
6086 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6087 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6088 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6089 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
6091 // First nodes[1] generates an update_fee, setting the channel's
6092 // pending_update_fee.
6094 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6095 *feerate_lock += 20;
6097 nodes[1].node.timer_tick_occurred();
6098 check_added_monitors!(nodes[1], 1);
6100 let events = nodes[1].node.get_and_clear_pending_msg_events();
6101 assert_eq!(events.len(), 1);
6102 let (update_msg, commitment_signed) = match events[0] {
6103 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6104 (update_fee.as_ref(), commitment_signed)
6106 _ => panic!("Unexpected event"),
6109 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6111 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan_0_1.2);
6112 let channel_reserve = chan_stat.channel_reserve_msat;
6113 let feerate = get_feerate!(nodes[0], nodes[1], chan_0_1.2);
6114 let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_0_1.2);
6116 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6117 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
6118 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6119 let payment_event = {
6120 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6121 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6122 check_added_monitors!(nodes[0], 1);
6124 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6125 assert_eq!(events.len(), 1);
6127 SendEvent::from_event(events.remove(0))
6129 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6130 check_added_monitors!(nodes[1], 0);
6131 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6132 expect_pending_htlcs_forwardable!(nodes[1]);
6134 chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
6135 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6137 // Flush the pending fee update.
6138 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6139 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6140 check_added_monitors!(nodes[2], 1);
6141 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6142 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6143 check_added_monitors!(nodes[1], 2);
6145 // A final RAA message is generated to finalize the fee update.
6146 let events = nodes[1].node.get_and_clear_pending_msg_events();
6147 assert_eq!(events.len(), 1);
6149 let raa_msg = match &events[0] {
6150 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6153 _ => panic!("Unexpected event"),
6156 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6157 check_added_monitors!(nodes[2], 1);
6158 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6160 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6161 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6162 assert_eq!(process_htlc_forwards_event.len(), 2);
6163 match &process_htlc_forwards_event[0] {
6164 &Event::PendingHTLCsForwardable { .. } => {},
6165 _ => panic!("Unexpected event"),
6168 // In response, we call ChannelManager's process_pending_htlc_forwards
6169 nodes[1].node.process_pending_htlc_forwards();
6170 check_added_monitors!(nodes[1], 1);
6172 // This causes the HTLC to be failed backwards.
6173 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6174 assert_eq!(fail_event.len(), 1);
6175 let (fail_msg, commitment_signed) = match &fail_event[0] {
6176 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6177 assert_eq!(updates.update_add_htlcs.len(), 0);
6178 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6179 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6180 assert_eq!(updates.update_fail_htlcs.len(), 1);
6181 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6183 _ => panic!("Unexpected event"),
6186 // Pass the failure messages back to nodes[0].
6187 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6188 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6190 // Complete the HTLC failure+removal process.
6191 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6192 check_added_monitors!(nodes[0], 1);
6193 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6194 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6195 check_added_monitors!(nodes[1], 2);
6196 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6197 assert_eq!(final_raa_event.len(), 1);
6198 let raa = match &final_raa_event[0] {
6199 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6200 _ => panic!("Unexpected event"),
6202 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6203 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6204 check_added_monitors!(nodes[0], 1);
6207 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6208 // 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.
6209 //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.
6212 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6213 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6214 let chanmon_cfgs = create_chanmon_cfgs(2);
6215 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6216 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6217 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6218 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6220 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6221 route.paths[0].hops[0].fee_msat = 100;
6223 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6224 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6225 ), true, APIError::ChannelUnavailable { .. }, {});
6226 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6230 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6231 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6232 let chanmon_cfgs = create_chanmon_cfgs(2);
6233 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6234 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6235 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6236 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6238 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6239 route.paths[0].hops[0].fee_msat = 0;
6240 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6241 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)),
6242 true, APIError::ChannelUnavailable { ref err },
6243 assert_eq!(err, "Cannot send 0-msat HTLC"));
6245 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6246 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send 0-msat HTLC", 1);
6250 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6251 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6252 let chanmon_cfgs = create_chanmon_cfgs(2);
6253 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6254 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6255 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6256 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6258 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6259 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6260 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6261 check_added_monitors!(nodes[0], 1);
6262 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6263 updates.update_add_htlcs[0].amount_msat = 0;
6265 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6266 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6267 check_closed_broadcast!(nodes[1], true).unwrap();
6268 check_added_monitors!(nodes[1], 1);
6269 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() },
6270 [nodes[0].node.get_our_node_id()], 100000);
6274 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6275 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6276 //It is enforced when constructing a route.
6277 let chanmon_cfgs = create_chanmon_cfgs(2);
6278 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6279 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6280 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6281 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6283 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6284 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
6285 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);
6286 route.paths[0].hops.last_mut().unwrap().cltv_expiry_delta = 500000001;
6287 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6288 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6289 ), true, APIError::InvalidRoute { ref err },
6290 assert_eq!(err, &"Channel CLTV overflowed?"));
6294 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6295 //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.
6296 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6297 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6298 let chanmon_cfgs = create_chanmon_cfgs(2);
6299 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6300 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6301 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6302 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6303 let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6304 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context().counterparty_max_accepted_htlcs as u64;
6306 // Fetch a route in advance as we will be unable to once we're unable to send.
6307 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6308 for i in 0..max_accepted_htlcs {
6309 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6310 let payment_event = {
6311 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6312 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6313 check_added_monitors!(nodes[0], 1);
6315 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6316 assert_eq!(events.len(), 1);
6317 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6318 assert_eq!(htlcs[0].htlc_id, i);
6322 SendEvent::from_event(events.remove(0))
6324 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6325 check_added_monitors!(nodes[1], 0);
6326 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6328 expect_pending_htlcs_forwardable!(nodes[1]);
6329 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6331 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6332 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6333 ), true, APIError::ChannelUnavailable { .. }, {});
6335 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6339 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6340 //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.
6341 let chanmon_cfgs = create_chanmon_cfgs(2);
6342 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6343 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6344 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6345 let channel_value = 100000;
6346 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6347 let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6349 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6351 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6352 // Manually create a route over our max in flight (which our router normally automatically
6354 route.paths[0].hops[0].fee_msat = max_in_flight + 1;
6355 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6356 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6357 ), true, APIError::ChannelUnavailable { .. }, {});
6358 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6360 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6363 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6365 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6366 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6367 let chanmon_cfgs = create_chanmon_cfgs(2);
6368 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6369 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6370 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6371 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6372 let htlc_minimum_msat: u64;
6374 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6375 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6376 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6377 htlc_minimum_msat = channel.context().get_holder_htlc_minimum_msat();
6380 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6381 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6382 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6383 check_added_monitors!(nodes[0], 1);
6384 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6385 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6386 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6387 assert!(nodes[1].node.list_channels().is_empty());
6388 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6389 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()));
6390 check_added_monitors!(nodes[1], 1);
6391 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6395 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6396 //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
6397 let chanmon_cfgs = create_chanmon_cfgs(2);
6398 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6399 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6400 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6401 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6403 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6404 let channel_reserve = chan_stat.channel_reserve_msat;
6405 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6406 let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
6407 // The 2* and +1 are for the fee spike reserve.
6408 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
6410 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6411 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
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());
6417 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6418 // at this time channel-initiatee receivers are not required to enforce that senders
6419 // respect the fee_spike_reserve.
6420 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6421 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6423 assert!(nodes[1].node.list_channels().is_empty());
6424 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6425 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6426 check_added_monitors!(nodes[1], 1);
6427 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6431 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6432 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6433 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6434 let chanmon_cfgs = create_chanmon_cfgs(2);
6435 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6436 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6437 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6438 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6440 let send_amt = 3999999;
6441 let (mut route, our_payment_hash, _, our_payment_secret) =
6442 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
6443 route.paths[0].hops[0].fee_msat = send_amt;
6444 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6445 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6446 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6447 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
6448 &route.paths[0], send_amt, RecipientOnionFields::secret_only(our_payment_secret), cur_height, &None).unwrap();
6449 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
6451 let mut msg = msgs::UpdateAddHTLC {
6455 payment_hash: our_payment_hash,
6456 cltv_expiry: htlc_cltv,
6457 onion_routing_packet: onion_packet.clone(),
6458 skimmed_fee_msat: None,
6462 msg.htlc_id = i as u64;
6463 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6465 msg.htlc_id = (50) as u64;
6466 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6468 assert!(nodes[1].node.list_channels().is_empty());
6469 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6470 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6471 check_added_monitors!(nodes[1], 1);
6472 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6476 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6477 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6478 let chanmon_cfgs = create_chanmon_cfgs(2);
6479 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6480 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6481 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6482 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6484 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6485 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6486 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6487 check_added_monitors!(nodes[0], 1);
6488 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6489 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;
6490 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6492 assert!(nodes[1].node.list_channels().is_empty());
6493 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6494 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6495 check_added_monitors!(nodes[1], 1);
6496 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 1000000);
6500 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6501 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6502 let chanmon_cfgs = create_chanmon_cfgs(2);
6503 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6504 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6505 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6507 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6508 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6509 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6510 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6511 check_added_monitors!(nodes[0], 1);
6512 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6513 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6514 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6516 assert!(nodes[1].node.list_channels().is_empty());
6517 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6518 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6519 check_added_monitors!(nodes[1], 1);
6520 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6524 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6525 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6526 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6527 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6528 let chanmon_cfgs = create_chanmon_cfgs(2);
6529 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6530 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6531 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6533 create_announced_chan_between_nodes(&nodes, 0, 1);
6534 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6535 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6536 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6537 check_added_monitors!(nodes[0], 1);
6538 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6539 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6541 //Disconnect and Reconnect
6542 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
6543 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
6544 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
6545 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
6547 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6548 assert_eq!(reestablish_1.len(), 1);
6549 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
6550 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
6552 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6553 assert_eq!(reestablish_2.len(), 1);
6554 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6555 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6556 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6557 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6560 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6561 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6562 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6563 check_added_monitors!(nodes[1], 1);
6564 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6566 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6568 assert!(nodes[1].node.list_channels().is_empty());
6569 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6570 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6571 check_added_monitors!(nodes[1], 1);
6572 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6576 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6577 //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.
6579 let chanmon_cfgs = create_chanmon_cfgs(2);
6580 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6581 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6582 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6583 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6584 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6585 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6586 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6588 check_added_monitors!(nodes[0], 1);
6589 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6590 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6592 let update_msg = msgs::UpdateFulfillHTLC{
6595 payment_preimage: our_payment_preimage,
6598 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6600 assert!(nodes[0].node.list_channels().is_empty());
6601 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6602 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()));
6603 check_added_monitors!(nodes[0], 1);
6604 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6608 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6609 //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.
6611 let chanmon_cfgs = create_chanmon_cfgs(2);
6612 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6613 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6614 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6615 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6617 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6618 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6619 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6620 check_added_monitors!(nodes[0], 1);
6621 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6622 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6624 let update_msg = msgs::UpdateFailHTLC{
6627 reason: msgs::OnionErrorPacket { data: Vec::new()},
6630 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6632 assert!(nodes[0].node.list_channels().is_empty());
6633 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6634 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()));
6635 check_added_monitors!(nodes[0], 1);
6636 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6640 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6641 //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.
6643 let chanmon_cfgs = create_chanmon_cfgs(2);
6644 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6645 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6646 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6647 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6649 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6650 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6651 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6652 check_added_monitors!(nodes[0], 1);
6653 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6654 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6655 let update_msg = msgs::UpdateFailMalformedHTLC{
6658 sha256_of_onion: [1; 32],
6659 failure_code: 0x8000,
6662 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6664 assert!(nodes[0].node.list_channels().is_empty());
6665 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6666 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()));
6667 check_added_monitors!(nodes[0], 1);
6668 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6672 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6673 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6675 let chanmon_cfgs = create_chanmon_cfgs(2);
6676 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6677 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6678 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6679 create_announced_chan_between_nodes(&nodes, 0, 1);
6681 let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6683 nodes[1].node.claim_funds(our_payment_preimage);
6684 check_added_monitors!(nodes[1], 1);
6685 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6687 let events = nodes[1].node.get_and_clear_pending_msg_events();
6688 assert_eq!(events.len(), 1);
6689 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6691 MessageSendEvent::UpdateHTLCs { node_id: _ , updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, .. } } => {
6692 assert!(update_add_htlcs.is_empty());
6693 assert_eq!(update_fulfill_htlcs.len(), 1);
6694 assert!(update_fail_htlcs.is_empty());
6695 assert!(update_fail_malformed_htlcs.is_empty());
6696 assert!(update_fee.is_none());
6697 update_fulfill_htlcs[0].clone()
6699 _ => panic!("Unexpected event"),
6703 update_fulfill_msg.htlc_id = 1;
6705 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6707 assert!(nodes[0].node.list_channels().is_empty());
6708 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6709 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6710 check_added_monitors!(nodes[0], 1);
6711 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6715 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6716 //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.
6718 let chanmon_cfgs = create_chanmon_cfgs(2);
6719 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6720 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6721 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6722 create_announced_chan_between_nodes(&nodes, 0, 1);
6724 let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6726 nodes[1].node.claim_funds(our_payment_preimage);
6727 check_added_monitors!(nodes[1], 1);
6728 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6730 let events = nodes[1].node.get_and_clear_pending_msg_events();
6731 assert_eq!(events.len(), 1);
6732 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6734 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, .. } } => {
6735 assert!(update_add_htlcs.is_empty());
6736 assert_eq!(update_fulfill_htlcs.len(), 1);
6737 assert!(update_fail_htlcs.is_empty());
6738 assert!(update_fail_malformed_htlcs.is_empty());
6739 assert!(update_fee.is_none());
6740 update_fulfill_htlcs[0].clone()
6742 _ => panic!("Unexpected event"),
6746 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6748 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6750 assert!(nodes[0].node.list_channels().is_empty());
6751 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6752 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6753 check_added_monitors!(nodes[0], 1);
6754 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6758 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6759 //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.
6761 let chanmon_cfgs = create_chanmon_cfgs(2);
6762 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6763 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6764 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6765 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6767 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6768 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6769 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6770 check_added_monitors!(nodes[0], 1);
6772 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6773 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6775 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6776 check_added_monitors!(nodes[1], 0);
6777 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6779 let events = nodes[1].node.get_and_clear_pending_msg_events();
6781 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6783 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, .. } } => {
6784 assert!(update_add_htlcs.is_empty());
6785 assert!(update_fulfill_htlcs.is_empty());
6786 assert!(update_fail_htlcs.is_empty());
6787 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6788 assert!(update_fee.is_none());
6789 update_fail_malformed_htlcs[0].clone()
6791 _ => panic!("Unexpected event"),
6794 update_msg.failure_code &= !0x8000;
6795 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6797 assert!(nodes[0].node.list_channels().is_empty());
6798 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6799 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6800 check_added_monitors!(nodes[0], 1);
6801 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 1000000);
6805 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6806 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6807 // * 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.
6809 let chanmon_cfgs = create_chanmon_cfgs(3);
6810 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6811 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6812 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6813 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6814 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000);
6816 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6819 let mut payment_event = {
6820 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6821 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6822 check_added_monitors!(nodes[0], 1);
6823 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6824 assert_eq!(events.len(), 1);
6825 SendEvent::from_event(events.remove(0))
6827 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6828 check_added_monitors!(nodes[1], 0);
6829 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6830 expect_pending_htlcs_forwardable!(nodes[1]);
6831 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6832 assert_eq!(events_2.len(), 1);
6833 check_added_monitors!(nodes[1], 1);
6834 payment_event = SendEvent::from_event(events_2.remove(0));
6835 assert_eq!(payment_event.msgs.len(), 1);
6838 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6839 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6840 check_added_monitors!(nodes[2], 0);
6841 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6843 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6844 assert_eq!(events_3.len(), 1);
6845 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6847 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 } } => {
6848 assert!(update_add_htlcs.is_empty());
6849 assert!(update_fulfill_htlcs.is_empty());
6850 assert!(update_fail_htlcs.is_empty());
6851 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6852 assert!(update_fee.is_none());
6853 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6855 _ => panic!("Unexpected event"),
6859 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6861 check_added_monitors!(nodes[1], 0);
6862 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6863 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 }]);
6864 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6865 assert_eq!(events_4.len(), 1);
6867 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6869 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, .. } } => {
6870 assert!(update_add_htlcs.is_empty());
6871 assert!(update_fulfill_htlcs.is_empty());
6872 assert_eq!(update_fail_htlcs.len(), 1);
6873 assert!(update_fail_malformed_htlcs.is_empty());
6874 assert!(update_fee.is_none());
6876 _ => panic!("Unexpected event"),
6879 check_added_monitors!(nodes[1], 1);
6883 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6884 let chanmon_cfgs = create_chanmon_cfgs(3);
6885 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6886 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6887 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6888 create_announced_chan_between_nodes(&nodes, 0, 1);
6889 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6891 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6894 let mut payment_event = {
6895 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6896 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6897 check_added_monitors!(nodes[0], 1);
6898 SendEvent::from_node(&nodes[0])
6901 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6902 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6903 expect_pending_htlcs_forwardable!(nodes[1]);
6904 check_added_monitors!(nodes[1], 1);
6905 payment_event = SendEvent::from_node(&nodes[1]);
6906 assert_eq!(payment_event.msgs.len(), 1);
6909 payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6910 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6911 check_added_monitors!(nodes[2], 0);
6912 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6914 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6915 assert_eq!(events_3.len(), 1);
6917 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6918 let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6919 // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6920 update_msg.failure_code |= 0x2000;
6922 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6923 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6925 _ => panic!("Unexpected event"),
6928 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6929 vec![HTLCDestination::NextHopChannel {
6930 node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6931 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6932 assert_eq!(events_4.len(), 1);
6933 check_added_monitors!(nodes[1], 1);
6936 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6937 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6938 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6940 _ => panic!("Unexpected event"),
6943 let events_5 = nodes[0].node.get_and_clear_pending_events();
6944 assert_eq!(events_5.len(), 2);
6946 // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6947 // the node originating the error to its next hop.
6949 Event::PaymentPathFailed { error_code, failure: PathFailure::OnPath { network_update: Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }) }, ..
6951 assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6952 assert!(is_permanent);
6953 assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
6955 _ => panic!("Unexpected event"),
6958 Event::PaymentFailed { payment_hash, .. } => {
6959 assert_eq!(payment_hash, our_payment_hash);
6961 _ => panic!("Unexpected event"),
6964 // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
6967 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6968 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6969 // 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
6970 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6972 let mut chanmon_cfgs = create_chanmon_cfgs(2);
6973 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6974 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6975 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6976 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6977 let chan =create_announced_chan_between_nodes(&nodes, 0, 1);
6979 let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6980 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context().holder_dust_limit_satoshis;
6982 // We route 2 dust-HTLCs between A and B
6983 let (_, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6984 let (_, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6985 route_payment(&nodes[0], &[&nodes[1]], 1000000);
6987 // Cache one local commitment tx as previous
6988 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6990 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6991 nodes[1].node.fail_htlc_backwards(&payment_hash_2);
6992 check_added_monitors!(nodes[1], 0);
6993 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
6994 check_added_monitors!(nodes[1], 1);
6996 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6997 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6998 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6999 check_added_monitors!(nodes[0], 1);
7001 // Cache one local commitment tx as lastest
7002 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7004 let events = nodes[0].node.get_and_clear_pending_msg_events();
7006 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7007 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7009 _ => panic!("Unexpected event"),
7012 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7013 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7015 _ => panic!("Unexpected event"),
7018 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7019 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7020 if announce_latest {
7021 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7023 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7026 check_closed_broadcast!(nodes[0], true);
7027 check_added_monitors!(nodes[0], 1);
7028 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7030 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7031 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7032 let events = nodes[0].node.get_and_clear_pending_events();
7033 // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7034 assert_eq!(events.len(), 4);
7035 let mut first_failed = false;
7036 for event in events {
7038 Event::PaymentPathFailed { payment_hash, .. } => {
7039 if payment_hash == payment_hash_1 {
7040 assert!(!first_failed);
7041 first_failed = true;
7043 assert_eq!(payment_hash, payment_hash_2);
7046 Event::PaymentFailed { .. } => {}
7047 _ => panic!("Unexpected event"),
7053 fn test_failure_delay_dust_htlc_local_commitment() {
7054 do_test_failure_delay_dust_htlc_local_commitment(true);
7055 do_test_failure_delay_dust_htlc_local_commitment(false);
7058 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7059 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7060 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7061 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7062 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7063 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7064 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7066 let chanmon_cfgs = create_chanmon_cfgs(3);
7067 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7068 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7069 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7070 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
7072 let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
7073 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context().holder_dust_limit_satoshis;
7075 let (_payment_preimage_1, dust_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7076 let (_payment_preimage_2, non_dust_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7078 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7079 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7081 // We revoked bs_commitment_tx
7083 let (payment_preimage_3, ..) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7084 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7087 let mut timeout_tx = Vec::new();
7089 // We fail dust-HTLC 1 by broadcast of local commitment tx
7090 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7091 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7092 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7093 expect_payment_failed!(nodes[0], dust_hash, false);
7095 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7096 check_closed_broadcast!(nodes[0], true);
7097 check_added_monitors!(nodes[0], 1);
7098 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7099 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7100 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7101 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7102 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7103 mine_transaction(&nodes[0], &timeout_tx[0]);
7104 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7105 expect_payment_failed!(nodes[0], non_dust_hash, false);
7107 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7108 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7109 check_closed_broadcast!(nodes[0], true);
7110 check_added_monitors!(nodes[0], 1);
7111 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7112 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7114 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7115 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
7116 .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
7117 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
7118 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
7119 // dust HTLC should have been failed.
7120 expect_payment_failed!(nodes[0], dust_hash, false);
7123 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7125 assert_eq!(timeout_tx[0].lock_time.0, 11);
7127 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
7128 mine_transaction(&nodes[0], &timeout_tx[0]);
7129 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7130 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7131 expect_payment_failed!(nodes[0], non_dust_hash, false);
7136 fn test_sweep_outbound_htlc_failure_update() {
7137 do_test_sweep_outbound_htlc_failure_update(false, true);
7138 do_test_sweep_outbound_htlc_failure_update(false, false);
7139 do_test_sweep_outbound_htlc_failure_update(true, false);
7143 fn test_user_configurable_csv_delay() {
7144 // We test our channel constructors yield errors when we pass them absurd csv delay
7146 let mut low_our_to_self_config = UserConfig::default();
7147 low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
7148 let mut high_their_to_self_config = UserConfig::default();
7149 high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
7150 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7151 let chanmon_cfgs = create_chanmon_cfgs(2);
7152 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7153 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7154 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7156 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in OutboundV1Channel::new()
7157 if let Err(error) = OutboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7158 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[1].node.init_features(), 1000000, 1000000, 0,
7159 &low_our_to_self_config, 0, 42)
7162 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())); },
7163 _ => panic!("Unexpected event"),
7165 } else { assert!(false) }
7167 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in InboundV1Channel::new()
7168 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7169 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7170 open_channel.to_self_delay = 200;
7171 if let Err(error) = InboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7172 &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,
7173 &low_our_to_self_config, 0, &nodes[0].logger, /*is_0conf=*/false)
7176 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())); },
7177 _ => panic!("Unexpected event"),
7179 } else { assert!(false); }
7181 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7182 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7183 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()));
7184 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7185 accept_channel.to_self_delay = 200;
7186 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
7188 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7190 &ErrorAction::SendErrorMessage { ref msg } => {
7191 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()));
7192 reason_msg = msg.data.clone();
7196 } else { panic!(); }
7197 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg }, [nodes[1].node.get_our_node_id()], 1000000);
7199 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in InboundV1Channel::new()
7200 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7201 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7202 open_channel.to_self_delay = 200;
7203 if let Err(error) = InboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7204 &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,
7205 &high_their_to_self_config, 0, &nodes[0].logger, /*is_0conf=*/false)
7208 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())); },
7209 _ => panic!("Unexpected event"),
7211 } else { assert!(false); }
7215 fn test_check_htlc_underpaying() {
7216 // Send payment through A -> B but A is maliciously
7217 // sending a probe payment (i.e less than expected value0
7218 // to B, B should refuse payment.
7220 let chanmon_cfgs = create_chanmon_cfgs(2);
7221 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7222 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7223 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7225 // Create some initial channels
7226 create_announced_chan_between_nodes(&nodes, 0, 1);
7228 let scorer = test_utils::TestScorer::new();
7229 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7230 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(),
7231 TEST_FINAL_CLTV).with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
7232 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 10_000);
7233 let route = get_route(&nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph.read_only(),
7234 None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes).unwrap();
7235 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7236 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, None).unwrap();
7237 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
7238 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
7239 check_added_monitors!(nodes[0], 1);
7241 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7242 assert_eq!(events.len(), 1);
7243 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7244 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7245 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7247 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7248 // and then will wait a second random delay before failing the HTLC back:
7249 expect_pending_htlcs_forwardable!(nodes[1]);
7250 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7252 // Node 3 is expecting payment of 100_000 but received 10_000,
7253 // it should fail htlc like we didn't know the preimage.
7254 nodes[1].node.process_pending_htlc_forwards();
7256 let events = nodes[1].node.get_and_clear_pending_msg_events();
7257 assert_eq!(events.len(), 1);
7258 let (update_fail_htlc, commitment_signed) = match events[0] {
7259 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 } } => {
7260 assert!(update_add_htlcs.is_empty());
7261 assert!(update_fulfill_htlcs.is_empty());
7262 assert_eq!(update_fail_htlcs.len(), 1);
7263 assert!(update_fail_malformed_htlcs.is_empty());
7264 assert!(update_fee.is_none());
7265 (update_fail_htlcs[0].clone(), commitment_signed)
7267 _ => panic!("Unexpected event"),
7269 check_added_monitors!(nodes[1], 1);
7271 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7272 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7274 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7275 let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
7276 expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
7277 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7281 fn test_announce_disable_channels() {
7282 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7283 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7285 let chanmon_cfgs = create_chanmon_cfgs(2);
7286 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7287 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7288 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7290 create_announced_chan_between_nodes(&nodes, 0, 1);
7291 create_announced_chan_between_nodes(&nodes, 1, 0);
7292 create_announced_chan_between_nodes(&nodes, 0, 1);
7295 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
7296 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
7298 for _ in 0..DISABLE_GOSSIP_TICKS + 1 {
7299 nodes[0].node.timer_tick_occurred();
7301 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7302 assert_eq!(msg_events.len(), 3);
7303 let mut chans_disabled = HashMap::new();
7304 for e in msg_events {
7306 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7307 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7308 // Check that each channel gets updated exactly once
7309 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7310 panic!("Generated ChannelUpdate for wrong chan!");
7313 _ => panic!("Unexpected event"),
7317 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
7318 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
7320 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7321 assert_eq!(reestablish_1.len(), 3);
7322 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
7323 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
7325 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7326 assert_eq!(reestablish_2.len(), 3);
7328 // Reestablish chan_1
7329 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7330 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7331 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7332 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7333 // Reestablish chan_2
7334 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7335 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7336 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7337 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7338 // Reestablish chan_3
7339 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7340 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7341 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7342 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7344 for _ in 0..ENABLE_GOSSIP_TICKS {
7345 nodes[0].node.timer_tick_occurred();
7347 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7348 nodes[0].node.timer_tick_occurred();
7349 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7350 assert_eq!(msg_events.len(), 3);
7351 for e in msg_events {
7353 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7354 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7355 match chans_disabled.remove(&msg.contents.short_channel_id) {
7356 // Each update should have a higher timestamp than the previous one, replacing
7358 Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7359 None => panic!("Generated ChannelUpdate for wrong chan!"),
7362 _ => panic!("Unexpected event"),
7365 // Check that each channel gets updated exactly once
7366 assert!(chans_disabled.is_empty());
7370 fn test_bump_penalty_txn_on_revoked_commitment() {
7371 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7372 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7374 let chanmon_cfgs = create_chanmon_cfgs(2);
7375 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7376 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7377 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7379 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7381 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7382 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7383 .with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7384 let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000);
7385 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7387 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7388 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7389 assert_eq!(revoked_txn[0].output.len(), 4);
7390 assert_eq!(revoked_txn[0].input.len(), 1);
7391 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7392 let revoked_txid = revoked_txn[0].txid();
7394 let mut penalty_sum = 0;
7395 for outp in revoked_txn[0].output.iter() {
7396 if outp.script_pubkey.is_v0_p2wsh() {
7397 penalty_sum += outp.value;
7401 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7402 let header_114 = connect_blocks(&nodes[1], 14);
7404 // Actually revoke tx by claiming a HTLC
7405 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7406 connect_block(&nodes[1], &create_dummy_block(header_114, 42, vec![revoked_txn[0].clone()]));
7407 check_added_monitors!(nodes[1], 1);
7409 // One or more justice tx should have been broadcast, check it
7413 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7414 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7415 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7416 assert_eq!(node_txn[0].output.len(), 1);
7417 check_spends!(node_txn[0], revoked_txn[0]);
7418 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7419 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7420 penalty_1 = node_txn[0].txid();
7424 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7425 connect_blocks(&nodes[1], 15);
7426 let mut penalty_2 = penalty_1;
7427 let mut feerate_2 = 0;
7429 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7430 assert_eq!(node_txn.len(), 1);
7431 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7432 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7433 assert_eq!(node_txn[0].output.len(), 1);
7434 check_spends!(node_txn[0], revoked_txn[0]);
7435 penalty_2 = node_txn[0].txid();
7436 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7437 assert_ne!(penalty_2, penalty_1);
7438 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7439 feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7440 // Verify 25% bump heuristic
7441 assert!(feerate_2 * 100 >= feerate_1 * 125);
7445 assert_ne!(feerate_2, 0);
7447 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7448 connect_blocks(&nodes[1], 1);
7450 let mut feerate_3 = 0;
7452 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7453 assert_eq!(node_txn.len(), 1);
7454 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7455 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7456 assert_eq!(node_txn[0].output.len(), 1);
7457 check_spends!(node_txn[0], revoked_txn[0]);
7458 penalty_3 = node_txn[0].txid();
7459 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7460 assert_ne!(penalty_3, penalty_2);
7461 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7462 feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7463 // Verify 25% bump heuristic
7464 assert!(feerate_3 * 100 >= feerate_2 * 125);
7468 assert_ne!(feerate_3, 0);
7470 nodes[1].node.get_and_clear_pending_events();
7471 nodes[1].node.get_and_clear_pending_msg_events();
7475 fn test_bump_penalty_txn_on_revoked_htlcs() {
7476 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7477 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7479 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7480 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7481 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7482 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7483 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7485 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7486 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7487 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 50).with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
7488 let scorer = test_utils::TestScorer::new();
7489 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7490 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 3_000_000);
7491 let route = get_route(&nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph.read_only(), None,
7492 nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes).unwrap();
7493 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7494 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50).with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7495 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 3_000_000);
7496 let route = get_route(&nodes[1].node.get_our_node_id(), &route_params, &nodes[1].network_graph.read_only(), None,
7497 nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes).unwrap();
7498 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7500 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7501 assert_eq!(revoked_local_txn[0].input.len(), 1);
7502 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7504 // Revoke local commitment tx
7505 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7507 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7508 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone()]));
7509 check_closed_broadcast!(nodes[1], true);
7510 check_added_monitors!(nodes[1], 1);
7511 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 1000000);
7512 connect_blocks(&nodes[1], 50); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7514 let revoked_htlc_txn = {
7515 let txn = nodes[1].tx_broadcaster.unique_txn_broadcast();
7516 assert_eq!(txn.len(), 2);
7518 assert_eq!(txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7519 assert_eq!(txn[0].input.len(), 1);
7520 check_spends!(txn[0], revoked_local_txn[0]);
7522 assert_eq!(txn[1].input.len(), 1);
7523 assert_eq!(txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7524 assert_eq!(txn[1].output.len(), 1);
7525 check_spends!(txn[1], revoked_local_txn[0]);
7530 // Broadcast set of revoked txn on A
7531 let hash_128 = connect_blocks(&nodes[0], 40);
7532 let block_11 = create_dummy_block(hash_128, 42, vec![revoked_local_txn[0].clone()]);
7533 connect_block(&nodes[0], &block_11);
7534 let block_129 = create_dummy_block(block_11.block_hash(), 42, vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()]);
7535 connect_block(&nodes[0], &block_129);
7536 let events = nodes[0].node.get_and_clear_pending_events();
7537 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7538 match events.last().unwrap() {
7539 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7540 _ => panic!("Unexpected event"),
7546 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7547 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7548 // Verify claim tx are spending revoked HTLC txn
7550 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7551 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7552 // which are included in the same block (they are broadcasted because we scan the
7553 // transactions linearly and generate claims as we go, they likely should be removed in the
7555 assert_eq!(node_txn[0].input.len(), 1);
7556 check_spends!(node_txn[0], revoked_local_txn[0]);
7557 assert_eq!(node_txn[1].input.len(), 1);
7558 check_spends!(node_txn[1], revoked_local_txn[0]);
7559 assert_eq!(node_txn[2].input.len(), 1);
7560 check_spends!(node_txn[2], revoked_local_txn[0]);
7562 // Each of the three justice transactions claim a separate (single) output of the three
7563 // available, which we check here:
7564 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7565 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7566 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7568 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7569 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7571 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7572 // output, checked above).
7573 assert_eq!(node_txn[3].input.len(), 2);
7574 assert_eq!(node_txn[3].output.len(), 1);
7575 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7577 first = node_txn[3].txid();
7578 // Store both feerates for later comparison
7579 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7580 feerate_1 = fee_1 * 1000 / node_txn[3].weight() as u64;
7581 penalty_txn = vec![node_txn[2].clone()];
7585 // Connect one more block to see if bumped penalty are issued for HTLC txn
7586 let block_130 = create_dummy_block(block_129.block_hash(), 42, penalty_txn);
7587 connect_block(&nodes[0], &block_130);
7588 let block_131 = create_dummy_block(block_130.block_hash(), 42, Vec::new());
7589 connect_block(&nodes[0], &block_131);
7591 // Few more blocks to confirm penalty txn
7592 connect_blocks(&nodes[0], 4);
7593 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7594 let header_144 = connect_blocks(&nodes[0], 9);
7596 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7597 assert_eq!(node_txn.len(), 1);
7599 assert_eq!(node_txn[0].input.len(), 2);
7600 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7601 // Verify bumped tx is different and 25% bump heuristic
7602 assert_ne!(first, node_txn[0].txid());
7603 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7604 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7605 assert!(feerate_2 * 100 > feerate_1 * 125);
7606 let txn = vec![node_txn[0].clone()];
7610 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7611 connect_block(&nodes[0], &create_dummy_block(header_144, 42, node_txn));
7612 connect_blocks(&nodes[0], 20);
7614 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7615 // We verify than no new transaction has been broadcast because previously
7616 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7617 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7618 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7619 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7620 // up bumped justice generation.
7621 assert_eq!(node_txn.len(), 0);
7624 check_closed_broadcast!(nodes[0], true);
7625 check_added_monitors!(nodes[0], 1);
7629 fn test_bump_penalty_txn_on_remote_commitment() {
7630 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7631 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7634 // Provide preimage for one
7635 // Check aggregation
7637 let chanmon_cfgs = create_chanmon_cfgs(2);
7638 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7639 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7640 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7642 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7643 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7644 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7646 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7647 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7648 assert_eq!(remote_txn[0].output.len(), 4);
7649 assert_eq!(remote_txn[0].input.len(), 1);
7650 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7652 // Claim a HTLC without revocation (provide B monitor with preimage)
7653 nodes[1].node.claim_funds(payment_preimage);
7654 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7655 mine_transaction(&nodes[1], &remote_txn[0]);
7656 check_added_monitors!(nodes[1], 2);
7657 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7659 // One or more claim tx should have been broadcast, check it
7663 let feerate_timeout;
7664 let feerate_preimage;
7666 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7667 // 3 transactions including:
7668 // preimage and timeout sweeps from remote commitment + preimage sweep bump
7669 assert_eq!(node_txn.len(), 3);
7670 assert_eq!(node_txn[0].input.len(), 1);
7671 assert_eq!(node_txn[1].input.len(), 1);
7672 assert_eq!(node_txn[2].input.len(), 1);
7673 check_spends!(node_txn[0], remote_txn[0]);
7674 check_spends!(node_txn[1], remote_txn[0]);
7675 check_spends!(node_txn[2], remote_txn[0]);
7677 preimage = node_txn[0].txid();
7678 let index = node_txn[0].input[0].previous_output.vout;
7679 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7680 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
7682 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7683 (node_txn[2].clone(), node_txn[1].clone())
7685 (node_txn[1].clone(), node_txn[2].clone())
7688 preimage_bump = preimage_bump_tx;
7689 check_spends!(preimage_bump, remote_txn[0]);
7690 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7692 timeout = timeout_tx.txid();
7693 let index = timeout_tx.input[0].previous_output.vout;
7694 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7695 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
7699 assert_ne!(feerate_timeout, 0);
7700 assert_ne!(feerate_preimage, 0);
7702 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7703 connect_blocks(&nodes[1], 1);
7705 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7706 assert_eq!(node_txn.len(), 1);
7707 assert_eq!(node_txn[0].input.len(), 1);
7708 assert_eq!(preimage_bump.input.len(), 1);
7709 check_spends!(node_txn[0], remote_txn[0]);
7710 check_spends!(preimage_bump, remote_txn[0]);
7712 let index = preimage_bump.input[0].previous_output.vout;
7713 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7714 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
7715 assert!(new_feerate * 100 > feerate_timeout * 125);
7716 assert_ne!(timeout, preimage_bump.txid());
7718 let index = node_txn[0].input[0].previous_output.vout;
7719 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7720 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
7721 assert!(new_feerate * 100 > feerate_preimage * 125);
7722 assert_ne!(preimage, node_txn[0].txid());
7727 nodes[1].node.get_and_clear_pending_events();
7728 nodes[1].node.get_and_clear_pending_msg_events();
7732 fn test_counterparty_raa_skip_no_crash() {
7733 // Previously, if our counterparty sent two RAAs in a row without us having provided a
7734 // commitment transaction, we would have happily carried on and provided them the next
7735 // commitment transaction based on one RAA forward. This would probably eventually have led to
7736 // channel closure, but it would not have resulted in funds loss. Still, our
7737 // TestChannelSigner would have panicked as it doesn't like jumps into the future. Here, we
7738 // check simply that the channel is closed in response to such an RAA, but don't check whether
7739 // we decide to punish our counterparty for revoking their funds (as we don't currently
7741 let chanmon_cfgs = create_chanmon_cfgs(2);
7742 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7743 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7744 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7745 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7747 let per_commitment_secret;
7748 let next_per_commitment_point;
7750 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7751 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7752 let keys = guard.channel_by_id.get_mut(&channel_id).map(
7753 |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
7754 ).flatten().unwrap().get_signer();
7756 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7758 // Make signer believe we got a counterparty signature, so that it allows the revocation
7759 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7760 per_commitment_secret = keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7762 // Must revoke without gaps
7763 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7764 keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7766 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7767 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7768 &SecretKey::from_slice(&keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7771 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7772 &msgs::RevokeAndACK {
7774 per_commitment_secret,
7775 next_per_commitment_point,
7777 next_local_nonce: None,
7779 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7780 check_added_monitors!(nodes[1], 1);
7781 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() }
7782 , [nodes[0].node.get_our_node_id()], 100000);
7786 fn test_bump_txn_sanitize_tracking_maps() {
7787 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7788 // verify we clean then right after expiration of ANTI_REORG_DELAY.
7790 let chanmon_cfgs = create_chanmon_cfgs(2);
7791 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7792 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7793 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7795 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7796 // Lock HTLC in both directions
7797 let (payment_preimage_1, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7798 let (_, payment_hash_2, ..) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7800 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7801 assert_eq!(revoked_local_txn[0].input.len(), 1);
7802 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7804 // Revoke local commitment tx
7805 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7807 // Broadcast set of revoked txn on A
7808 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7809 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7810 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7812 mine_transaction(&nodes[0], &revoked_local_txn[0]);
7813 check_closed_broadcast!(nodes[0], true);
7814 check_added_monitors!(nodes[0], 1);
7815 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 1000000);
7817 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7818 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7819 check_spends!(node_txn[0], revoked_local_txn[0]);
7820 check_spends!(node_txn[1], revoked_local_txn[0]);
7821 check_spends!(node_txn[2], revoked_local_txn[0]);
7822 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7826 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, penalty_txn));
7827 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7829 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7830 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7831 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7836 fn test_channel_conf_timeout() {
7837 // Tests that, for inbound channels, we give up on them if the funding transaction does not
7838 // confirm within 2016 blocks, as recommended by BOLT 2.
7839 let chanmon_cfgs = create_chanmon_cfgs(2);
7840 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7841 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7842 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7844 let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7846 // The outbound node should wait forever for confirmation:
7847 // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7848 // copied here instead of directly referencing the constant.
7849 connect_blocks(&nodes[0], 2016);
7850 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7852 // The inbound node should fail the channel after exactly 2016 blocks
7853 connect_blocks(&nodes[1], 2015);
7854 check_added_monitors!(nodes[1], 0);
7855 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7857 connect_blocks(&nodes[1], 1);
7858 check_added_monitors!(nodes[1], 1);
7859 check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut, [nodes[0].node.get_our_node_id()], 1000000);
7860 let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7861 assert_eq!(close_ev.len(), 1);
7863 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
7864 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7865 assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7867 _ => panic!("Unexpected event"),
7872 fn test_override_channel_config() {
7873 let chanmon_cfgs = create_chanmon_cfgs(2);
7874 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7875 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7876 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7878 // Node0 initiates a channel to node1 using the override config.
7879 let mut override_config = UserConfig::default();
7880 override_config.channel_handshake_config.our_to_self_delay = 200;
7882 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7884 // Assert the channel created by node0 is using the override config.
7885 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7886 assert_eq!(res.channel_flags, 0);
7887 assert_eq!(res.to_self_delay, 200);
7891 fn test_override_0msat_htlc_minimum() {
7892 let mut zero_config = UserConfig::default();
7893 zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7894 let chanmon_cfgs = create_chanmon_cfgs(2);
7895 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7896 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7897 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7899 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7900 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7901 assert_eq!(res.htlc_minimum_msat, 1);
7903 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7904 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7905 assert_eq!(res.htlc_minimum_msat, 1);
7909 fn test_channel_update_has_correct_htlc_maximum_msat() {
7910 // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7911 // Bolt 7 specifies that if present `htlc_maximum_msat`:
7912 // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7913 // 90% of the `channel_value`.
7914 // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7916 let mut config_30_percent = UserConfig::default();
7917 config_30_percent.channel_handshake_config.announced_channel = true;
7918 config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7919 let mut config_50_percent = UserConfig::default();
7920 config_50_percent.channel_handshake_config.announced_channel = true;
7921 config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7922 let mut config_95_percent = UserConfig::default();
7923 config_95_percent.channel_handshake_config.announced_channel = true;
7924 config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7925 let mut config_100_percent = UserConfig::default();
7926 config_100_percent.channel_handshake_config.announced_channel = true;
7927 config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7929 let chanmon_cfgs = create_chanmon_cfgs(4);
7930 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7931 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)]);
7932 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7934 let channel_value_satoshis = 100000;
7935 let channel_value_msat = channel_value_satoshis * 1000;
7936 let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7937 let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7938 let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7940 let (node_0_chan_update, node_1_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
7941 let (node_2_chan_update, node_3_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
7943 // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7944 // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7945 assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7946 // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7947 // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7948 assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7950 // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7951 // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7953 assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7954 // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7955 // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7957 assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7961 fn test_manually_accept_inbound_channel_request() {
7962 let mut manually_accept_conf = UserConfig::default();
7963 manually_accept_conf.manually_accept_inbound_channels = true;
7964 let chanmon_cfgs = create_chanmon_cfgs(2);
7965 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7966 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7967 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7969 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7970 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7972 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7974 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7975 // accepting the inbound channel request.
7976 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7978 let events = nodes[1].node.get_and_clear_pending_events();
7980 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7981 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
7983 _ => panic!("Unexpected event"),
7986 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7987 assert_eq!(accept_msg_ev.len(), 1);
7989 match accept_msg_ev[0] {
7990 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7991 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7993 _ => panic!("Unexpected event"),
7996 nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7998 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7999 assert_eq!(close_msg_ev.len(), 1);
8001 let events = nodes[1].node.get_and_clear_pending_events();
8003 Event::ChannelClosed { user_channel_id, .. } => {
8004 assert_eq!(user_channel_id, 23);
8006 _ => panic!("Unexpected event"),
8011 fn test_manually_reject_inbound_channel_request() {
8012 let mut manually_accept_conf = UserConfig::default();
8013 manually_accept_conf.manually_accept_inbound_channels = true;
8014 let chanmon_cfgs = create_chanmon_cfgs(2);
8015 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8016 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8017 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8019 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8020 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8022 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
8024 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8025 // rejecting the inbound channel request.
8026 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8028 let events = nodes[1].node.get_and_clear_pending_events();
8030 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8031 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8033 _ => panic!("Unexpected event"),
8036 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8037 assert_eq!(close_msg_ev.len(), 1);
8039 match close_msg_ev[0] {
8040 MessageSendEvent::HandleError { ref node_id, .. } => {
8041 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8043 _ => panic!("Unexpected event"),
8046 // There should be no more events to process, as the channel was never opened.
8047 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
8051 fn test_can_not_accept_inbound_channel_twice() {
8052 let mut manually_accept_conf = UserConfig::default();
8053 manually_accept_conf.manually_accept_inbound_channels = true;
8054 let chanmon_cfgs = create_chanmon_cfgs(2);
8055 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8056 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8057 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8059 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8060 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8062 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
8064 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8065 // accepting the inbound channel request.
8066 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8068 let events = nodes[1].node.get_and_clear_pending_events();
8070 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8071 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
8072 let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
8074 Err(APIError::APIMisuseError { err }) => {
8075 assert_eq!(err, "No such channel awaiting to be accepted.");
8077 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8078 Err(e) => panic!("Unexpected Error {:?}", e),
8081 _ => panic!("Unexpected event"),
8084 // Ensure that the channel wasn't closed after attempting to accept it twice.
8085 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8086 assert_eq!(accept_msg_ev.len(), 1);
8088 match accept_msg_ev[0] {
8089 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8090 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8092 _ => panic!("Unexpected event"),
8097 fn test_can_not_accept_unknown_inbound_channel() {
8098 let chanmon_cfg = create_chanmon_cfgs(2);
8099 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8100 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8101 let nodes = create_network(2, &node_cfg, &node_chanmgr);
8103 let unknown_channel_id = ChannelId::new_zero();
8104 let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
8106 Err(APIError::APIMisuseError { err }) => {
8107 assert_eq!(err, "No such channel awaiting to be accepted.");
8109 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8110 Err(e) => panic!("Unexpected Error: {:?}", e),
8115 fn test_onion_value_mpp_set_calculation() {
8116 // Test that we use the onion value `amt_to_forward` when
8117 // calculating whether we've reached the `total_msat` of an MPP
8118 // by having a routing node forward more than `amt_to_forward`
8119 // and checking that the receiving node doesn't generate
8120 // a PaymentClaimable event too early
8122 let chanmon_cfgs = create_chanmon_cfgs(node_count);
8123 let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8124 let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8125 let mut nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8127 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8128 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8129 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8130 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8132 let total_msat = 100_000;
8133 let expected_paths: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
8134 let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], total_msat);
8135 let sample_path = route.paths.pop().unwrap();
8137 let mut path_1 = sample_path.clone();
8138 path_1.hops[0].pubkey = nodes[1].node.get_our_node_id();
8139 path_1.hops[0].short_channel_id = chan_1_id;
8140 path_1.hops[1].pubkey = nodes[3].node.get_our_node_id();
8141 path_1.hops[1].short_channel_id = chan_3_id;
8142 path_1.hops[1].fee_msat = 100_000;
8143 route.paths.push(path_1);
8145 let mut path_2 = sample_path.clone();
8146 path_2.hops[0].pubkey = nodes[2].node.get_our_node_id();
8147 path_2.hops[0].short_channel_id = chan_2_id;
8148 path_2.hops[1].pubkey = nodes[3].node.get_our_node_id();
8149 path_2.hops[1].short_channel_id = chan_4_id;
8150 path_2.hops[1].fee_msat = 1_000;
8151 route.paths.push(path_2);
8154 let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
8155 let onion_session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
8156 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8157 nodes[0].node.test_send_payment_internal(&route, our_payment_hash,
8158 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8159 check_added_monitors!(nodes[0], expected_paths.len());
8161 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8162 assert_eq!(events.len(), expected_paths.len());
8165 let ev = remove_first_msg_event_to_node(&expected_paths[0][0].node.get_our_node_id(), &mut events);
8166 let mut payment_event = SendEvent::from_event(ev);
8167 let mut prev_node = &nodes[0];
8169 for (idx, &node) in expected_paths[0].iter().enumerate() {
8170 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
8172 if idx == 0 { // routing node
8173 let session_priv = [3; 32];
8174 let height = nodes[0].best_block_info().1;
8175 let session_priv = SecretKey::from_slice(&session_priv).unwrap();
8176 let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
8177 let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], 100_000,
8178 RecipientOnionFields::secret_only(our_payment_secret), height + 1, &None).unwrap();
8179 // Edit amt_to_forward to simulate the sender having set
8180 // the final amount and the routing node taking less fee
8181 if let msgs::OutboundOnionPayload::Receive { ref mut amt_msat, .. } = onion_payloads[1] {
8184 let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
8185 payment_event.msgs[0].onion_routing_packet = new_onion_packet;
8188 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
8189 check_added_monitors!(node, 0);
8190 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
8191 expect_pending_htlcs_forwardable!(node);
8194 let mut events_2 = node.node.get_and_clear_pending_msg_events();
8195 assert_eq!(events_2.len(), 1);
8196 check_added_monitors!(node, 1);
8197 payment_event = SendEvent::from_event(events_2.remove(0));
8198 assert_eq!(payment_event.msgs.len(), 1);
8200 let events_2 = node.node.get_and_clear_pending_events();
8201 assert!(events_2.is_empty());
8208 let ev = remove_first_msg_event_to_node(&expected_paths[1][0].node.get_our_node_id(), &mut events);
8209 pass_along_path(&nodes[0], expected_paths[1], 101_000, our_payment_hash.clone(), Some(our_payment_secret), ev, true, None);
8211 claim_payment_along_route(&nodes[0], expected_paths, false, our_payment_preimage);
8214 fn do_test_overshoot_mpp(msat_amounts: &[u64], total_msat: u64) {
8216 let routing_node_count = msat_amounts.len();
8217 let node_count = routing_node_count + 2;
8219 let chanmon_cfgs = create_chanmon_cfgs(node_count);
8220 let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8221 let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8222 let nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8227 // Create channels for each amount
8228 let mut expected_paths = Vec::with_capacity(routing_node_count);
8229 let mut src_chan_ids = Vec::with_capacity(routing_node_count);
8230 let mut dst_chan_ids = Vec::with_capacity(routing_node_count);
8231 for i in 0..routing_node_count {
8232 let routing_node = 2 + i;
8233 let src_chan_id = create_announced_chan_between_nodes(&nodes, src_idx, routing_node).0.contents.short_channel_id;
8234 src_chan_ids.push(src_chan_id);
8235 let dst_chan_id = create_announced_chan_between_nodes(&nodes, routing_node, dst_idx).0.contents.short_channel_id;
8236 dst_chan_ids.push(dst_chan_id);
8237 let path = vec![&nodes[routing_node], &nodes[dst_idx]];
8238 expected_paths.push(path);
8240 let expected_paths: Vec<&[&Node]> = expected_paths.iter().map(|route| route.as_slice()).collect();
8242 // Create a route for each amount
8243 let example_amount = 100000;
8244 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);
8245 let sample_path = route.paths.pop().unwrap();
8246 for i in 0..routing_node_count {
8247 let routing_node = 2 + i;
8248 let mut path = sample_path.clone();
8249 path.hops[0].pubkey = nodes[routing_node].node.get_our_node_id();
8250 path.hops[0].short_channel_id = src_chan_ids[i];
8251 path.hops[1].pubkey = nodes[dst_idx].node.get_our_node_id();
8252 path.hops[1].short_channel_id = dst_chan_ids[i];
8253 path.hops[1].fee_msat = msat_amounts[i];
8254 route.paths.push(path);
8257 // Send payment with manually set total_msat
8258 let payment_id = PaymentId(nodes[src_idx].keys_manager.backing.get_secure_random_bytes());
8259 let onion_session_privs = nodes[src_idx].node.test_add_new_pending_payment(our_payment_hash,
8260 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8261 nodes[src_idx].node.test_send_payment_internal(&route, our_payment_hash,
8262 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8263 check_added_monitors!(nodes[src_idx], expected_paths.len());
8265 let mut events = nodes[src_idx].node.get_and_clear_pending_msg_events();
8266 assert_eq!(events.len(), expected_paths.len());
8267 let mut amount_received = 0;
8268 for (path_idx, expected_path) in expected_paths.iter().enumerate() {
8269 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
8271 let current_path_amount = msat_amounts[path_idx];
8272 amount_received += current_path_amount;
8273 let became_claimable_now = amount_received >= total_msat && amount_received - current_path_amount < total_msat;
8274 pass_along_path(&nodes[src_idx], expected_path, amount_received, our_payment_hash.clone(), Some(our_payment_secret), ev, became_claimable_now, None);
8277 claim_payment_along_route(&nodes[src_idx], &expected_paths, false, our_payment_preimage);
8281 fn test_overshoot_mpp() {
8282 do_test_overshoot_mpp(&[100_000, 101_000], 200_000);
8283 do_test_overshoot_mpp(&[100_000, 10_000, 100_000], 200_000);
8287 fn test_simple_mpp() {
8288 // Simple test of sending a multi-path payment.
8289 let chanmon_cfgs = create_chanmon_cfgs(4);
8290 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8291 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8292 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8294 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8295 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8296 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8297 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8299 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8300 let path = route.paths[0].clone();
8301 route.paths.push(path);
8302 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
8303 route.paths[0].hops[0].short_channel_id = chan_1_id;
8304 route.paths[0].hops[1].short_channel_id = chan_3_id;
8305 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
8306 route.paths[1].hops[0].short_channel_id = chan_2_id;
8307 route.paths[1].hops[1].short_channel_id = chan_4_id;
8308 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8309 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8313 fn test_preimage_storage() {
8314 // Simple test of payment preimage storage allowing no client-side storage to claim payments
8315 let chanmon_cfgs = create_chanmon_cfgs(2);
8316 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8317 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8318 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8320 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8323 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
8324 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8325 nodes[0].node.send_payment_with_route(&route, payment_hash,
8326 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8327 check_added_monitors!(nodes[0], 1);
8328 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8329 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8330 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8331 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8333 // Note that after leaving the above scope we have no knowledge of any arguments or return
8334 // values from previous calls.
8335 expect_pending_htlcs_forwardable!(nodes[1]);
8336 let events = nodes[1].node.get_and_clear_pending_events();
8337 assert_eq!(events.len(), 1);
8339 Event::PaymentClaimable { ref purpose, .. } => {
8341 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8342 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8344 _ => panic!("expected PaymentPurpose::InvoicePayment")
8347 _ => panic!("Unexpected event"),
8352 fn test_bad_secret_hash() {
8353 // Simple test of unregistered payment hash/invalid payment secret handling
8354 let chanmon_cfgs = create_chanmon_cfgs(2);
8355 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8356 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8357 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8359 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8361 let random_payment_hash = PaymentHash([42; 32]);
8362 let random_payment_secret = PaymentSecret([43; 32]);
8363 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8364 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8366 // All the below cases should end up being handled exactly identically, so we macro the
8367 // resulting events.
8368 macro_rules! handle_unknown_invalid_payment_data {
8369 ($payment_hash: expr) => {
8370 check_added_monitors!(nodes[0], 1);
8371 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8372 let payment_event = SendEvent::from_event(events.pop().unwrap());
8373 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8374 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8376 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8377 // again to process the pending backwards-failure of the HTLC
8378 expect_pending_htlcs_forwardable!(nodes[1]);
8379 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8380 check_added_monitors!(nodes[1], 1);
8382 // We should fail the payment back
8383 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8384 match events.pop().unwrap() {
8385 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8386 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8387 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8389 _ => panic!("Unexpected event"),
8394 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8395 // Error data is the HTLC value (100,000) and current block height
8396 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8398 // Send a payment with the right payment hash but the wrong payment secret
8399 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
8400 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8401 handle_unknown_invalid_payment_data!(our_payment_hash);
8402 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8404 // Send a payment with a random payment hash, but the right payment secret
8405 nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8406 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8407 handle_unknown_invalid_payment_data!(random_payment_hash);
8408 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8410 // Send a payment with a random payment hash and random payment secret
8411 nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8412 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8413 handle_unknown_invalid_payment_data!(random_payment_hash);
8414 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8418 fn test_update_err_monitor_lockdown() {
8419 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8420 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8421 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8424 // This scenario may happen in a watchtower setup, where watchtower process a block height
8425 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8426 // commitment at same time.
8428 let chanmon_cfgs = create_chanmon_cfgs(2);
8429 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8430 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8431 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8433 // Create some initial channel
8434 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8435 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8437 // Rebalance the network to generate htlc in the two directions
8438 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8440 // Route a HTLC from node 0 to node 1 (but don't settle)
8441 let (preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8443 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8444 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8445 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8446 let persister = test_utils::TestPersister::new();
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), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8456 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), Ok(ChannelMonitorUpdateStatus::Completed));
8459 let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8460 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8461 // transaction lock time requirements here.
8462 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 200));
8463 watchtower.chain_monitor.block_connected(&block, 200);
8465 // Try to update ChannelMonitor
8466 nodes[1].node.claim_funds(preimage);
8467 check_added_monitors!(nodes[1], 1);
8468 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8470 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8471 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8472 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8474 let mut node_0_per_peer_lock;
8475 let mut node_0_peer_state_lock;
8476 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) {
8477 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8478 assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::InProgress);
8479 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8480 } else { assert!(false); }
8485 // Our local monitor is in-sync and hasn't processed yet timeout
8486 check_added_monitors!(nodes[0], 1);
8487 let events = nodes[0].node.get_and_clear_pending_events();
8488 assert_eq!(events.len(), 1);
8492 fn test_concurrent_monitor_claim() {
8493 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8494 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8495 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8496 // state N+1 confirms. Alice claims output from state N+1.
8498 let chanmon_cfgs = create_chanmon_cfgs(2);
8499 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8500 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8501 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8503 // Create some initial channel
8504 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8505 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8507 // Rebalance the network to generate htlc in the two directions
8508 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8510 // Route a HTLC from node 0 to node 1 (but don't settle)
8511 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8513 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8514 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8515 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8516 let persister = test_utils::TestPersister::new();
8517 let alice_broadcaster = test_utils::TestBroadcaster::with_blocks(
8518 Arc::new(Mutex::new(nodes[0].blocks.lock().unwrap().clone())),
8520 let watchtower_alice = {
8522 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8523 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8524 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8525 assert!(new_monitor == *monitor);
8528 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &alice_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8529 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), Ok(ChannelMonitorUpdateStatus::Completed));
8532 let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8533 // Make Alice aware of enough blocks that it doesn't think we're violating transaction lock time
8534 // requirements here.
8535 const HTLC_TIMEOUT_BROADCAST: u32 = CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS;
8536 alice_broadcaster.blocks.lock().unwrap().resize((HTLC_TIMEOUT_BROADCAST) as usize, (block.clone(), HTLC_TIMEOUT_BROADCAST));
8537 watchtower_alice.chain_monitor.block_connected(&block, HTLC_TIMEOUT_BROADCAST);
8539 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8541 let mut txn = alice_broadcaster.txn_broadcast();
8542 assert_eq!(txn.len(), 2);
8546 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8547 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8548 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8549 let persister = test_utils::TestPersister::new();
8550 let bob_broadcaster = test_utils::TestBroadcaster::with_blocks(Arc::clone(&alice_broadcaster.blocks));
8551 let watchtower_bob = {
8553 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8554 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8555 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8556 assert!(new_monitor == *monitor);
8559 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &bob_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8560 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), Ok(ChannelMonitorUpdateStatus::Completed));
8563 watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST - 1);
8565 // Route another payment to generate another update with still previous HTLC pending
8566 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8567 nodes[1].node.send_payment_with_route(&route, payment_hash,
8568 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8569 check_added_monitors!(nodes[1], 1);
8571 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8572 assert_eq!(updates.update_add_htlcs.len(), 1);
8573 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8575 let mut node_0_per_peer_lock;
8576 let mut node_0_peer_state_lock;
8577 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) {
8578 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8579 // Watchtower Alice should already have seen the block and reject the update
8580 assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::InProgress);
8581 assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8582 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8583 } else { assert!(false); }
8588 // Our local monitor is in-sync and hasn't processed yet timeout
8589 check_added_monitors!(nodes[0], 1);
8591 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8592 watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST);
8594 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8597 let mut txn = bob_broadcaster.txn_broadcast();
8598 assert_eq!(txn.len(), 2);
8599 bob_state_y = txn.remove(0);
8602 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8603 let height = HTLC_TIMEOUT_BROADCAST + 1;
8604 connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
8605 check_closed_broadcast(&nodes[0], 1, true);
8606 check_closed_event!(&nodes[0], 1, ClosureReason::HolderForceClosed, false,
8607 [nodes[1].node.get_our_node_id()], 100000);
8608 watchtower_alice.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, vec![bob_state_y.clone()]), height);
8609 check_added_monitors(&nodes[0], 1);
8611 let htlc_txn = alice_broadcaster.txn_broadcast();
8612 assert_eq!(htlc_txn.len(), 2);
8613 check_spends!(htlc_txn[0], bob_state_y);
8614 // Alice doesn't clean up the old HTLC claim since it hasn't seen a conflicting spend for
8615 // it. However, she should, because it now has an invalid parent.
8616 check_spends!(htlc_txn[1], alice_state);
8621 fn test_pre_lockin_no_chan_closed_update() {
8622 // Test that if a peer closes a channel in response to a funding_created message we don't
8623 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8626 // Doing so would imply a channel monitor update before the initial channel monitor
8627 // registration, violating our API guarantees.
8629 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8630 // then opening a second channel with the same funding output as the first (which is not
8631 // rejected because the first channel does not exist in the ChannelManager) and closing it
8632 // before receiving funding_signed.
8633 let chanmon_cfgs = create_chanmon_cfgs(2);
8634 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8635 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8636 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8638 // Create an initial channel
8639 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8640 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8641 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8642 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8643 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8645 // Move the first channel through the funding flow...
8646 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8648 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8649 check_added_monitors!(nodes[0], 0);
8651 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8652 let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8653 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8654 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8655 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("Hi".to_string()) }, true,
8656 [nodes[1].node.get_our_node_id(); 2], 100000);
8660 fn test_htlc_no_detection() {
8661 // This test is a mutation to underscore the detection logic bug we had
8662 // before #653. HTLC value routed is above the remaining balance, thus
8663 // inverting HTLC and `to_remote` output. HTLC will come second and
8664 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8665 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8666 // outputs order detection for correct spending children filtring.
8668 let chanmon_cfgs = create_chanmon_cfgs(2);
8669 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8670 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8671 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8673 // Create some initial channels
8674 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8676 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8677 let (_, our_payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8678 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8679 assert_eq!(local_txn[0].input.len(), 1);
8680 assert_eq!(local_txn[0].output.len(), 3);
8681 check_spends!(local_txn[0], chan_1.3);
8683 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8684 let block = create_dummy_block(nodes[0].best_block_hash(), 42, vec![local_txn[0].clone()]);
8685 connect_block(&nodes[0], &block);
8686 // We deliberately connect the local tx twice as this should provoke a failure calling
8687 // this test before #653 fix.
8688 chain::Listen::block_connected(&nodes[0].chain_monitor.chain_monitor, &block, nodes[0].best_block_info().1 + 1);
8689 check_closed_broadcast!(nodes[0], true);
8690 check_added_monitors!(nodes[0], 1);
8691 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
8692 connect_blocks(&nodes[0], TEST_FINAL_CLTV);
8694 let htlc_timeout = {
8695 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8696 assert_eq!(node_txn.len(), 1);
8697 assert_eq!(node_txn[0].input.len(), 1);
8698 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8699 check_spends!(node_txn[0], local_txn[0]);
8703 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![htlc_timeout.clone()]));
8704 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8705 expect_payment_failed!(nodes[0], our_payment_hash, false);
8708 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8709 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8710 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8711 // Carol, Alice would be the upstream node, and Carol the downstream.)
8713 // Steps of the test:
8714 // 1) Alice sends a HTLC to Carol through Bob.
8715 // 2) Carol doesn't settle the HTLC.
8716 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8717 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8718 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8719 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8720 // 5) Carol release the preimage to Bob off-chain.
8721 // 6) Bob claims the offered output on the broadcasted commitment.
8722 let chanmon_cfgs = create_chanmon_cfgs(3);
8723 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8724 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8725 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8727 // Create some initial channels
8728 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8729 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8731 // Steps (1) and (2):
8732 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8733 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8735 // Check that Alice's commitment transaction now contains an output for this HTLC.
8736 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8737 check_spends!(alice_txn[0], chan_ab.3);
8738 assert_eq!(alice_txn[0].output.len(), 2);
8739 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8740 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8741 assert_eq!(alice_txn.len(), 2);
8743 // Steps (3) and (4):
8744 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8745 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8746 let mut force_closing_node = 0; // Alice force-closes
8747 let mut counterparty_node = 1; // Bob if Alice force-closes
8750 if !broadcast_alice {
8751 force_closing_node = 1;
8752 counterparty_node = 0;
8754 nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8755 check_closed_broadcast!(nodes[force_closing_node], true);
8756 check_added_monitors!(nodes[force_closing_node], 1);
8757 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed, [nodes[counterparty_node].node.get_our_node_id()], 100000);
8758 if go_onchain_before_fulfill {
8759 let txn_to_broadcast = match broadcast_alice {
8760 true => alice_txn.clone(),
8761 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8763 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8764 if broadcast_alice {
8765 check_closed_broadcast!(nodes[1], true);
8766 check_added_monitors!(nodes[1], 1);
8767 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
8772 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8773 // process of removing the HTLC from their commitment transactions.
8774 nodes[2].node.claim_funds(payment_preimage);
8775 check_added_monitors!(nodes[2], 1);
8776 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8778 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8779 assert!(carol_updates.update_add_htlcs.is_empty());
8780 assert!(carol_updates.update_fail_htlcs.is_empty());
8781 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8782 assert!(carol_updates.update_fee.is_none());
8783 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8785 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8786 let went_onchain = go_onchain_before_fulfill || force_closing_node == 1;
8787 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if went_onchain { None } else { Some(1000) }, went_onchain, false);
8788 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8789 if !go_onchain_before_fulfill && broadcast_alice {
8790 let events = nodes[1].node.get_and_clear_pending_msg_events();
8791 assert_eq!(events.len(), 1);
8793 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8794 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8796 _ => panic!("Unexpected event"),
8799 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8800 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8801 // Carol<->Bob's updated commitment transaction info.
8802 check_added_monitors!(nodes[1], 2);
8804 let events = nodes[1].node.get_and_clear_pending_msg_events();
8805 assert_eq!(events.len(), 2);
8806 let bob_revocation = match events[0] {
8807 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8808 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8811 _ => panic!("Unexpected event"),
8813 let bob_updates = match events[1] {
8814 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8815 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8818 _ => panic!("Unexpected event"),
8821 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8822 check_added_monitors!(nodes[2], 1);
8823 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8824 check_added_monitors!(nodes[2], 1);
8826 let events = nodes[2].node.get_and_clear_pending_msg_events();
8827 assert_eq!(events.len(), 1);
8828 let carol_revocation = match events[0] {
8829 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8830 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8833 _ => panic!("Unexpected event"),
8835 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8836 check_added_monitors!(nodes[1], 1);
8838 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8839 // here's where we put said channel's commitment tx on-chain.
8840 let mut txn_to_broadcast = alice_txn.clone();
8841 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8842 if !go_onchain_before_fulfill {
8843 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8844 // If Bob was the one to force-close, he will have already passed these checks earlier.
8845 if broadcast_alice {
8846 check_closed_broadcast!(nodes[1], true);
8847 check_added_monitors!(nodes[1], 1);
8848 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
8850 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8851 if broadcast_alice {
8852 assert_eq!(bob_txn.len(), 1);
8853 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8855 assert_eq!(bob_txn.len(), 2);
8856 check_spends!(bob_txn[0], chan_ab.3);
8861 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8862 // broadcasted commitment transaction.
8864 let script_weight = match broadcast_alice {
8865 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8866 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8868 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8869 // Bob force-closed and broadcasts the commitment transaction along with a
8870 // HTLC-output-claiming transaction.
8871 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8872 if broadcast_alice {
8873 assert_eq!(bob_txn.len(), 1);
8874 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8875 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8877 assert_eq!(bob_txn.len(), 2);
8878 check_spends!(bob_txn[1], txn_to_broadcast[0]);
8879 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8885 fn test_onchain_htlc_settlement_after_close() {
8886 do_test_onchain_htlc_settlement_after_close(true, true);
8887 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8888 do_test_onchain_htlc_settlement_after_close(true, false);
8889 do_test_onchain_htlc_settlement_after_close(false, false);
8893 fn test_duplicate_temporary_channel_id_from_different_peers() {
8894 // Tests that we can accept two different `OpenChannel` requests with the same
8895 // `temporary_channel_id`, as long as they are from different peers.
8896 let chanmon_cfgs = create_chanmon_cfgs(3);
8897 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8898 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8899 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8901 // Create an first channel channel
8902 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8903 let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8905 // Create an second channel
8906 nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None).unwrap();
8907 let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8909 // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8910 // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8911 open_chan_msg_chan_2_0.temporary_channel_id = open_chan_msg_chan_1_0.temporary_channel_id;
8913 // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8914 // `temporary_channel_id` as they are from different peers.
8915 nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
8917 let events = nodes[0].node.get_and_clear_pending_msg_events();
8918 assert_eq!(events.len(), 1);
8920 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8921 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8922 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8924 _ => panic!("Unexpected event"),
8928 nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
8930 let events = nodes[0].node.get_and_clear_pending_msg_events();
8931 assert_eq!(events.len(), 1);
8933 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8934 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
8935 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8937 _ => panic!("Unexpected event"),
8943 fn test_duplicate_chan_id() {
8944 // Test that if a given peer tries to open a channel with the same channel_id as one that is
8945 // already open we reject it and keep the old channel.
8947 // Previously, full_stack_target managed to figure out that if you tried to open two channels
8948 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8949 // the existing channel when we detect the duplicate new channel, screwing up our monitor
8950 // updating logic for the existing channel.
8951 let chanmon_cfgs = create_chanmon_cfgs(2);
8952 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8953 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8954 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8956 // Create an initial channel
8957 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8958 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8959 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8960 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()));
8962 // Try to create a second channel with the same temporary_channel_id as the first and check
8963 // that it is rejected.
8964 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8966 let events = nodes[1].node.get_and_clear_pending_msg_events();
8967 assert_eq!(events.len(), 1);
8969 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8970 // Technically, at this point, nodes[1] would be justified in thinking both the
8971 // first (valid) and second (invalid) channels are closed, given they both have
8972 // the same non-temporary channel_id. However, currently we do not, so we just
8973 // move forward with it.
8974 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8975 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8977 _ => panic!("Unexpected event"),
8981 // Move the first channel through the funding flow...
8982 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8984 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8985 check_added_monitors!(nodes[0], 0);
8987 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8988 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8990 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8991 assert_eq!(added_monitors.len(), 1);
8992 assert_eq!(added_monitors[0].0, funding_output);
8993 added_monitors.clear();
8995 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
8997 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8999 let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
9000 let channel_id = funding_outpoint.to_channel_id();
9002 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
9005 // First try to open a second channel with a temporary channel id equal to the txid-based one.
9006 // Technically this is allowed by the spec, but we don't support it and there's little reason
9007 // to. Still, it shouldn't cause any other issues.
9008 open_chan_msg.temporary_channel_id = channel_id;
9009 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
9011 let events = nodes[1].node.get_and_clear_pending_msg_events();
9012 assert_eq!(events.len(), 1);
9014 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9015 // Technically, at this point, nodes[1] would be justified in thinking both
9016 // channels are closed, but currently we do not, so we just move forward with it.
9017 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9018 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9020 _ => panic!("Unexpected event"),
9024 // Now try to create a second channel which has a duplicate funding output.
9025 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9026 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9027 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
9028 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()));
9029 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
9031 let (_, funding_created) = {
9032 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9033 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9034 // Once we call `get_funding_created` the channel has a duplicate channel_id as
9035 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
9036 // try to create another channel. Instead, we drop the channel entirely here (leaving the
9037 // channelmanager in a possibly nonsense state instead).
9038 match a_peer_state.channel_by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap() {
9039 ChannelPhase::UnfundedOutboundV1(chan) => {
9040 let logger = test_utils::TestLogger::new();
9041 chan.get_funding_created(tx.clone(), funding_outpoint, false, &&logger).map_err(|_| ()).unwrap()
9043 _ => panic!("Unexpected ChannelPhase variant"),
9046 check_added_monitors!(nodes[0], 0);
9047 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9048 // At this point we'll look up if the channel_id is present and immediately fail the channel
9049 // without trying to persist the `ChannelMonitor`.
9050 check_added_monitors!(nodes[1], 0);
9052 // ...still, nodes[1] will reject the duplicate channel.
9054 let events = nodes[1].node.get_and_clear_pending_msg_events();
9055 assert_eq!(events.len(), 1);
9057 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9058 // Technically, at this point, nodes[1] would be justified in thinking both
9059 // channels are closed, but currently we do not, so we just move forward with it.
9060 assert_eq!(msg.channel_id, channel_id);
9061 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9063 _ => panic!("Unexpected event"),
9067 // finally, finish creating the original channel and send a payment over it to make sure
9068 // everything is functional.
9069 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9071 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9072 assert_eq!(added_monitors.len(), 1);
9073 assert_eq!(added_monitors[0].0, funding_output);
9074 added_monitors.clear();
9076 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9078 let events_4 = nodes[0].node.get_and_clear_pending_events();
9079 assert_eq!(events_4.len(), 0);
9080 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9081 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9083 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9084 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9085 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9087 send_payment(&nodes[0], &[&nodes[1]], 8000000);
9091 fn test_error_chans_closed() {
9092 // Test that we properly handle error messages, closing appropriate channels.
9094 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9095 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9096 // we can test various edge cases around it to ensure we don't regress.
9097 let chanmon_cfgs = create_chanmon_cfgs(3);
9098 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9099 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9100 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9102 // Create some initial channels
9103 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9104 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9105 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
9107 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9108 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9109 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9111 // Closing a channel from a different peer has no effect
9112 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9113 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9115 // Closing one channel doesn't impact others
9116 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9117 check_added_monitors!(nodes[0], 1);
9118 check_closed_broadcast!(nodes[0], false);
9119 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) },
9120 [nodes[1].node.get_our_node_id()], 100000);
9121 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9122 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9123 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);
9124 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);
9126 // A null channel ID should close all channels
9127 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9128 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: ChannelId::new_zero(), data: "ERR".to_owned() });
9129 check_added_monitors!(nodes[0], 2);
9130 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) },
9131 [nodes[1].node.get_our_node_id(); 2], 100000);
9132 let events = nodes[0].node.get_and_clear_pending_msg_events();
9133 assert_eq!(events.len(), 2);
9135 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9136 assert_eq!(msg.contents.flags & 2, 2);
9138 _ => panic!("Unexpected event"),
9141 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9142 assert_eq!(msg.contents.flags & 2, 2);
9144 _ => panic!("Unexpected event"),
9146 // Note that at this point users of a standard PeerHandler will end up calling
9147 // peer_disconnected.
9148 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9149 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9151 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9152 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9153 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9157 fn test_invalid_funding_tx() {
9158 // Test that we properly handle invalid funding transactions sent to us from a peer.
9160 // Previously, all other major lightning implementations had failed to properly sanitize
9161 // funding transactions from their counterparties, leading to a multi-implementation critical
9162 // security vulnerability (though we always sanitized properly, we've previously had
9163 // un-released crashes in the sanitization process).
9165 // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9166 // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9167 // gave up on it. We test this here by generating such a transaction.
9168 let chanmon_cfgs = create_chanmon_cfgs(2);
9169 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9170 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9171 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9173 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9174 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()));
9175 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()));
9177 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9179 // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9180 // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9181 // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9183 let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9184 let wit_program_script: Script = wit_program.into();
9185 for output in tx.output.iter_mut() {
9186 // Make the confirmed funding transaction have a bogus script_pubkey
9187 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9190 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9191 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()));
9192 check_added_monitors!(nodes[1], 1);
9193 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9195 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()));
9196 check_added_monitors!(nodes[0], 1);
9197 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9199 let events_1 = nodes[0].node.get_and_clear_pending_events();
9200 assert_eq!(events_1.len(), 0);
9202 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9203 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9204 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9206 let expected_err = "funding tx had wrong script/value or output index";
9207 confirm_transaction_at(&nodes[1], &tx, 1);
9208 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() },
9209 [nodes[0].node.get_our_node_id()], 100000);
9210 check_added_monitors!(nodes[1], 1);
9211 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9212 assert_eq!(events_2.len(), 1);
9213 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9214 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9215 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9216 assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9217 } else { panic!(); }
9218 } else { panic!(); }
9219 assert_eq!(nodes[1].node.list_channels().len(), 0);
9221 // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9222 // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9223 // as its not 32 bytes long.
9224 let mut spend_tx = Transaction {
9225 version: 2i32, lock_time: PackedLockTime::ZERO,
9226 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9227 previous_output: BitcoinOutPoint {
9231 script_sig: Script::new(),
9232 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9233 witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9235 output: vec![TxOut {
9237 script_pubkey: Script::new(),
9240 check_spends!(spend_tx, tx);
9241 mine_transaction(&nodes[1], &spend_tx);
9245 fn test_coinbase_funding_tx() {
9246 // Miners are able to fund channels directly from coinbase transactions, however
9247 // by consensus rules, outputs of a coinbase transaction are encumbered by a 100
9248 // block maturity timelock. To ensure that a (non-0conf) channel like this is enforceable
9249 // on-chain, the minimum depth is updated to 100 blocks for coinbase funding transactions.
9251 // Note that 0conf channels with coinbase funding transactions are unaffected and are
9252 // immediately operational after opening.
9253 let chanmon_cfgs = create_chanmon_cfgs(2);
9254 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9255 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9256 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9258 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9259 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9261 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9262 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9264 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9266 // Create the coinbase funding transaction.
9267 let (temporary_channel_id, tx, _) = create_coinbase_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9269 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9270 check_added_monitors!(nodes[0], 0);
9271 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9273 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9274 check_added_monitors!(nodes[1], 1);
9275 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9277 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9279 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
9280 check_added_monitors!(nodes[0], 1);
9282 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9283 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
9285 // Starting at height 0, we "confirm" the coinbase at height 1.
9286 confirm_transaction_at(&nodes[0], &tx, 1);
9287 // We connect 98 more blocks to have 99 confirmations for the coinbase transaction.
9288 connect_blocks(&nodes[0], COINBASE_MATURITY - 2);
9289 // Check that we have no pending message events (we have not queued a `channel_ready` yet).
9290 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
9291 // Now connect one more block which results in 100 confirmations of the coinbase transaction.
9292 connect_blocks(&nodes[0], 1);
9293 // There should now be a `channel_ready` which can be handled.
9294 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()));
9296 confirm_transaction_at(&nodes[1], &tx, 1);
9297 connect_blocks(&nodes[1], COINBASE_MATURITY - 2);
9298 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9299 connect_blocks(&nodes[1], 1);
9300 expect_channel_ready_event(&nodes[1], &nodes[0].node.get_our_node_id());
9301 create_chan_between_nodes_with_value_confirm_second(&nodes[0], &nodes[1]);
9304 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9305 // In the first version of the chain::Confirm interface, after a refactor was made to not
9306 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9307 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9308 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9309 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9310 // spending transaction until height N+1 (or greater). This was due to the way
9311 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9312 // spending transaction at the height the input transaction was confirmed at, not whether we
9313 // should broadcast a spending transaction at the current height.
9314 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9315 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9316 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9317 // until we learned about an additional block.
9319 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9320 // aren't broadcasting transactions too early (ie not broadcasting them at all).
9321 let chanmon_cfgs = create_chanmon_cfgs(3);
9322 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9323 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9324 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9325 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9327 create_announced_chan_between_nodes(&nodes, 0, 1);
9328 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
9329 let (_, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9330 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
9331 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9333 nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9334 check_closed_broadcast!(nodes[1], true);
9335 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[2].node.get_our_node_id()], 100000);
9336 check_added_monitors!(nodes[1], 1);
9337 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9338 assert_eq!(node_txn.len(), 1);
9340 let conf_height = nodes[1].best_block_info().1;
9341 if !test_height_before_timelock {
9342 connect_blocks(&nodes[1], 24 * 6);
9344 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9345 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9346 if test_height_before_timelock {
9347 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9348 // generate any events or broadcast any transactions
9349 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9350 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9352 // We should broadcast an HTLC transaction spending our funding transaction first
9353 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9354 assert_eq!(spending_txn.len(), 2);
9355 assert_eq!(spending_txn[0].txid(), node_txn[0].txid());
9356 check_spends!(spending_txn[1], node_txn[0]);
9357 // We should also generate a SpendableOutputs event with the to_self output (as its
9359 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9360 assert_eq!(descriptor_spend_txn.len(), 1);
9362 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9363 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9364 // additional block built on top of the current chain.
9365 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9366 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9367 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 }]);
9368 check_added_monitors!(nodes[1], 1);
9370 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9371 assert!(updates.update_add_htlcs.is_empty());
9372 assert!(updates.update_fulfill_htlcs.is_empty());
9373 assert_eq!(updates.update_fail_htlcs.len(), 1);
9374 assert!(updates.update_fail_malformed_htlcs.is_empty());
9375 assert!(updates.update_fee.is_none());
9376 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9377 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9378 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9383 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9384 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9385 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9388 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9389 let chanmon_cfgs = create_chanmon_cfgs(2);
9390 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9391 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9392 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9394 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9396 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9397 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
9398 let route = get_route!(nodes[0], payment_params, 10_000).unwrap();
9400 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9403 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9404 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9405 check_added_monitors!(nodes[0], 1);
9406 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9407 assert_eq!(events.len(), 1);
9408 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9409 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9410 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9412 expect_pending_htlcs_forwardable!(nodes[1]);
9413 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9416 // Note that we use a different PaymentId here to allow us to duplicativly pay
9417 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9418 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9419 check_added_monitors!(nodes[0], 1);
9420 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9421 assert_eq!(events.len(), 1);
9422 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9423 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9424 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9425 // At this point, nodes[1] would notice it has too much value for the payment. It will
9426 // assume the second is a privacy attack (no longer particularly relevant
9427 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9428 // the first HTLC delivered above.
9431 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9432 nodes[1].node.process_pending_htlc_forwards();
9434 if test_for_second_fail_panic {
9435 // Now we go fail back the first HTLC from the user end.
9436 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9438 let expected_destinations = vec![
9439 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9440 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9442 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], expected_destinations);
9443 nodes[1].node.process_pending_htlc_forwards();
9445 check_added_monitors!(nodes[1], 1);
9446 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9447 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9449 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9450 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9451 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9453 let failure_events = nodes[0].node.get_and_clear_pending_events();
9454 assert_eq!(failure_events.len(), 4);
9455 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9456 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9457 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9458 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9460 // Let the second HTLC fail and claim the first
9461 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9462 nodes[1].node.process_pending_htlc_forwards();
9464 check_added_monitors!(nodes[1], 1);
9465 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9466 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9467 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9469 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9471 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9476 fn test_dup_htlc_second_fail_panic() {
9477 // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9478 // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9479 // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9480 // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9481 do_test_dup_htlc_second_rejected(true);
9485 fn test_dup_htlc_second_rejected() {
9486 // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9487 // simply reject the second HTLC but are still able to claim the first HTLC.
9488 do_test_dup_htlc_second_rejected(false);
9492 fn test_inconsistent_mpp_params() {
9493 // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9494 // such HTLC and allow the second to stay.
9495 let chanmon_cfgs = create_chanmon_cfgs(4);
9496 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9497 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9498 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9500 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9501 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9502 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9503 let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9505 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9506 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
9507 let mut route = get_route!(nodes[0], payment_params, 15_000_000).unwrap();
9508 assert_eq!(route.paths.len(), 2);
9509 route.paths.sort_by(|path_a, _| {
9510 // Sort the path so that the path through nodes[1] comes first
9511 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9512 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9515 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9517 let cur_height = nodes[0].best_block_info().1;
9518 let payment_id = PaymentId([42; 32]);
9520 let session_privs = {
9521 // We create a fake route here so that we start with three pending HTLCs, which we'll
9522 // ultimately have, just not right away.
9523 let mut dup_route = route.clone();
9524 dup_route.paths.push(route.paths[1].clone());
9525 nodes[0].node.test_add_new_pending_payment(our_payment_hash,
9526 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &dup_route).unwrap()
9528 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
9529 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9530 &None, session_privs[0]).unwrap();
9531 check_added_monitors!(nodes[0], 1);
9534 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9535 assert_eq!(events.len(), 1);
9536 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9538 assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9540 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9541 RecipientOnionFields::secret_only(our_payment_secret), 14_000_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9542 check_added_monitors!(nodes[0], 1);
9545 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9546 assert_eq!(events.len(), 1);
9547 let payment_event = SendEvent::from_event(events.pop().unwrap());
9549 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9550 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9552 expect_pending_htlcs_forwardable!(nodes[2]);
9553 check_added_monitors!(nodes[2], 1);
9555 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9556 assert_eq!(events.len(), 1);
9557 let payment_event = SendEvent::from_event(events.pop().unwrap());
9559 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9560 check_added_monitors!(nodes[3], 0);
9561 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9563 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9564 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9565 // post-payment_secrets) and fail back the new HTLC.
9567 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9568 nodes[3].node.process_pending_htlc_forwards();
9569 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9570 nodes[3].node.process_pending_htlc_forwards();
9572 check_added_monitors!(nodes[3], 1);
9574 let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9575 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9576 commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9578 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 }]);
9579 check_added_monitors!(nodes[2], 1);
9581 let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9582 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9583 commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9585 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9587 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9588 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9589 &None, session_privs[2]).unwrap();
9590 check_added_monitors!(nodes[0], 1);
9592 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9593 assert_eq!(events.len(), 1);
9594 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9596 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9597 expect_payment_sent(&nodes[0], our_payment_preimage, Some(None), true, true);
9601 fn test_double_partial_claim() {
9602 // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9603 // time out, the sender resends only some of the MPP parts, then the user processes the
9604 // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9606 let chanmon_cfgs = create_chanmon_cfgs(4);
9607 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9608 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9609 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9611 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9612 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9613 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9614 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9616 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9617 assert_eq!(route.paths.len(), 2);
9618 route.paths.sort_by(|path_a, _| {
9619 // Sort the path so that the path through nodes[1] comes first
9620 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9621 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9624 send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9625 // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9626 // amount of time to respond to.
9628 // Connect some blocks to time out the payment
9629 connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9630 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9632 let failed_destinations = vec![
9633 HTLCDestination::FailedPayment { payment_hash },
9634 HTLCDestination::FailedPayment { payment_hash },
9636 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9638 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
9640 // nodes[1] now retries one of the two paths...
9641 nodes[0].node.send_payment_with_route(&route, payment_hash,
9642 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9643 check_added_monitors!(nodes[0], 2);
9645 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9646 assert_eq!(events.len(), 2);
9647 let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
9648 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9650 // At this point nodes[3] has received one half of the payment, and the user goes to handle
9651 // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9652 nodes[3].node.claim_funds(payment_preimage);
9653 check_added_monitors!(nodes[3], 0);
9654 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9657 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9658 #[derive(Clone, Copy, PartialEq)]
9659 enum ExposureEvent {
9660 /// Breach occurs at HTLC forwarding (see `send_htlc`)
9662 /// Breach occurs at HTLC reception (see `update_add_htlc`)
9664 /// Breach occurs at outbound update_fee (see `send_update_fee`)
9665 AtUpdateFeeOutbound,
9668 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool, multiplier_dust_limit: bool) {
9669 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9672 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9673 // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9674 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9675 // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9676 // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9677 // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9678 // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9679 // might be available again for HTLC processing once the dust bandwidth has cleared up.
9681 let chanmon_cfgs = create_chanmon_cfgs(2);
9682 let mut config = test_default_channel_config();
9683 config.channel_config.max_dust_htlc_exposure = if multiplier_dust_limit {
9684 // Default test fee estimator rate is 253 sat/kw, so we set the multiplier to 5_000_000 / 253
9685 // to get roughly the same initial value as the default setting when this test was
9686 // originally written.
9687 MaxDustHTLCExposure::FeeRateMultiplier(5_000_000 / 253)
9688 } else { MaxDustHTLCExposure::FixedLimitMsat(5_000_000) }; // initial default setting value
9689 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9690 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9691 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9693 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9694 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9695 open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9696 open_channel.max_accepted_htlcs = 60;
9698 open_channel.dust_limit_satoshis = 546;
9700 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9701 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9702 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9704 let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
9706 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9709 let mut node_0_per_peer_lock;
9710 let mut node_0_peer_state_lock;
9711 match get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, temporary_channel_id) {
9712 ChannelPhase::UnfundedOutboundV1(chan) => {
9713 chan.context.holder_dust_limit_satoshis = 546;
9715 _ => panic!("Unexpected ChannelPhase variant"),
9719 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9720 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()));
9721 check_added_monitors!(nodes[1], 1);
9722 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9724 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()));
9725 check_added_monitors!(nodes[0], 1);
9726 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9728 let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9729 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9730 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9732 // Fetch a route in advance as we will be unable to once we're unable to send.
9733 let (mut route, payment_hash, _, payment_secret) =
9734 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
9736 let (dust_buffer_feerate, max_dust_htlc_exposure_msat) = {
9737 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9738 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9739 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
9740 (chan.context().get_dust_buffer_feerate(None) as u64,
9741 chan.context().get_max_dust_htlc_exposure_msat(&LowerBoundedFeeEstimator(nodes[0].fee_estimator)))
9743 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;
9744 let dust_outbound_htlc_on_holder_tx: u64 = max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9746 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;
9747 let dust_inbound_htlc_on_holder_tx: u64 = max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9749 let dust_htlc_on_counterparty_tx: u64 = 4;
9750 let dust_htlc_on_counterparty_tx_msat: u64 = max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9753 if dust_outbound_balance {
9754 // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9755 // Outbound dust balance: 4372 sats
9756 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9757 for _ in 0..dust_outbound_htlc_on_holder_tx {
9758 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9759 nodes[0].node.send_payment_with_route(&route, payment_hash,
9760 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9763 // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9764 // Inbound dust balance: 4372 sats
9765 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9766 for _ in 0..dust_inbound_htlc_on_holder_tx {
9767 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9771 if dust_outbound_balance {
9772 // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9773 // Outbound dust balance: 5000 sats
9774 for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9775 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9776 nodes[0].node.send_payment_with_route(&route, payment_hash,
9777 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9780 // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9781 // Inbound dust balance: 5000 sats
9782 for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9783 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9788 if exposure_breach_event == ExposureEvent::AtHTLCForward {
9789 route.paths[0].hops.last_mut().unwrap().fee_msat =
9790 if on_holder_tx { dust_outbound_htlc_on_holder_tx_msat } else { dust_htlc_on_counterparty_tx_msat + 1 };
9791 // With default dust exposure: 5000 sats
9793 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9794 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9795 ), true, APIError::ChannelUnavailable { .. }, {});
9797 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9798 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9799 ), true, APIError::ChannelUnavailable { .. }, {});
9801 } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9802 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 });
9803 nodes[1].node.send_payment_with_route(&route, payment_hash,
9804 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9805 check_added_monitors!(nodes[1], 1);
9806 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9807 assert_eq!(events.len(), 1);
9808 let payment_event = SendEvent::from_event(events.remove(0));
9809 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9810 // With default dust exposure: 5000 sats
9812 // Outbound dust balance: 6399 sats
9813 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9814 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9815 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);
9817 // Outbound dust balance: 5200 sats
9818 nodes[0].logger.assert_log("lightning::ln::channel".to_string(),
9819 format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx",
9820 dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx - 1) + dust_htlc_on_counterparty_tx_msat + 4,
9821 max_dust_htlc_exposure_msat), 1);
9823 } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9824 route.paths[0].hops.last_mut().unwrap().fee_msat = 2_500_000;
9825 // For the multiplier dust exposure limit, since it scales with feerate,
9826 // we need to add a lot of HTLCs that will become dust at the new feerate
9827 // to cross the threshold.
9829 let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[1], Some(1_000), None);
9830 nodes[0].node.send_payment_with_route(&route, payment_hash,
9831 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9834 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9835 *feerate_lock = *feerate_lock * 10;
9837 nodes[0].node.timer_tick_occurred();
9838 check_added_monitors!(nodes[0], 1);
9839 nodes[0].logger.assert_log_contains("lightning::ln::channel", "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure", 1);
9842 let _ = nodes[0].node.get_and_clear_pending_msg_events();
9843 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9844 added_monitors.clear();
9847 fn do_test_max_dust_htlc_exposure_by_threshold_type(multiplier_dust_limit: bool) {
9848 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true, multiplier_dust_limit);
9849 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true, multiplier_dust_limit);
9850 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true, multiplier_dust_limit);
9851 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false, multiplier_dust_limit);
9852 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false, multiplier_dust_limit);
9853 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false, multiplier_dust_limit);
9854 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true, multiplier_dust_limit);
9855 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false, multiplier_dust_limit);
9856 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true, multiplier_dust_limit);
9857 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false, multiplier_dust_limit);
9858 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false, multiplier_dust_limit);
9859 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true, multiplier_dust_limit);
9863 fn test_max_dust_htlc_exposure() {
9864 do_test_max_dust_htlc_exposure_by_threshold_type(false);
9865 do_test_max_dust_htlc_exposure_by_threshold_type(true);
9869 fn test_non_final_funding_tx() {
9870 let chanmon_cfgs = create_chanmon_cfgs(2);
9871 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9872 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9873 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9875 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9876 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9877 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9878 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9879 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
9881 let best_height = nodes[0].node.best_block.read().unwrap().height();
9883 let chan_id = *nodes[0].network_chan_count.borrow();
9884 let events = nodes[0].node.get_and_clear_pending_events();
9885 let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
9886 assert_eq!(events.len(), 1);
9887 let mut tx = match events[0] {
9888 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9889 // Timelock the transaction _beyond_ the best client height + 1.
9890 Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 2), input: vec![input], output: vec![TxOut {
9891 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9894 _ => panic!("Unexpected event"),
9896 // Transaction should fail as it's evaluated as non-final for propagation.
9897 match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
9898 Err(APIError::APIMisuseError { err }) => {
9899 assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
9903 let events = nodes[0].node.get_and_clear_pending_events();
9904 assert_eq!(events.len(), 1);
9906 Event::ChannelClosed { channel_id, .. } => {
9907 assert_eq!(channel_id, temp_channel_id);
9909 _ => panic!("Unexpected event"),
9914 fn test_non_final_funding_tx_within_headroom() {
9915 let chanmon_cfgs = create_chanmon_cfgs(2);
9916 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9917 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9918 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9920 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9921 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9922 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9923 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9924 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
9926 let best_height = nodes[0].node.best_block.read().unwrap().height();
9928 let chan_id = *nodes[0].network_chan_count.borrow();
9929 let events = nodes[0].node.get_and_clear_pending_events();
9930 let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
9931 assert_eq!(events.len(), 1);
9932 let mut tx = match events[0] {
9933 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9934 // Timelock the transaction within a +1 headroom from the best block.
9935 Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 1), input: vec![input], output: vec![TxOut {
9936 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9939 _ => panic!("Unexpected event"),
9942 // Transaction should be accepted if it's in a +1 headroom from best block.
9943 assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
9944 get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9948 fn accept_busted_but_better_fee() {
9949 // If a peer sends us a fee update that is too low, but higher than our previous channel
9950 // feerate, we should accept it. In the future we may want to consider closing the channel
9951 // later, but for now we only accept the update.
9952 let mut chanmon_cfgs = create_chanmon_cfgs(2);
9953 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9954 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9955 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9957 create_chan_between_nodes(&nodes[0], &nodes[1]);
9959 // Set nodes[1] to expect 5,000 sat/kW.
9961 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
9962 *feerate_lock = 5000;
9965 // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
9967 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9968 *feerate_lock = 1000;
9970 nodes[0].node.timer_tick_occurred();
9971 check_added_monitors!(nodes[0], 1);
9973 let events = nodes[0].node.get_and_clear_pending_msg_events();
9974 assert_eq!(events.len(), 1);
9976 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9977 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9978 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9980 _ => panic!("Unexpected event"),
9983 // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
9986 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9987 *feerate_lock = 2000;
9989 nodes[0].node.timer_tick_occurred();
9990 check_added_monitors!(nodes[0], 1);
9992 let events = nodes[0].node.get_and_clear_pending_msg_events();
9993 assert_eq!(events.len(), 1);
9995 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9996 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9997 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9999 _ => panic!("Unexpected event"),
10002 // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
10005 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10006 *feerate_lock = 1000;
10008 nodes[0].node.timer_tick_occurred();
10009 check_added_monitors!(nodes[0], 1);
10011 let events = nodes[0].node.get_and_clear_pending_msg_events();
10012 assert_eq!(events.len(), 1);
10014 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
10015 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
10016 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
10017 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000 (- 250)".to_owned() },
10018 [nodes[0].node.get_our_node_id()], 100000);
10019 check_closed_broadcast!(nodes[1], true);
10020 check_added_monitors!(nodes[1], 1);
10022 _ => panic!("Unexpected event"),
10026 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
10027 let mut chanmon_cfgs = create_chanmon_cfgs(2);
10028 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10029 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10030 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10031 let min_final_cltv_expiry_delta = 120;
10032 let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
10033 min_final_cltv_expiry_delta - 2 };
10034 let recv_value = 100_000;
10036 create_chan_between_nodes(&nodes[0], &nodes[1]);
10038 let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), final_cltv_expiry_delta as u32);
10039 let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
10040 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
10041 Some(recv_value), Some(min_final_cltv_expiry_delta));
10042 (payment_hash, payment_preimage, payment_secret)
10044 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
10045 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
10047 let route = get_route!(nodes[0], payment_parameters, recv_value).unwrap();
10048 nodes[0].node.send_payment_with_route(&route, payment_hash,
10049 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
10050 check_added_monitors!(nodes[0], 1);
10051 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10052 assert_eq!(events.len(), 1);
10053 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
10054 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
10055 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
10056 expect_pending_htlcs_forwardable!(nodes[1]);
10059 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
10060 None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
10062 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
10064 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
10066 check_added_monitors!(nodes[1], 1);
10068 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
10069 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
10070 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
10072 expect_payment_failed!(nodes[0], payment_hash, true);
10077 fn test_payment_with_custom_min_cltv_expiry_delta() {
10078 do_payment_with_custom_min_final_cltv_expiry(false, false);
10079 do_payment_with_custom_min_final_cltv_expiry(false, true);
10080 do_payment_with_custom_min_final_cltv_expiry(true, false);
10081 do_payment_with_custom_min_final_cltv_expiry(true, true);
10085 fn test_disconnects_peer_awaiting_response_ticks() {
10086 // Tests that nodes which are awaiting on a response critical for channel responsiveness
10087 // disconnect their counterparty after `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10088 let mut chanmon_cfgs = create_chanmon_cfgs(2);
10089 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10090 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10091 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10093 // Asserts a disconnect event is queued to the user.
10094 let check_disconnect_event = |node: &Node, should_disconnect: bool| {
10095 let disconnect_event = node.node.get_and_clear_pending_msg_events().iter().find_map(|event|
10096 if let MessageSendEvent::HandleError { action, .. } = event {
10097 if let msgs::ErrorAction::DisconnectPeerWithWarning { .. } = action {
10106 assert_eq!(disconnect_event.is_some(), should_disconnect);
10109 // Fires timer ticks ensuring we only attempt to disconnect peers after reaching
10110 // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10111 let check_disconnect = |node: &Node| {
10112 // No disconnect without any timer ticks.
10113 check_disconnect_event(node, false);
10115 // No disconnect with 1 timer tick less than required.
10116 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS - 1 {
10117 node.node.timer_tick_occurred();
10118 check_disconnect_event(node, false);
10121 // Disconnect after reaching the required ticks.
10122 node.node.timer_tick_occurred();
10123 check_disconnect_event(node, true);
10125 // Disconnect again on the next tick if the peer hasn't been disconnected yet.
10126 node.node.timer_tick_occurred();
10127 check_disconnect_event(node, true);
10130 create_chan_between_nodes(&nodes[0], &nodes[1]);
10132 // We'll start by performing a fee update with Alice (nodes[0]) on the channel.
10133 *nodes[0].fee_estimator.sat_per_kw.lock().unwrap() *= 2;
10134 nodes[0].node.timer_tick_occurred();
10135 check_added_monitors!(&nodes[0], 1);
10136 let alice_fee_update = get_htlc_update_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
10137 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), alice_fee_update.update_fee.as_ref().unwrap());
10138 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &alice_fee_update.commitment_signed);
10139 check_added_monitors!(&nodes[1], 1);
10141 // This will prompt Bob (nodes[1]) to respond with his `CommitmentSigned` and `RevokeAndACK`.
10142 let (bob_revoke_and_ack, bob_commitment_signed) = get_revoke_commit_msgs!(&nodes[1], nodes[0].node.get_our_node_id());
10143 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revoke_and_ack);
10144 check_added_monitors!(&nodes[0], 1);
10145 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_commitment_signed);
10146 check_added_monitors(&nodes[0], 1);
10148 // Alice then needs to send her final `RevokeAndACK` to complete the commitment dance. We
10149 // pretend Bob hasn't received the message and check whether he'll disconnect Alice after
10150 // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10151 let alice_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
10152 check_disconnect(&nodes[1]);
10154 // Now, we'll reconnect them to test awaiting a `ChannelReestablish` message.
10156 // Note that since the commitment dance didn't complete above, Alice is expected to resend her
10157 // final `RevokeAndACK` to Bob to complete it.
10158 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
10159 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10160 let bob_init = msgs::Init {
10161 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
10163 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &bob_init, true).unwrap();
10164 let alice_init = msgs::Init {
10165 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
10167 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &alice_init, true).unwrap();
10169 // Upon reconnection, Alice sends her `ChannelReestablish` to Bob. Alice, however, hasn't
10170 // received Bob's yet, so she should disconnect him after reaching
10171 // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10172 let alice_channel_reestablish = get_event_msg!(
10173 nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id()
10175 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &alice_channel_reestablish);
10176 check_disconnect(&nodes[0]);
10178 // Bob now sends his `ChannelReestablish` to Alice to resume the channel and consider it "live".
10179 let bob_channel_reestablish = nodes[1].node.get_and_clear_pending_msg_events().iter().find_map(|event|
10180 if let MessageSendEvent::SendChannelReestablish { node_id, msg } = event {
10181 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
10187 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bob_channel_reestablish);
10189 // Sanity check that Alice won't disconnect Bob since she's no longer waiting for any messages.
10190 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
10191 nodes[0].node.timer_tick_occurred();
10192 check_disconnect_event(&nodes[0], false);
10195 // However, Bob is still waiting on Alice's `RevokeAndACK`, so he should disconnect her after
10196 // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10197 check_disconnect(&nodes[1]);
10199 // Finally, have Bob process the last message.
10200 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &alice_revoke_and_ack);
10201 check_added_monitors(&nodes[1], 1);
10203 // At this point, neither node should attempt to disconnect each other, since they aren't
10204 // waiting on any messages.
10205 for node in &nodes {
10206 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
10207 node.node.timer_tick_occurred();
10208 check_disconnect_event(node, false);
10214 fn test_remove_expired_outbound_unfunded_channels() {
10215 let chanmon_cfgs = create_chanmon_cfgs(2);
10216 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10217 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10218 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10220 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10221 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10222 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10223 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10224 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10226 let events = nodes[0].node.get_and_clear_pending_events();
10227 assert_eq!(events.len(), 1);
10229 Event::FundingGenerationReady { .. } => (),
10230 _ => panic!("Unexpected event"),
10233 // Asserts the outbound channel has been removed from a nodes[0]'s peer state map.
10234 let check_outbound_channel_existence = |should_exist: bool| {
10235 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
10236 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
10237 assert_eq!(chan_lock.channel_by_id.contains_key(&temp_channel_id), should_exist);
10240 // Channel should exist without any timer ticks.
10241 check_outbound_channel_existence(true);
10243 // Channel should exist with 1 timer tick less than required.
10244 for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS - 1 {
10245 nodes[0].node.timer_tick_occurred();
10246 check_outbound_channel_existence(true)
10249 // Remove channel after reaching the required ticks.
10250 nodes[0].node.timer_tick_occurred();
10251 check_outbound_channel_existence(false);
10253 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
10254 assert_eq!(msg_events.len(), 1);
10255 match msg_events[0] {
10256 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
10257 assert_eq!(msg.data, "Force-closing pending channel due to timeout awaiting establishment handshake");
10259 _ => panic!("Unexpected event"),
10261 check_closed_event(&nodes[0], 1, ClosureReason::HolderForceClosed, false, &[nodes[1].node.get_our_node_id()], 100000);
10265 fn test_remove_expired_inbound_unfunded_channels() {
10266 let chanmon_cfgs = create_chanmon_cfgs(2);
10267 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10268 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10269 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10271 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10272 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10273 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10274 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10275 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10277 let events = nodes[0].node.get_and_clear_pending_events();
10278 assert_eq!(events.len(), 1);
10280 Event::FundingGenerationReady { .. } => (),
10281 _ => panic!("Unexpected event"),
10284 // Asserts the inbound channel has been removed from a nodes[1]'s peer state map.
10285 let check_inbound_channel_existence = |should_exist: bool| {
10286 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
10287 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
10288 assert_eq!(chan_lock.channel_by_id.contains_key(&temp_channel_id), should_exist);
10291 // Channel should exist without any timer ticks.
10292 check_inbound_channel_existence(true);
10294 // Channel should exist with 1 timer tick less than required.
10295 for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS - 1 {
10296 nodes[1].node.timer_tick_occurred();
10297 check_inbound_channel_existence(true)
10300 // Remove channel after reaching the required ticks.
10301 nodes[1].node.timer_tick_occurred();
10302 check_inbound_channel_existence(false);
10304 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
10305 assert_eq!(msg_events.len(), 1);
10306 match msg_events[0] {
10307 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
10308 assert_eq!(msg.data, "Force-closing pending channel due to timeout awaiting establishment handshake");
10310 _ => panic!("Unexpected event"),
10312 check_closed_event(&nodes[1], 1, ClosureReason::HolderForceClosed, false, &[nodes[0].node.get_our_node_id()], 100000);
10315 fn do_test_multi_post_event_actions(do_reload: bool) {
10316 // Tests handling multiple post-Event actions at once.
10317 // There is specific code in ChannelManager to handle channels where multiple post-Event
10318 // `ChannelMonitorUpdates` are pending at once. This test exercises that code.
10320 // Specifically, we test calling `get_and_clear_pending_events` while there are two
10321 // PaymentSents from different channels and one channel has two pending `ChannelMonitorUpdate`s
10322 // - one from an RAA and one from an inbound commitment_signed.
10323 let chanmon_cfgs = create_chanmon_cfgs(3);
10324 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10325 let (persister, chain_monitor);
10326 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10327 let nodes_0_deserialized;
10328 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10330 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
10331 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 0, 2).2;
10333 send_payment(&nodes[0], &[&nodes[1]], 1_000_000);
10334 send_payment(&nodes[0], &[&nodes[2]], 1_000_000);
10336 let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
10337 let (payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[2]], 1_000_000);
10339 nodes[1].node.claim_funds(our_payment_preimage);
10340 check_added_monitors!(nodes[1], 1);
10341 expect_payment_claimed!(nodes[1], our_payment_hash, 1_000_000);
10343 nodes[2].node.claim_funds(payment_preimage_2);
10344 check_added_monitors!(nodes[2], 1);
10345 expect_payment_claimed!(nodes[2], payment_hash_2, 1_000_000);
10347 for dest in &[1, 2] {
10348 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[*dest], nodes[0].node.get_our_node_id());
10349 nodes[0].node.handle_update_fulfill_htlc(&nodes[*dest].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
10350 commitment_signed_dance!(nodes[0], nodes[*dest], htlc_fulfill_updates.commitment_signed, false);
10351 check_added_monitors(&nodes[0], 0);
10354 let (route, payment_hash_3, _, payment_secret_3) =
10355 get_route_and_payment_hash!(nodes[1], nodes[0], 100_000);
10356 let payment_id = PaymentId(payment_hash_3.0);
10357 nodes[1].node.send_payment_with_route(&route, payment_hash_3,
10358 RecipientOnionFields::secret_only(payment_secret_3), payment_id).unwrap();
10359 check_added_monitors(&nodes[1], 1);
10361 let send_event = SendEvent::from_node(&nodes[1]);
10362 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event.msgs[0]);
10363 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_event.commitment_msg);
10364 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
10367 let nodes_0_serialized = nodes[0].node.encode();
10368 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
10369 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_2).encode();
10370 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);
10372 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10373 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10375 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
10376 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[2]));
10379 let events = nodes[0].node.get_and_clear_pending_events();
10380 assert_eq!(events.len(), 4);
10381 if let Event::PaymentSent { payment_preimage, .. } = events[0] {
10382 assert!(payment_preimage == our_payment_preimage || payment_preimage == payment_preimage_2);
10383 } else { panic!(); }
10384 if let Event::PaymentSent { payment_preimage, .. } = events[1] {
10385 assert!(payment_preimage == our_payment_preimage || payment_preimage == payment_preimage_2);
10386 } else { panic!(); }
10387 if let Event::PaymentPathSuccessful { .. } = events[2] {} else { panic!(); }
10388 if let Event::PaymentPathSuccessful { .. } = events[3] {} else { panic!(); }
10390 // After the events are processed, the ChannelMonitorUpdates will be released and, upon their
10391 // completion, we'll respond to nodes[1] with an RAA + CS.
10392 get_revoke_commit_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
10393 check_added_monitors(&nodes[0], 3);
10397 fn test_multi_post_event_actions() {
10398 do_test_multi_post_event_actions(true);
10399 do_test_multi_post_event_actions(false);
10403 fn test_batch_channel_open() {
10404 let chanmon_cfgs = create_chanmon_cfgs(3);
10405 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10406 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10407 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10409 // Initiate channel opening and create the batch channel funding transaction.
10410 let (tx, funding_created_msgs) = create_batch_channel_funding(&nodes[0], &[
10411 (&nodes[1], 100_000, 0, 42, None),
10412 (&nodes[2], 200_000, 0, 43, None),
10415 // Go through the funding_created and funding_signed flow with node 1.
10416 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[0]);
10417 check_added_monitors(&nodes[1], 1);
10418 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
10420 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10421 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
10422 check_added_monitors(&nodes[0], 1);
10424 // The transaction should not have been broadcast before all channels are ready.
10425 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
10427 // Go through the funding_created and funding_signed flow with node 2.
10428 nodes[2].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[1]);
10429 check_added_monitors(&nodes[2], 1);
10430 expect_channel_pending_event(&nodes[2], &nodes[0].node.get_our_node_id());
10432 let funding_signed_msg = get_event_msg!(nodes[2], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10433 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
10434 nodes[0].node.handle_funding_signed(&nodes[2].node.get_our_node_id(), &funding_signed_msg);
10435 check_added_monitors(&nodes[0], 1);
10437 // The transaction should not have been broadcast before persisting all monitors has been
10439 assert_eq!(nodes[0].tx_broadcaster.txn_broadcast().len(), 0);
10440 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
10442 // Complete the persistence of the monitor.
10443 nodes[0].chain_monitor.complete_sole_pending_chan_update(
10444 &OutPoint { txid: tx.txid(), index: 1 }.to_channel_id()
10446 let events = nodes[0].node.get_and_clear_pending_events();
10448 // The transaction should only have been broadcast now.
10449 let broadcasted_txs = nodes[0].tx_broadcaster.txn_broadcast();
10450 assert_eq!(broadcasted_txs.len(), 1);
10451 assert_eq!(broadcasted_txs[0], tx);
10453 assert_eq!(events.len(), 2);
10454 assert!(events.iter().any(|e| matches!(
10456 crate::events::Event::ChannelPending {
10457 ref counterparty_node_id,
10459 } if counterparty_node_id == &nodes[1].node.get_our_node_id(),
10461 assert!(events.iter().any(|e| matches!(
10463 crate::events::Event::ChannelPending {
10464 ref counterparty_node_id,
10466 } if counterparty_node_id == &nodes[2].node.get_our_node_id(),
10471 fn test_disconnect_in_funding_batch() {
10472 let chanmon_cfgs = create_chanmon_cfgs(3);
10473 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10474 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10475 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10477 // Initiate channel opening and create the batch channel funding transaction.
10478 let (tx, funding_created_msgs) = create_batch_channel_funding(&nodes[0], &[
10479 (&nodes[1], 100_000, 0, 42, None),
10480 (&nodes[2], 200_000, 0, 43, None),
10483 // Go through the funding_created and funding_signed flow with node 1.
10484 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[0]);
10485 check_added_monitors(&nodes[1], 1);
10486 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
10488 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10489 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
10490 check_added_monitors(&nodes[0], 1);
10492 // The transaction should not have been broadcast before all channels are ready.
10493 assert_eq!(nodes[0].tx_broadcaster.txn_broadcast().len(), 0);
10495 // The remaining peer in the batch disconnects.
10496 nodes[0].node.peer_disconnected(&nodes[2].node.get_our_node_id());
10498 // The channels in the batch will close immediately.
10499 let channel_id_1 = OutPoint { txid: tx.txid(), index: 0 }.to_channel_id();
10500 let channel_id_2 = OutPoint { txid: tx.txid(), index: 1 }.to_channel_id();
10501 let events = nodes[0].node.get_and_clear_pending_events();
10502 assert_eq!(events.len(), 4);
10503 assert!(events.iter().any(|e| matches!(
10505 Event::ChannelClosed {
10508 } if channel_id == &channel_id_1
10510 assert!(events.iter().any(|e| matches!(
10512 Event::ChannelClosed {
10515 } if channel_id == &channel_id_2
10517 assert_eq!(events.iter().filter(|e| matches!(
10519 Event::DiscardFunding { .. },
10522 // The monitor should become closed.
10523 check_added_monitors(&nodes[0], 1);
10525 let mut monitor_updates = nodes[0].chain_monitor.monitor_updates.lock().unwrap();
10526 let monitor_updates_1 = monitor_updates.get(&channel_id_1).unwrap();
10527 assert_eq!(monitor_updates_1.len(), 1);
10528 assert_eq!(monitor_updates_1[0].update_id, CLOSED_CHANNEL_UPDATE_ID);
10531 // The funding transaction should not have been broadcast, and therefore, we don't need
10532 // to broadcast a force-close transaction for the closed monitor.
10533 assert_eq!(nodes[0].tx_broadcaster.txn_broadcast().len(), 0);
10535 // Ensure the channels don't exist anymore.
10536 assert!(nodes[0].node.list_channels().is_empty());
10540 fn test_batch_funding_close_after_funding_signed() {
10541 let chanmon_cfgs = create_chanmon_cfgs(3);
10542 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10543 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10544 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10546 // Initiate channel opening and create the batch channel funding transaction.
10547 let (tx, funding_created_msgs) = create_batch_channel_funding(&nodes[0], &[
10548 (&nodes[1], 100_000, 0, 42, None),
10549 (&nodes[2], 200_000, 0, 43, None),
10552 // Go through the funding_created and funding_signed flow with node 1.
10553 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[0]);
10554 check_added_monitors(&nodes[1], 1);
10555 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
10557 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10558 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
10559 check_added_monitors(&nodes[0], 1);
10561 // Go through the funding_created and funding_signed flow with node 2.
10562 nodes[2].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[1]);
10563 check_added_monitors(&nodes[2], 1);
10564 expect_channel_pending_event(&nodes[2], &nodes[0].node.get_our_node_id());
10566 let funding_signed_msg = get_event_msg!(nodes[2], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10567 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
10568 nodes[0].node.handle_funding_signed(&nodes[2].node.get_our_node_id(), &funding_signed_msg);
10569 check_added_monitors(&nodes[0], 1);
10571 // The transaction should not have been broadcast before all channels are ready.
10572 assert_eq!(nodes[0].tx_broadcaster.txn_broadcast().len(), 0);
10574 // Force-close the channel for which we've completed the initial monitor.
10575 let channel_id_1 = OutPoint { txid: tx.txid(), index: 0 }.to_channel_id();
10576 let channel_id_2 = OutPoint { txid: tx.txid(), index: 1 }.to_channel_id();
10577 nodes[0].node.force_close_broadcasting_latest_txn(&channel_id_1, &nodes[1].node.get_our_node_id()).unwrap();
10578 check_added_monitors(&nodes[0], 2);
10580 let mut monitor_updates = nodes[0].chain_monitor.monitor_updates.lock().unwrap();
10581 let monitor_updates_1 = monitor_updates.get(&channel_id_1).unwrap();
10582 assert_eq!(monitor_updates_1.len(), 1);
10583 assert_eq!(monitor_updates_1[0].update_id, CLOSED_CHANNEL_UPDATE_ID);
10584 let monitor_updates_2 = monitor_updates.get(&channel_id_2).unwrap();
10585 assert_eq!(monitor_updates_2.len(), 1);
10586 assert_eq!(monitor_updates_2[0].update_id, CLOSED_CHANNEL_UPDATE_ID);
10588 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
10589 match msg_events[0] {
10590 MessageSendEvent::HandleError { .. } => (),
10591 _ => panic!("Unexpected message."),
10594 // We broadcast the commitment transaction as part of the force-close.
10596 let broadcasted_txs = nodes[0].tx_broadcaster.txn_broadcast();
10597 assert_eq!(broadcasted_txs.len(), 1);
10598 assert!(broadcasted_txs[0].txid() != tx.txid());
10599 assert_eq!(broadcasted_txs[0].input.len(), 1);
10600 assert_eq!(broadcasted_txs[0].input[0].previous_output.txid, tx.txid());
10603 // All channels in the batch should close immediately.
10604 let events = nodes[0].node.get_and_clear_pending_events();
10605 assert_eq!(events.len(), 4);
10606 assert!(events.iter().any(|e| matches!(
10608 Event::ChannelClosed {
10611 } if channel_id == &channel_id_1
10613 assert!(events.iter().any(|e| matches!(
10615 Event::ChannelClosed {
10618 } if channel_id == &channel_id_2
10620 assert_eq!(events.iter().filter(|e| matches!(
10622 Event::DiscardFunding { .. },
10625 // Ensure the channels don't exist anymore.
10626 assert!(nodes[0].node.list_channels().is_empty());
10629 fn do_test_funding_and_commitment_tx_confirm_same_block(confirm_remote_commitment: bool) {
10630 // Tests that a node will forget the channel (when it only requires 1 confirmation) if the
10631 // funding and commitment transaction confirm in the same block.
10632 let chanmon_cfgs = create_chanmon_cfgs(2);
10633 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10634 let mut min_depth_1_block_cfg = test_default_channel_config();
10635 min_depth_1_block_cfg.channel_handshake_config.minimum_depth = 1;
10636 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(min_depth_1_block_cfg), Some(min_depth_1_block_cfg)]);
10637 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10639 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
10640 let chan_id = chain::transaction::OutPoint { txid: funding_tx.txid(), index: 0 }.to_channel_id();
10642 assert_eq!(nodes[0].node.list_channels().len(), 1);
10643 assert_eq!(nodes[1].node.list_channels().len(), 1);
10645 let (closing_node, other_node) = if confirm_remote_commitment {
10646 (&nodes[1], &nodes[0])
10648 (&nodes[0], &nodes[1])
10651 closing_node.node.force_close_broadcasting_latest_txn(&chan_id, &other_node.node.get_our_node_id()).unwrap();
10652 let mut msg_events = closing_node.node.get_and_clear_pending_msg_events();
10653 assert_eq!(msg_events.len(), 1);
10654 match msg_events.pop().unwrap() {
10655 MessageSendEvent::HandleError { action: msgs::ErrorAction::SendErrorMessage { .. }, .. } => {},
10656 _ => panic!("Unexpected event"),
10658 check_added_monitors(closing_node, 1);
10659 check_closed_event(closing_node, 1, ClosureReason::HolderForceClosed, false, &[other_node.node.get_our_node_id()], 1_000_000);
10661 let commitment_tx = {
10662 let mut txn = closing_node.tx_broadcaster.txn_broadcast();
10663 assert_eq!(txn.len(), 1);
10664 let commitment_tx = txn.pop().unwrap();
10665 check_spends!(commitment_tx, funding_tx);
10669 mine_transactions(&nodes[0], &[&funding_tx, &commitment_tx]);
10670 mine_transactions(&nodes[1], &[&funding_tx, &commitment_tx]);
10672 check_closed_broadcast(other_node, 1, true);
10673 check_added_monitors(other_node, 1);
10674 check_closed_event(other_node, 1, ClosureReason::CommitmentTxConfirmed, false, &[closing_node.node.get_our_node_id()], 1_000_000);
10676 assert!(nodes[0].node.list_channels().is_empty());
10677 assert!(nodes[1].node.list_channels().is_empty());
10681 fn test_funding_and_commitment_tx_confirm_same_block() {
10682 do_test_funding_and_commitment_tx_confirm_same_block(false);
10683 do_test_funding_and_commitment_tx_confirm_same_block(true);