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::ChainHash;
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, 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, 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, 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, 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::DisconnectPeer { ref msg } } => {
1342 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1343 assert_eq!(msg.as_ref().unwrap().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, 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, 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.bolt11_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.bolt11_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::DisconnectPeer { .. }, 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::DisconnectPeer { .. }, 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::DisconnectPeer { .. }, 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::DisconnectPeer { msg: Some(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, 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::DisconnectPeer { .. }, 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.bolt11_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, 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, 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, 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, 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, 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 = ChainHash::using_genesis_block(Network::Testnet);
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, 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);
6208 fn test_payment_route_reaching_same_channel_twice() {
6209 //A route should not go through the same channel twice
6210 //It is enforced when constructing a route.
6211 let chanmon_cfgs = create_chanmon_cfgs(2);
6212 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6213 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6214 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6215 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6217 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6218 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
6219 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);
6221 // Extend the path by itself, essentially simulating route going through same channel twice
6222 let cloned_hops = route.paths[0].hops.clone();
6223 route.paths[0].hops.extend_from_slice(&cloned_hops);
6225 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6226 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6227 ), false, APIError::InvalidRoute { ref err },
6228 assert_eq!(err, &"Path went through the same channel twice"));
6231 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6232 // 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.
6233 //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.
6236 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6237 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6238 let chanmon_cfgs = create_chanmon_cfgs(2);
6239 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6240 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6241 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6242 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6244 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6245 route.paths[0].hops[0].fee_msat = 100;
6247 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6248 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6249 ), true, APIError::ChannelUnavailable { .. }, {});
6250 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6254 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6255 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6256 let chanmon_cfgs = create_chanmon_cfgs(2);
6257 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6258 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6259 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6260 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6262 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6263 route.paths[0].hops[0].fee_msat = 0;
6264 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6265 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)),
6266 true, APIError::ChannelUnavailable { ref err },
6267 assert_eq!(err, "Cannot send 0-msat HTLC"));
6269 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6270 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send 0-msat HTLC", 1);
6274 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6275 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6276 let chanmon_cfgs = create_chanmon_cfgs(2);
6277 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6278 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6279 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6280 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6282 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6283 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6284 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6285 check_added_monitors!(nodes[0], 1);
6286 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6287 updates.update_add_htlcs[0].amount_msat = 0;
6289 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6290 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6291 check_closed_broadcast!(nodes[1], true).unwrap();
6292 check_added_monitors!(nodes[1], 1);
6293 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() },
6294 [nodes[0].node.get_our_node_id()], 100000);
6298 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6299 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6300 //It is enforced when constructing a route.
6301 let chanmon_cfgs = create_chanmon_cfgs(2);
6302 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6303 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6304 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6305 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6307 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6308 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
6309 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);
6310 route.paths[0].hops.last_mut().unwrap().cltv_expiry_delta = 500000001;
6311 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6312 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6313 ), true, APIError::InvalidRoute { ref err },
6314 assert_eq!(err, &"Channel CLTV overflowed?"));
6318 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6319 //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.
6320 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6321 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6322 let chanmon_cfgs = create_chanmon_cfgs(2);
6323 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6324 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6325 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6326 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6327 let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6328 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context().counterparty_max_accepted_htlcs as u64;
6330 // Fetch a route in advance as we will be unable to once we're unable to send.
6331 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6332 for i in 0..max_accepted_htlcs {
6333 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6334 let payment_event = {
6335 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6336 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6337 check_added_monitors!(nodes[0], 1);
6339 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6340 assert_eq!(events.len(), 1);
6341 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6342 assert_eq!(htlcs[0].htlc_id, i);
6346 SendEvent::from_event(events.remove(0))
6348 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6349 check_added_monitors!(nodes[1], 0);
6350 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6352 expect_pending_htlcs_forwardable!(nodes[1]);
6353 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
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 { .. }, {});
6359 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6363 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6364 //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.
6365 let chanmon_cfgs = create_chanmon_cfgs(2);
6366 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6367 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6368 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6369 let channel_value = 100000;
6370 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6371 let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6373 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6375 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6376 // Manually create a route over our max in flight (which our router normally automatically
6378 route.paths[0].hops[0].fee_msat = max_in_flight + 1;
6379 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6380 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6381 ), true, APIError::ChannelUnavailable { .. }, {});
6382 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6384 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6387 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6389 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6390 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6391 let chanmon_cfgs = create_chanmon_cfgs(2);
6392 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6393 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6394 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6395 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6396 let htlc_minimum_msat: u64;
6398 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6399 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6400 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6401 htlc_minimum_msat = channel.context().get_holder_htlc_minimum_msat();
6404 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6405 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6406 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6407 check_added_monitors!(nodes[0], 1);
6408 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6409 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6410 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6411 assert!(nodes[1].node.list_channels().is_empty());
6412 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6413 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()));
6414 check_added_monitors!(nodes[1], 1);
6415 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6419 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6420 //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
6421 let chanmon_cfgs = create_chanmon_cfgs(2);
6422 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6423 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6424 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6425 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6427 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6428 let channel_reserve = chan_stat.channel_reserve_msat;
6429 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6430 let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
6431 // The 2* and +1 are for the fee spike reserve.
6432 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
6434 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6435 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6436 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6437 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6438 check_added_monitors!(nodes[0], 1);
6439 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6441 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6442 // at this time channel-initiatee receivers are not required to enforce that senders
6443 // respect the fee_spike_reserve.
6444 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6445 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6447 assert!(nodes[1].node.list_channels().is_empty());
6448 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6449 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6450 check_added_monitors!(nodes[1], 1);
6451 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6455 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6456 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6457 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6458 let chanmon_cfgs = create_chanmon_cfgs(2);
6459 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6460 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6461 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6462 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6464 let send_amt = 3999999;
6465 let (mut route, our_payment_hash, _, our_payment_secret) =
6466 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
6467 route.paths[0].hops[0].fee_msat = send_amt;
6468 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6469 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6470 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6471 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
6472 &route.paths[0], send_amt, RecipientOnionFields::secret_only(our_payment_secret), cur_height, &None).unwrap();
6473 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
6475 let mut msg = msgs::UpdateAddHTLC {
6479 payment_hash: our_payment_hash,
6480 cltv_expiry: htlc_cltv,
6481 onion_routing_packet: onion_packet.clone(),
6482 skimmed_fee_msat: None,
6486 msg.htlc_id = i as u64;
6487 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6489 msg.htlc_id = (50) as u64;
6490 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
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(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").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()], 100000);
6500 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6501 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: 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);
6506 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
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].amount_msat = get_channel_value_stat!(nodes[1], nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
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!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
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()], 1000000);
6524 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6525 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6526 let chanmon_cfgs = create_chanmon_cfgs(2);
6527 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6528 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6529 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6531 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6532 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6533 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6534 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6535 check_added_monitors!(nodes[0], 1);
6536 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6537 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6538 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6540 assert!(nodes[1].node.list_channels().is_empty());
6541 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6542 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6543 check_added_monitors!(nodes[1], 1);
6544 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6548 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6549 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6550 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6551 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6552 let chanmon_cfgs = create_chanmon_cfgs(2);
6553 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6554 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6555 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6557 create_announced_chan_between_nodes(&nodes, 0, 1);
6558 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6559 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6560 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6561 check_added_monitors!(nodes[0], 1);
6562 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6563 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6565 //Disconnect and Reconnect
6566 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
6567 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
6568 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
6569 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
6571 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6572 assert_eq!(reestablish_1.len(), 1);
6573 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
6574 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
6576 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6577 assert_eq!(reestablish_2.len(), 1);
6578 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6579 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6580 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6581 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6584 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6585 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6586 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6587 check_added_monitors!(nodes[1], 1);
6588 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].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 assert!(nodes[1].node.list_channels().is_empty());
6593 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6594 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6595 check_added_monitors!(nodes[1], 1);
6596 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6600 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6601 //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.
6603 let chanmon_cfgs = create_chanmon_cfgs(2);
6604 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6605 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6606 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6607 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6608 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6609 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6610 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6612 check_added_monitors!(nodes[0], 1);
6613 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6614 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6616 let update_msg = msgs::UpdateFulfillHTLC{
6619 payment_preimage: our_payment_preimage,
6622 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6624 assert!(nodes[0].node.list_channels().is_empty());
6625 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6626 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()));
6627 check_added_monitors!(nodes[0], 1);
6628 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6632 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6633 //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.
6635 let chanmon_cfgs = create_chanmon_cfgs(2);
6636 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6637 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6638 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6639 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6641 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6642 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6643 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6644 check_added_monitors!(nodes[0], 1);
6645 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6646 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6648 let update_msg = msgs::UpdateFailHTLC{
6651 reason: msgs::OnionErrorPacket { data: Vec::new()},
6654 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6656 assert!(nodes[0].node.list_channels().is_empty());
6657 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6658 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()));
6659 check_added_monitors!(nodes[0], 1);
6660 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6664 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6665 //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.
6667 let chanmon_cfgs = create_chanmon_cfgs(2);
6668 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6669 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6670 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6671 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6673 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6674 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6675 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6676 check_added_monitors!(nodes[0], 1);
6677 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6678 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6679 let update_msg = msgs::UpdateFailMalformedHTLC{
6682 sha256_of_onion: [1; 32],
6683 failure_code: 0x8000,
6686 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6688 assert!(nodes[0].node.list_channels().is_empty());
6689 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6690 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()));
6691 check_added_monitors!(nodes[0], 1);
6692 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6696 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6697 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6699 let chanmon_cfgs = create_chanmon_cfgs(2);
6700 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6701 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6702 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6703 create_announced_chan_between_nodes(&nodes, 0, 1);
6705 let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6707 nodes[1].node.claim_funds(our_payment_preimage);
6708 check_added_monitors!(nodes[1], 1);
6709 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6711 let events = nodes[1].node.get_and_clear_pending_msg_events();
6712 assert_eq!(events.len(), 1);
6713 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6715 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, .. } } => {
6716 assert!(update_add_htlcs.is_empty());
6717 assert_eq!(update_fulfill_htlcs.len(), 1);
6718 assert!(update_fail_htlcs.is_empty());
6719 assert!(update_fail_malformed_htlcs.is_empty());
6720 assert!(update_fee.is_none());
6721 update_fulfill_htlcs[0].clone()
6723 _ => panic!("Unexpected event"),
6727 update_fulfill_msg.htlc_id = 1;
6729 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6731 assert!(nodes[0].node.list_channels().is_empty());
6732 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6733 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6734 check_added_monitors!(nodes[0], 1);
6735 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6739 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6740 //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.
6742 let chanmon_cfgs = create_chanmon_cfgs(2);
6743 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6744 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6745 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6746 create_announced_chan_between_nodes(&nodes, 0, 1);
6748 let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6750 nodes[1].node.claim_funds(our_payment_preimage);
6751 check_added_monitors!(nodes[1], 1);
6752 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6754 let events = nodes[1].node.get_and_clear_pending_msg_events();
6755 assert_eq!(events.len(), 1);
6756 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6758 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, .. } } => {
6759 assert!(update_add_htlcs.is_empty());
6760 assert_eq!(update_fulfill_htlcs.len(), 1);
6761 assert!(update_fail_htlcs.is_empty());
6762 assert!(update_fail_malformed_htlcs.is_empty());
6763 assert!(update_fee.is_none());
6764 update_fulfill_htlcs[0].clone()
6766 _ => panic!("Unexpected event"),
6770 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6772 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6774 assert!(nodes[0].node.list_channels().is_empty());
6775 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6776 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6777 check_added_monitors!(nodes[0], 1);
6778 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6782 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6783 //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.
6785 let chanmon_cfgs = create_chanmon_cfgs(2);
6786 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6787 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6788 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6789 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6791 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6792 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6793 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6794 check_added_monitors!(nodes[0], 1);
6796 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6797 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6799 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6800 check_added_monitors!(nodes[1], 0);
6801 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6803 let events = nodes[1].node.get_and_clear_pending_msg_events();
6805 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6807 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, .. } } => {
6808 assert!(update_add_htlcs.is_empty());
6809 assert!(update_fulfill_htlcs.is_empty());
6810 assert!(update_fail_htlcs.is_empty());
6811 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6812 assert!(update_fee.is_none());
6813 update_fail_malformed_htlcs[0].clone()
6815 _ => panic!("Unexpected event"),
6818 update_msg.failure_code &= !0x8000;
6819 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6821 assert!(nodes[0].node.list_channels().is_empty());
6822 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6823 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6824 check_added_monitors!(nodes[0], 1);
6825 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 1000000);
6829 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6830 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6831 // * 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.
6833 let chanmon_cfgs = create_chanmon_cfgs(3);
6834 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6835 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6836 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6837 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6838 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000);
6840 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6843 let mut payment_event = {
6844 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6845 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6846 check_added_monitors!(nodes[0], 1);
6847 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6848 assert_eq!(events.len(), 1);
6849 SendEvent::from_event(events.remove(0))
6851 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6852 check_added_monitors!(nodes[1], 0);
6853 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6854 expect_pending_htlcs_forwardable!(nodes[1]);
6855 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6856 assert_eq!(events_2.len(), 1);
6857 check_added_monitors!(nodes[1], 1);
6858 payment_event = SendEvent::from_event(events_2.remove(0));
6859 assert_eq!(payment_event.msgs.len(), 1);
6862 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6863 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6864 check_added_monitors!(nodes[2], 0);
6865 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6867 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6868 assert_eq!(events_3.len(), 1);
6869 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6871 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 } } => {
6872 assert!(update_add_htlcs.is_empty());
6873 assert!(update_fulfill_htlcs.is_empty());
6874 assert!(update_fail_htlcs.is_empty());
6875 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6876 assert!(update_fee.is_none());
6877 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6879 _ => panic!("Unexpected event"),
6883 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6885 check_added_monitors!(nodes[1], 0);
6886 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6887 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 }]);
6888 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6889 assert_eq!(events_4.len(), 1);
6891 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6893 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, .. } } => {
6894 assert!(update_add_htlcs.is_empty());
6895 assert!(update_fulfill_htlcs.is_empty());
6896 assert_eq!(update_fail_htlcs.len(), 1);
6897 assert!(update_fail_malformed_htlcs.is_empty());
6898 assert!(update_fee.is_none());
6900 _ => panic!("Unexpected event"),
6903 check_added_monitors!(nodes[1], 1);
6907 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6908 let chanmon_cfgs = create_chanmon_cfgs(3);
6909 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6910 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6911 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6912 create_announced_chan_between_nodes(&nodes, 0, 1);
6913 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6915 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6918 let mut payment_event = {
6919 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6920 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6921 check_added_monitors!(nodes[0], 1);
6922 SendEvent::from_node(&nodes[0])
6925 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6926 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6927 expect_pending_htlcs_forwardable!(nodes[1]);
6928 check_added_monitors!(nodes[1], 1);
6929 payment_event = SendEvent::from_node(&nodes[1]);
6930 assert_eq!(payment_event.msgs.len(), 1);
6933 payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6934 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6935 check_added_monitors!(nodes[2], 0);
6936 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6938 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6939 assert_eq!(events_3.len(), 1);
6941 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6942 let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6943 // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6944 update_msg.failure_code |= 0x2000;
6946 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6947 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6949 _ => panic!("Unexpected event"),
6952 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6953 vec![HTLCDestination::NextHopChannel {
6954 node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6955 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6956 assert_eq!(events_4.len(), 1);
6957 check_added_monitors!(nodes[1], 1);
6960 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6961 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6962 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6964 _ => panic!("Unexpected event"),
6967 let events_5 = nodes[0].node.get_and_clear_pending_events();
6968 assert_eq!(events_5.len(), 2);
6970 // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6971 // the node originating the error to its next hop.
6973 Event::PaymentPathFailed { error_code, failure: PathFailure::OnPath { network_update: Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }) }, ..
6975 assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6976 assert!(is_permanent);
6977 assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
6979 _ => panic!("Unexpected event"),
6982 Event::PaymentFailed { payment_hash, .. } => {
6983 assert_eq!(payment_hash, our_payment_hash);
6985 _ => panic!("Unexpected event"),
6988 // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
6991 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6992 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6993 // 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
6994 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6996 let mut chanmon_cfgs = create_chanmon_cfgs(2);
6997 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6998 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6999 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7000 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7001 let chan =create_announced_chan_between_nodes(&nodes, 0, 1);
7003 let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
7004 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context().holder_dust_limit_satoshis;
7006 // We route 2 dust-HTLCs between A and B
7007 let (_, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7008 let (_, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7009 route_payment(&nodes[0], &[&nodes[1]], 1000000);
7011 // Cache one local commitment tx as previous
7012 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7014 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7015 nodes[1].node.fail_htlc_backwards(&payment_hash_2);
7016 check_added_monitors!(nodes[1], 0);
7017 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7018 check_added_monitors!(nodes[1], 1);
7020 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7021 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7022 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7023 check_added_monitors!(nodes[0], 1);
7025 // Cache one local commitment tx as lastest
7026 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7028 let events = nodes[0].node.get_and_clear_pending_msg_events();
7030 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7031 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7033 _ => panic!("Unexpected event"),
7036 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7037 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7039 _ => panic!("Unexpected event"),
7042 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7043 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7044 if announce_latest {
7045 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7047 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7050 check_closed_broadcast!(nodes[0], true);
7051 check_added_monitors!(nodes[0], 1);
7052 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7054 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7055 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7056 let events = nodes[0].node.get_and_clear_pending_events();
7057 // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7058 assert_eq!(events.len(), 4);
7059 let mut first_failed = false;
7060 for event in events {
7062 Event::PaymentPathFailed { payment_hash, .. } => {
7063 if payment_hash == payment_hash_1 {
7064 assert!(!first_failed);
7065 first_failed = true;
7067 assert_eq!(payment_hash, payment_hash_2);
7070 Event::PaymentFailed { .. } => {}
7071 _ => panic!("Unexpected event"),
7077 fn test_failure_delay_dust_htlc_local_commitment() {
7078 do_test_failure_delay_dust_htlc_local_commitment(true);
7079 do_test_failure_delay_dust_htlc_local_commitment(false);
7082 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7083 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7084 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7085 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7086 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7087 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7088 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7090 let chanmon_cfgs = create_chanmon_cfgs(3);
7091 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7092 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7093 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7094 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
7096 let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
7097 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context().holder_dust_limit_satoshis;
7099 let (_payment_preimage_1, dust_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7100 let (_payment_preimage_2, non_dust_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7102 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7103 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7105 // We revoked bs_commitment_tx
7107 let (payment_preimage_3, ..) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7108 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7111 let mut timeout_tx = Vec::new();
7113 // We fail dust-HTLC 1 by broadcast of local commitment tx
7114 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7115 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7116 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7117 expect_payment_failed!(nodes[0], dust_hash, false);
7119 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7120 check_closed_broadcast!(nodes[0], true);
7121 check_added_monitors!(nodes[0], 1);
7122 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7123 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7124 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7125 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7126 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7127 mine_transaction(&nodes[0], &timeout_tx[0]);
7128 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7129 expect_payment_failed!(nodes[0], non_dust_hash, false);
7131 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7132 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7133 check_closed_broadcast!(nodes[0], true);
7134 check_added_monitors!(nodes[0], 1);
7135 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7136 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7138 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7139 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
7140 .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
7141 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
7142 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
7143 // dust HTLC should have been failed.
7144 expect_payment_failed!(nodes[0], dust_hash, false);
7147 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7149 assert_eq!(timeout_tx[0].lock_time.0, 11);
7151 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
7152 mine_transaction(&nodes[0], &timeout_tx[0]);
7153 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7154 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7155 expect_payment_failed!(nodes[0], non_dust_hash, false);
7160 fn test_sweep_outbound_htlc_failure_update() {
7161 do_test_sweep_outbound_htlc_failure_update(false, true);
7162 do_test_sweep_outbound_htlc_failure_update(false, false);
7163 do_test_sweep_outbound_htlc_failure_update(true, false);
7167 fn test_user_configurable_csv_delay() {
7168 // We test our channel constructors yield errors when we pass them absurd csv delay
7170 let mut low_our_to_self_config = UserConfig::default();
7171 low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
7172 let mut high_their_to_self_config = UserConfig::default();
7173 high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
7174 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7175 let chanmon_cfgs = create_chanmon_cfgs(2);
7176 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7177 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7178 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7180 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in OutboundV1Channel::new()
7181 if let Err(error) = OutboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7182 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[1].node.init_features(), 1000000, 1000000, 0,
7183 &low_our_to_self_config, 0, 42, None)
7186 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())); },
7187 _ => panic!("Unexpected event"),
7189 } else { assert!(false) }
7191 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in InboundV1Channel::new()
7192 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None, None).unwrap();
7193 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7194 open_channel.to_self_delay = 200;
7195 if let Err(error) = InboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7196 &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,
7197 &low_our_to_self_config, 0, &nodes[0].logger, /*is_0conf=*/false)
7200 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())); },
7201 _ => panic!("Unexpected event"),
7203 } else { assert!(false); }
7205 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7206 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None, None).unwrap();
7207 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()));
7208 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7209 accept_channel.to_self_delay = 200;
7210 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
7212 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7214 &ErrorAction::SendErrorMessage { ref msg } => {
7215 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()));
7216 reason_msg = msg.data.clone();
7220 } else { panic!(); }
7221 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg }, [nodes[1].node.get_our_node_id()], 1000000);
7223 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in InboundV1Channel::new()
7224 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None, None).unwrap();
7225 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7226 open_channel.to_self_delay = 200;
7227 if let Err(error) = InboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7228 &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,
7229 &high_their_to_self_config, 0, &nodes[0].logger, /*is_0conf=*/false)
7232 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())); },
7233 _ => panic!("Unexpected event"),
7235 } else { assert!(false); }
7239 fn test_check_htlc_underpaying() {
7240 // Send payment through A -> B but A is maliciously
7241 // sending a probe payment (i.e less than expected value0
7242 // to B, B should refuse payment.
7244 let chanmon_cfgs = create_chanmon_cfgs(2);
7245 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7246 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7247 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7249 // Create some initial channels
7250 create_announced_chan_between_nodes(&nodes, 0, 1);
7252 let scorer = test_utils::TestScorer::new();
7253 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7254 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
7255 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
7256 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 10_000);
7257 let route = get_route(&nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph.read_only(),
7258 None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes).unwrap();
7259 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7260 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, None).unwrap();
7261 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
7262 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
7263 check_added_monitors!(nodes[0], 1);
7265 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7266 assert_eq!(events.len(), 1);
7267 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7268 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7269 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7271 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7272 // and then will wait a second random delay before failing the HTLC back:
7273 expect_pending_htlcs_forwardable!(nodes[1]);
7274 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7276 // Node 3 is expecting payment of 100_000 but received 10_000,
7277 // it should fail htlc like we didn't know the preimage.
7278 nodes[1].node.process_pending_htlc_forwards();
7280 let events = nodes[1].node.get_and_clear_pending_msg_events();
7281 assert_eq!(events.len(), 1);
7282 let (update_fail_htlc, commitment_signed) = match events[0] {
7283 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 } } => {
7284 assert!(update_add_htlcs.is_empty());
7285 assert!(update_fulfill_htlcs.is_empty());
7286 assert_eq!(update_fail_htlcs.len(), 1);
7287 assert!(update_fail_malformed_htlcs.is_empty());
7288 assert!(update_fee.is_none());
7289 (update_fail_htlcs[0].clone(), commitment_signed)
7291 _ => panic!("Unexpected event"),
7293 check_added_monitors!(nodes[1], 1);
7295 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7296 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7298 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7299 let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
7300 expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
7301 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7305 fn test_announce_disable_channels() {
7306 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7307 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7309 let chanmon_cfgs = create_chanmon_cfgs(2);
7310 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7311 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7312 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7314 create_announced_chan_between_nodes(&nodes, 0, 1);
7315 create_announced_chan_between_nodes(&nodes, 1, 0);
7316 create_announced_chan_between_nodes(&nodes, 0, 1);
7319 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
7320 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
7322 for _ in 0..DISABLE_GOSSIP_TICKS + 1 {
7323 nodes[0].node.timer_tick_occurred();
7325 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7326 assert_eq!(msg_events.len(), 3);
7327 let mut chans_disabled = HashMap::new();
7328 for e in msg_events {
7330 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7331 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7332 // Check that each channel gets updated exactly once
7333 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7334 panic!("Generated ChannelUpdate for wrong chan!");
7337 _ => panic!("Unexpected event"),
7341 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
7342 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
7344 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7345 assert_eq!(reestablish_1.len(), 3);
7346 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
7347 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
7349 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7350 assert_eq!(reestablish_2.len(), 3);
7352 // Reestablish chan_1
7353 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7354 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7355 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7356 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7357 // Reestablish chan_2
7358 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7359 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7360 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7361 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7362 // Reestablish chan_3
7363 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7364 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7365 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7366 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7368 for _ in 0..ENABLE_GOSSIP_TICKS {
7369 nodes[0].node.timer_tick_occurred();
7371 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7372 nodes[0].node.timer_tick_occurred();
7373 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7374 assert_eq!(msg_events.len(), 3);
7375 for e in msg_events {
7377 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7378 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7379 match chans_disabled.remove(&msg.contents.short_channel_id) {
7380 // Each update should have a higher timestamp than the previous one, replacing
7382 Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7383 None => panic!("Generated ChannelUpdate for wrong chan!"),
7386 _ => panic!("Unexpected event"),
7389 // Check that each channel gets updated exactly once
7390 assert!(chans_disabled.is_empty());
7394 fn test_bump_penalty_txn_on_revoked_commitment() {
7395 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7396 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7398 let chanmon_cfgs = create_chanmon_cfgs(2);
7399 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7400 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7401 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7403 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7405 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7406 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7407 .with_bolt11_features(nodes[0].node.bolt11_invoice_features()).unwrap();
7408 let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000);
7409 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7411 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7412 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7413 assert_eq!(revoked_txn[0].output.len(), 4);
7414 assert_eq!(revoked_txn[0].input.len(), 1);
7415 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7416 let revoked_txid = revoked_txn[0].txid();
7418 let mut penalty_sum = 0;
7419 for outp in revoked_txn[0].output.iter() {
7420 if outp.script_pubkey.is_v0_p2wsh() {
7421 penalty_sum += outp.value;
7425 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7426 let header_114 = connect_blocks(&nodes[1], 14);
7428 // Actually revoke tx by claiming a HTLC
7429 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7430 connect_block(&nodes[1], &create_dummy_block(header_114, 42, vec![revoked_txn[0].clone()]));
7431 check_added_monitors!(nodes[1], 1);
7433 // One or more justice tx should have been broadcast, check it
7437 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7438 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7439 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7440 assert_eq!(node_txn[0].output.len(), 1);
7441 check_spends!(node_txn[0], revoked_txn[0]);
7442 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7443 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7444 penalty_1 = node_txn[0].txid();
7448 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7449 connect_blocks(&nodes[1], 15);
7450 let mut penalty_2 = penalty_1;
7451 let mut feerate_2 = 0;
7453 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7454 assert_eq!(node_txn.len(), 1);
7455 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7456 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7457 assert_eq!(node_txn[0].output.len(), 1);
7458 check_spends!(node_txn[0], revoked_txn[0]);
7459 penalty_2 = node_txn[0].txid();
7460 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7461 assert_ne!(penalty_2, penalty_1);
7462 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7463 feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7464 // Verify 25% bump heuristic
7465 assert!(feerate_2 * 100 >= feerate_1 * 125);
7469 assert_ne!(feerate_2, 0);
7471 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7472 connect_blocks(&nodes[1], 1);
7474 let mut feerate_3 = 0;
7476 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7477 assert_eq!(node_txn.len(), 1);
7478 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7479 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7480 assert_eq!(node_txn[0].output.len(), 1);
7481 check_spends!(node_txn[0], revoked_txn[0]);
7482 penalty_3 = node_txn[0].txid();
7483 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7484 assert_ne!(penalty_3, penalty_2);
7485 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7486 feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7487 // Verify 25% bump heuristic
7488 assert!(feerate_3 * 100 >= feerate_2 * 125);
7492 assert_ne!(feerate_3, 0);
7494 nodes[1].node.get_and_clear_pending_events();
7495 nodes[1].node.get_and_clear_pending_msg_events();
7499 fn test_bump_penalty_txn_on_revoked_htlcs() {
7500 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7501 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7503 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7504 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7505 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7506 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7507 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7509 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7510 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7511 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 50).with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
7512 let scorer = test_utils::TestScorer::new();
7513 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7514 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 3_000_000);
7515 let route = get_route(&nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph.read_only(), None,
7516 nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes).unwrap();
7517 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7518 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50)
7519 .with_bolt11_features(nodes[0].node.bolt11_invoice_features()).unwrap();
7520 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 3_000_000);
7521 let route = get_route(&nodes[1].node.get_our_node_id(), &route_params, &nodes[1].network_graph.read_only(), None,
7522 nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes).unwrap();
7523 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7525 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7526 assert_eq!(revoked_local_txn[0].input.len(), 1);
7527 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7529 // Revoke local commitment tx
7530 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7532 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7533 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone()]));
7534 check_closed_broadcast!(nodes[1], true);
7535 check_added_monitors!(nodes[1], 1);
7536 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 1000000);
7537 connect_blocks(&nodes[1], 50); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7539 let revoked_htlc_txn = {
7540 let txn = nodes[1].tx_broadcaster.unique_txn_broadcast();
7541 assert_eq!(txn.len(), 2);
7543 assert_eq!(txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7544 assert_eq!(txn[0].input.len(), 1);
7545 check_spends!(txn[0], revoked_local_txn[0]);
7547 assert_eq!(txn[1].input.len(), 1);
7548 assert_eq!(txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7549 assert_eq!(txn[1].output.len(), 1);
7550 check_spends!(txn[1], revoked_local_txn[0]);
7555 // Broadcast set of revoked txn on A
7556 let hash_128 = connect_blocks(&nodes[0], 40);
7557 let block_11 = create_dummy_block(hash_128, 42, vec![revoked_local_txn[0].clone()]);
7558 connect_block(&nodes[0], &block_11);
7559 let block_129 = create_dummy_block(block_11.block_hash(), 42, vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()]);
7560 connect_block(&nodes[0], &block_129);
7561 let events = nodes[0].node.get_and_clear_pending_events();
7562 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7563 match events.last().unwrap() {
7564 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7565 _ => panic!("Unexpected event"),
7571 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7572 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7573 // Verify claim tx are spending revoked HTLC txn
7575 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7576 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7577 // which are included in the same block (they are broadcasted because we scan the
7578 // transactions linearly and generate claims as we go, they likely should be removed in the
7580 assert_eq!(node_txn[0].input.len(), 1);
7581 check_spends!(node_txn[0], revoked_local_txn[0]);
7582 assert_eq!(node_txn[1].input.len(), 1);
7583 check_spends!(node_txn[1], revoked_local_txn[0]);
7584 assert_eq!(node_txn[2].input.len(), 1);
7585 check_spends!(node_txn[2], revoked_local_txn[0]);
7587 // Each of the three justice transactions claim a separate (single) output of the three
7588 // available, which we check here:
7589 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7590 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7591 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7593 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7594 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7596 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7597 // output, checked above).
7598 assert_eq!(node_txn[3].input.len(), 2);
7599 assert_eq!(node_txn[3].output.len(), 1);
7600 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7602 first = node_txn[3].txid();
7603 // Store both feerates for later comparison
7604 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7605 feerate_1 = fee_1 * 1000 / node_txn[3].weight() as u64;
7606 penalty_txn = vec![node_txn[2].clone()];
7610 // Connect one more block to see if bumped penalty are issued for HTLC txn
7611 let block_130 = create_dummy_block(block_129.block_hash(), 42, penalty_txn);
7612 connect_block(&nodes[0], &block_130);
7613 let block_131 = create_dummy_block(block_130.block_hash(), 42, Vec::new());
7614 connect_block(&nodes[0], &block_131);
7616 // Few more blocks to confirm penalty txn
7617 connect_blocks(&nodes[0], 4);
7618 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7619 let header_144 = connect_blocks(&nodes[0], 9);
7621 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7622 assert_eq!(node_txn.len(), 1);
7624 assert_eq!(node_txn[0].input.len(), 2);
7625 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7626 // Verify bumped tx is different and 25% bump heuristic
7627 assert_ne!(first, node_txn[0].txid());
7628 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7629 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7630 assert!(feerate_2 * 100 > feerate_1 * 125);
7631 let txn = vec![node_txn[0].clone()];
7635 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7636 connect_block(&nodes[0], &create_dummy_block(header_144, 42, node_txn));
7637 connect_blocks(&nodes[0], 20);
7639 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7640 // We verify than no new transaction has been broadcast because previously
7641 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7642 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7643 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7644 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7645 // up bumped justice generation.
7646 assert_eq!(node_txn.len(), 0);
7649 check_closed_broadcast!(nodes[0], true);
7650 check_added_monitors!(nodes[0], 1);
7654 fn test_bump_penalty_txn_on_remote_commitment() {
7655 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7656 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7659 // Provide preimage for one
7660 // Check aggregation
7662 let chanmon_cfgs = create_chanmon_cfgs(2);
7663 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7664 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7665 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7667 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7668 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7669 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7671 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7672 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7673 assert_eq!(remote_txn[0].output.len(), 4);
7674 assert_eq!(remote_txn[0].input.len(), 1);
7675 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7677 // Claim a HTLC without revocation (provide B monitor with preimage)
7678 nodes[1].node.claim_funds(payment_preimage);
7679 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7680 mine_transaction(&nodes[1], &remote_txn[0]);
7681 check_added_monitors!(nodes[1], 2);
7682 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7684 // One or more claim tx should have been broadcast, check it
7688 let feerate_timeout;
7689 let feerate_preimage;
7691 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7692 // 3 transactions including:
7693 // preimage and timeout sweeps from remote commitment + preimage sweep bump
7694 assert_eq!(node_txn.len(), 3);
7695 assert_eq!(node_txn[0].input.len(), 1);
7696 assert_eq!(node_txn[1].input.len(), 1);
7697 assert_eq!(node_txn[2].input.len(), 1);
7698 check_spends!(node_txn[0], remote_txn[0]);
7699 check_spends!(node_txn[1], remote_txn[0]);
7700 check_spends!(node_txn[2], remote_txn[0]);
7702 preimage = node_txn[0].txid();
7703 let index = node_txn[0].input[0].previous_output.vout;
7704 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7705 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
7707 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7708 (node_txn[2].clone(), node_txn[1].clone())
7710 (node_txn[1].clone(), node_txn[2].clone())
7713 preimage_bump = preimage_bump_tx;
7714 check_spends!(preimage_bump, remote_txn[0]);
7715 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7717 timeout = timeout_tx.txid();
7718 let index = timeout_tx.input[0].previous_output.vout;
7719 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7720 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
7724 assert_ne!(feerate_timeout, 0);
7725 assert_ne!(feerate_preimage, 0);
7727 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7728 connect_blocks(&nodes[1], 1);
7730 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7731 assert_eq!(node_txn.len(), 1);
7732 assert_eq!(node_txn[0].input.len(), 1);
7733 assert_eq!(preimage_bump.input.len(), 1);
7734 check_spends!(node_txn[0], remote_txn[0]);
7735 check_spends!(preimage_bump, remote_txn[0]);
7737 let index = preimage_bump.input[0].previous_output.vout;
7738 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7739 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
7740 assert!(new_feerate * 100 > feerate_timeout * 125);
7741 assert_ne!(timeout, preimage_bump.txid());
7743 let index = node_txn[0].input[0].previous_output.vout;
7744 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7745 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
7746 assert!(new_feerate * 100 > feerate_preimage * 125);
7747 assert_ne!(preimage, node_txn[0].txid());
7752 nodes[1].node.get_and_clear_pending_events();
7753 nodes[1].node.get_and_clear_pending_msg_events();
7757 fn test_counterparty_raa_skip_no_crash() {
7758 // Previously, if our counterparty sent two RAAs in a row without us having provided a
7759 // commitment transaction, we would have happily carried on and provided them the next
7760 // commitment transaction based on one RAA forward. This would probably eventually have led to
7761 // channel closure, but it would not have resulted in funds loss. Still, our
7762 // TestChannelSigner would have panicked as it doesn't like jumps into the future. Here, we
7763 // check simply that the channel is closed in response to such an RAA, but don't check whether
7764 // we decide to punish our counterparty for revoking their funds (as we don't currently
7766 let chanmon_cfgs = create_chanmon_cfgs(2);
7767 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7768 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7769 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7770 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7772 let per_commitment_secret;
7773 let next_per_commitment_point;
7775 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7776 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7777 let keys = guard.channel_by_id.get_mut(&channel_id).map(
7778 |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
7779 ).flatten().unwrap().get_signer();
7781 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7783 // Make signer believe we got a counterparty signature, so that it allows the revocation
7784 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7785 per_commitment_secret = keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7787 // Must revoke without gaps
7788 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7789 keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7791 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7792 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7793 &SecretKey::from_slice(&keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7796 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7797 &msgs::RevokeAndACK {
7799 per_commitment_secret,
7800 next_per_commitment_point,
7802 next_local_nonce: None,
7804 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7805 check_added_monitors!(nodes[1], 1);
7806 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() }
7807 , [nodes[0].node.get_our_node_id()], 100000);
7811 fn test_bump_txn_sanitize_tracking_maps() {
7812 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7813 // verify we clean then right after expiration of ANTI_REORG_DELAY.
7815 let chanmon_cfgs = create_chanmon_cfgs(2);
7816 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7817 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7818 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7820 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7821 // Lock HTLC in both directions
7822 let (payment_preimage_1, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7823 let (_, payment_hash_2, ..) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7825 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7826 assert_eq!(revoked_local_txn[0].input.len(), 1);
7827 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7829 // Revoke local commitment tx
7830 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7832 // Broadcast set of revoked txn on A
7833 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7834 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7835 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7837 mine_transaction(&nodes[0], &revoked_local_txn[0]);
7838 check_closed_broadcast!(nodes[0], true);
7839 check_added_monitors!(nodes[0], 1);
7840 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 1000000);
7842 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7843 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7844 check_spends!(node_txn[0], revoked_local_txn[0]);
7845 check_spends!(node_txn[1], revoked_local_txn[0]);
7846 check_spends!(node_txn[2], revoked_local_txn[0]);
7847 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7851 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, penalty_txn));
7852 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7854 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7855 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7856 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7861 fn test_channel_conf_timeout() {
7862 // Tests that, for inbound channels, we give up on them if the funding transaction does not
7863 // confirm within 2016 blocks, as recommended by BOLT 2.
7864 let chanmon_cfgs = create_chanmon_cfgs(2);
7865 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7866 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7867 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7869 let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7871 // The outbound node should wait forever for confirmation:
7872 // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7873 // copied here instead of directly referencing the constant.
7874 connect_blocks(&nodes[0], 2016);
7875 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7877 // The inbound node should fail the channel after exactly 2016 blocks
7878 connect_blocks(&nodes[1], 2015);
7879 check_added_monitors!(nodes[1], 0);
7880 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7882 connect_blocks(&nodes[1], 1);
7883 check_added_monitors!(nodes[1], 1);
7884 check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut, [nodes[0].node.get_our_node_id()], 1000000);
7885 let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7886 assert_eq!(close_ev.len(), 1);
7888 MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { ref msg }, ref node_id } => {
7889 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7890 assert_eq!(msg.as_ref().unwrap().data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7892 _ => panic!("Unexpected event"),
7897 fn test_override_channel_config() {
7898 let chanmon_cfgs = create_chanmon_cfgs(2);
7899 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7900 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7901 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7903 // Node0 initiates a channel to node1 using the override config.
7904 let mut override_config = UserConfig::default();
7905 override_config.channel_handshake_config.our_to_self_delay = 200;
7907 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, None, Some(override_config)).unwrap();
7909 // Assert the channel created by node0 is using the override config.
7910 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7911 assert_eq!(res.channel_flags, 0);
7912 assert_eq!(res.to_self_delay, 200);
7916 fn test_override_0msat_htlc_minimum() {
7917 let mut zero_config = UserConfig::default();
7918 zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7919 let chanmon_cfgs = create_chanmon_cfgs(2);
7920 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7921 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7922 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7924 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, None, Some(zero_config)).unwrap();
7925 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7926 assert_eq!(res.htlc_minimum_msat, 1);
7928 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7929 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7930 assert_eq!(res.htlc_minimum_msat, 1);
7934 fn test_channel_update_has_correct_htlc_maximum_msat() {
7935 // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7936 // Bolt 7 specifies that if present `htlc_maximum_msat`:
7937 // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7938 // 90% of the `channel_value`.
7939 // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7941 let mut config_30_percent = UserConfig::default();
7942 config_30_percent.channel_handshake_config.announced_channel = true;
7943 config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7944 let mut config_50_percent = UserConfig::default();
7945 config_50_percent.channel_handshake_config.announced_channel = true;
7946 config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7947 let mut config_95_percent = UserConfig::default();
7948 config_95_percent.channel_handshake_config.announced_channel = true;
7949 config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7950 let mut config_100_percent = UserConfig::default();
7951 config_100_percent.channel_handshake_config.announced_channel = true;
7952 config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7954 let chanmon_cfgs = create_chanmon_cfgs(4);
7955 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7956 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)]);
7957 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7959 let channel_value_satoshis = 100000;
7960 let channel_value_msat = channel_value_satoshis * 1000;
7961 let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7962 let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7963 let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7965 let (node_0_chan_update, node_1_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
7966 let (node_2_chan_update, node_3_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
7968 // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7969 // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7970 assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7971 // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7972 // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7973 assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7975 // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7976 // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7978 assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7979 // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7980 // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7982 assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7986 fn test_manually_accept_inbound_channel_request() {
7987 let mut manually_accept_conf = UserConfig::default();
7988 manually_accept_conf.manually_accept_inbound_channels = true;
7989 let chanmon_cfgs = create_chanmon_cfgs(2);
7990 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7991 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7992 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7994 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, Some(manually_accept_conf)).unwrap();
7995 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7997 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7999 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8000 // accepting the inbound channel request.
8001 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8003 let events = nodes[1].node.get_and_clear_pending_events();
8005 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8006 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
8008 _ => panic!("Unexpected event"),
8011 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8012 assert_eq!(accept_msg_ev.len(), 1);
8014 match accept_msg_ev[0] {
8015 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8016 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8018 _ => panic!("Unexpected event"),
8021 nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8023 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8024 assert_eq!(close_msg_ev.len(), 1);
8026 let events = nodes[1].node.get_and_clear_pending_events();
8028 Event::ChannelClosed { user_channel_id, .. } => {
8029 assert_eq!(user_channel_id, 23);
8031 _ => panic!("Unexpected event"),
8036 fn test_manually_reject_inbound_channel_request() {
8037 let mut manually_accept_conf = UserConfig::default();
8038 manually_accept_conf.manually_accept_inbound_channels = true;
8039 let chanmon_cfgs = create_chanmon_cfgs(2);
8040 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8041 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8042 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8044 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, Some(manually_accept_conf)).unwrap();
8045 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8047 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
8049 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8050 // rejecting the inbound channel request.
8051 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8053 let events = nodes[1].node.get_and_clear_pending_events();
8055 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8056 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8058 _ => panic!("Unexpected event"),
8061 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8062 assert_eq!(close_msg_ev.len(), 1);
8064 match close_msg_ev[0] {
8065 MessageSendEvent::HandleError { ref node_id, .. } => {
8066 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8068 _ => panic!("Unexpected event"),
8071 // There should be no more events to process, as the channel was never opened.
8072 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
8076 fn test_can_not_accept_inbound_channel_twice() {
8077 let mut manually_accept_conf = UserConfig::default();
8078 manually_accept_conf.manually_accept_inbound_channels = true;
8079 let chanmon_cfgs = create_chanmon_cfgs(2);
8080 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8081 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8082 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8084 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, Some(manually_accept_conf)).unwrap();
8085 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8087 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
8089 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8090 // accepting the inbound channel request.
8091 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8093 let events = nodes[1].node.get_and_clear_pending_events();
8095 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8096 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
8097 let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
8099 Err(APIError::APIMisuseError { err }) => {
8100 assert_eq!(err, "No such channel awaiting to be accepted.");
8102 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8103 Err(e) => panic!("Unexpected Error {:?}", e),
8106 _ => panic!("Unexpected event"),
8109 // Ensure that the channel wasn't closed after attempting to accept it twice.
8110 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8111 assert_eq!(accept_msg_ev.len(), 1);
8113 match accept_msg_ev[0] {
8114 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8115 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8117 _ => panic!("Unexpected event"),
8122 fn test_can_not_accept_unknown_inbound_channel() {
8123 let chanmon_cfg = create_chanmon_cfgs(2);
8124 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8125 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8126 let nodes = create_network(2, &node_cfg, &node_chanmgr);
8128 let unknown_channel_id = ChannelId::new_zero();
8129 let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
8131 Err(APIError::APIMisuseError { err }) => {
8132 assert_eq!(err, "No such channel awaiting to be accepted.");
8134 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8135 Err(e) => panic!("Unexpected Error: {:?}", e),
8140 fn test_onion_value_mpp_set_calculation() {
8141 // Test that we use the onion value `amt_to_forward` when
8142 // calculating whether we've reached the `total_msat` of an MPP
8143 // by having a routing node forward more than `amt_to_forward`
8144 // and checking that the receiving node doesn't generate
8145 // a PaymentClaimable event too early
8147 let chanmon_cfgs = create_chanmon_cfgs(node_count);
8148 let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8149 let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8150 let mut nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8152 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8153 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8154 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8155 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8157 let total_msat = 100_000;
8158 let expected_paths: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
8159 let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], total_msat);
8160 let sample_path = route.paths.pop().unwrap();
8162 let mut path_1 = sample_path.clone();
8163 path_1.hops[0].pubkey = nodes[1].node.get_our_node_id();
8164 path_1.hops[0].short_channel_id = chan_1_id;
8165 path_1.hops[1].pubkey = nodes[3].node.get_our_node_id();
8166 path_1.hops[1].short_channel_id = chan_3_id;
8167 path_1.hops[1].fee_msat = 100_000;
8168 route.paths.push(path_1);
8170 let mut path_2 = sample_path.clone();
8171 path_2.hops[0].pubkey = nodes[2].node.get_our_node_id();
8172 path_2.hops[0].short_channel_id = chan_2_id;
8173 path_2.hops[1].pubkey = nodes[3].node.get_our_node_id();
8174 path_2.hops[1].short_channel_id = chan_4_id;
8175 path_2.hops[1].fee_msat = 1_000;
8176 route.paths.push(path_2);
8179 let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
8180 let onion_session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
8181 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8182 nodes[0].node.test_send_payment_internal(&route, our_payment_hash,
8183 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8184 check_added_monitors!(nodes[0], expected_paths.len());
8186 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8187 assert_eq!(events.len(), expected_paths.len());
8190 let ev = remove_first_msg_event_to_node(&expected_paths[0][0].node.get_our_node_id(), &mut events);
8191 let mut payment_event = SendEvent::from_event(ev);
8192 let mut prev_node = &nodes[0];
8194 for (idx, &node) in expected_paths[0].iter().enumerate() {
8195 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
8197 if idx == 0 { // routing node
8198 let session_priv = [3; 32];
8199 let height = nodes[0].best_block_info().1;
8200 let session_priv = SecretKey::from_slice(&session_priv).unwrap();
8201 let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
8202 let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], 100_000,
8203 RecipientOnionFields::secret_only(our_payment_secret), height + 1, &None).unwrap();
8204 // Edit amt_to_forward to simulate the sender having set
8205 // the final amount and the routing node taking less fee
8206 if let msgs::OutboundOnionPayload::Receive { ref mut amt_msat, .. } = onion_payloads[1] {
8209 let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
8210 payment_event.msgs[0].onion_routing_packet = new_onion_packet;
8213 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
8214 check_added_monitors!(node, 0);
8215 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
8216 expect_pending_htlcs_forwardable!(node);
8219 let mut events_2 = node.node.get_and_clear_pending_msg_events();
8220 assert_eq!(events_2.len(), 1);
8221 check_added_monitors!(node, 1);
8222 payment_event = SendEvent::from_event(events_2.remove(0));
8223 assert_eq!(payment_event.msgs.len(), 1);
8225 let events_2 = node.node.get_and_clear_pending_events();
8226 assert!(events_2.is_empty());
8233 let ev = remove_first_msg_event_to_node(&expected_paths[1][0].node.get_our_node_id(), &mut events);
8234 pass_along_path(&nodes[0], expected_paths[1], 101_000, our_payment_hash.clone(), Some(our_payment_secret), ev, true, None);
8236 claim_payment_along_route(&nodes[0], expected_paths, false, our_payment_preimage);
8239 fn do_test_overshoot_mpp(msat_amounts: &[u64], total_msat: u64) {
8241 let routing_node_count = msat_amounts.len();
8242 let node_count = routing_node_count + 2;
8244 let chanmon_cfgs = create_chanmon_cfgs(node_count);
8245 let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8246 let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8247 let nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8252 // Create channels for each amount
8253 let mut expected_paths = Vec::with_capacity(routing_node_count);
8254 let mut src_chan_ids = Vec::with_capacity(routing_node_count);
8255 let mut dst_chan_ids = Vec::with_capacity(routing_node_count);
8256 for i in 0..routing_node_count {
8257 let routing_node = 2 + i;
8258 let src_chan_id = create_announced_chan_between_nodes(&nodes, src_idx, routing_node).0.contents.short_channel_id;
8259 src_chan_ids.push(src_chan_id);
8260 let dst_chan_id = create_announced_chan_between_nodes(&nodes, routing_node, dst_idx).0.contents.short_channel_id;
8261 dst_chan_ids.push(dst_chan_id);
8262 let path = vec![&nodes[routing_node], &nodes[dst_idx]];
8263 expected_paths.push(path);
8265 let expected_paths: Vec<&[&Node]> = expected_paths.iter().map(|route| route.as_slice()).collect();
8267 // Create a route for each amount
8268 let example_amount = 100000;
8269 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);
8270 let sample_path = route.paths.pop().unwrap();
8271 for i in 0..routing_node_count {
8272 let routing_node = 2 + i;
8273 let mut path = sample_path.clone();
8274 path.hops[0].pubkey = nodes[routing_node].node.get_our_node_id();
8275 path.hops[0].short_channel_id = src_chan_ids[i];
8276 path.hops[1].pubkey = nodes[dst_idx].node.get_our_node_id();
8277 path.hops[1].short_channel_id = dst_chan_ids[i];
8278 path.hops[1].fee_msat = msat_amounts[i];
8279 route.paths.push(path);
8282 // Send payment with manually set total_msat
8283 let payment_id = PaymentId(nodes[src_idx].keys_manager.backing.get_secure_random_bytes());
8284 let onion_session_privs = nodes[src_idx].node.test_add_new_pending_payment(our_payment_hash,
8285 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8286 nodes[src_idx].node.test_send_payment_internal(&route, our_payment_hash,
8287 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8288 check_added_monitors!(nodes[src_idx], expected_paths.len());
8290 let mut events = nodes[src_idx].node.get_and_clear_pending_msg_events();
8291 assert_eq!(events.len(), expected_paths.len());
8292 let mut amount_received = 0;
8293 for (path_idx, expected_path) in expected_paths.iter().enumerate() {
8294 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
8296 let current_path_amount = msat_amounts[path_idx];
8297 amount_received += current_path_amount;
8298 let became_claimable_now = amount_received >= total_msat && amount_received - current_path_amount < total_msat;
8299 pass_along_path(&nodes[src_idx], expected_path, amount_received, our_payment_hash.clone(), Some(our_payment_secret), ev, became_claimable_now, None);
8302 claim_payment_along_route(&nodes[src_idx], &expected_paths, false, our_payment_preimage);
8306 fn test_overshoot_mpp() {
8307 do_test_overshoot_mpp(&[100_000, 101_000], 200_000);
8308 do_test_overshoot_mpp(&[100_000, 10_000, 100_000], 200_000);
8312 fn test_simple_mpp() {
8313 // Simple test of sending a multi-path payment.
8314 let chanmon_cfgs = create_chanmon_cfgs(4);
8315 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8316 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8317 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8319 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8320 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8321 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8322 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8324 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8325 let path = route.paths[0].clone();
8326 route.paths.push(path);
8327 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
8328 route.paths[0].hops[0].short_channel_id = chan_1_id;
8329 route.paths[0].hops[1].short_channel_id = chan_3_id;
8330 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
8331 route.paths[1].hops[0].short_channel_id = chan_2_id;
8332 route.paths[1].hops[1].short_channel_id = chan_4_id;
8333 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8334 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8338 fn test_preimage_storage() {
8339 // Simple test of payment preimage storage allowing no client-side storage to claim payments
8340 let chanmon_cfgs = create_chanmon_cfgs(2);
8341 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8342 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8343 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8345 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8348 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
8349 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8350 nodes[0].node.send_payment_with_route(&route, payment_hash,
8351 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8352 check_added_monitors!(nodes[0], 1);
8353 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8354 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8355 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8356 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8358 // Note that after leaving the above scope we have no knowledge of any arguments or return
8359 // values from previous calls.
8360 expect_pending_htlcs_forwardable!(nodes[1]);
8361 let events = nodes[1].node.get_and_clear_pending_events();
8362 assert_eq!(events.len(), 1);
8364 Event::PaymentClaimable { ref purpose, .. } => {
8366 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8367 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8369 _ => panic!("expected PaymentPurpose::InvoicePayment")
8372 _ => panic!("Unexpected event"),
8377 fn test_bad_secret_hash() {
8378 // Simple test of unregistered payment hash/invalid payment secret handling
8379 let chanmon_cfgs = create_chanmon_cfgs(2);
8380 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8381 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8382 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8384 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8386 let random_payment_hash = PaymentHash([42; 32]);
8387 let random_payment_secret = PaymentSecret([43; 32]);
8388 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8389 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8391 // All the below cases should end up being handled exactly identically, so we macro the
8392 // resulting events.
8393 macro_rules! handle_unknown_invalid_payment_data {
8394 ($payment_hash: expr) => {
8395 check_added_monitors!(nodes[0], 1);
8396 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8397 let payment_event = SendEvent::from_event(events.pop().unwrap());
8398 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8399 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8401 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8402 // again to process the pending backwards-failure of the HTLC
8403 expect_pending_htlcs_forwardable!(nodes[1]);
8404 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8405 check_added_monitors!(nodes[1], 1);
8407 // We should fail the payment back
8408 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8409 match events.pop().unwrap() {
8410 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8411 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8412 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8414 _ => panic!("Unexpected event"),
8419 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8420 // Error data is the HTLC value (100,000) and current block height
8421 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8423 // Send a payment with the right payment hash but the wrong payment secret
8424 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
8425 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8426 handle_unknown_invalid_payment_data!(our_payment_hash);
8427 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8429 // Send a payment with a random payment hash, but the right payment secret
8430 nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8431 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8432 handle_unknown_invalid_payment_data!(random_payment_hash);
8433 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8435 // Send a payment with a random payment hash and random payment secret
8436 nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8437 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8438 handle_unknown_invalid_payment_data!(random_payment_hash);
8439 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8443 fn test_update_err_monitor_lockdown() {
8444 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8445 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8446 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8449 // This scenario may happen in a watchtower setup, where watchtower process a block height
8450 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8451 // commitment at same time.
8453 let chanmon_cfgs = create_chanmon_cfgs(2);
8454 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8455 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8456 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8458 // Create some initial channel
8459 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8460 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8462 // Rebalance the network to generate htlc in the two directions
8463 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8465 // Route a HTLC from node 0 to node 1 (but don't settle)
8466 let (preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8468 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8469 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8470 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8471 let persister = test_utils::TestPersister::new();
8474 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8475 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8476 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8477 assert!(new_monitor == *monitor);
8480 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);
8481 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), Ok(ChannelMonitorUpdateStatus::Completed));
8484 let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8485 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8486 // transaction lock time requirements here.
8487 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 200));
8488 watchtower.chain_monitor.block_connected(&block, 200);
8490 // Try to update ChannelMonitor
8491 nodes[1].node.claim_funds(preimage);
8492 check_added_monitors!(nodes[1], 1);
8493 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8495 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8496 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8497 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8499 let mut node_0_per_peer_lock;
8500 let mut node_0_peer_state_lock;
8501 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) {
8502 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8503 assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::InProgress);
8504 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8505 } else { assert!(false); }
8510 // Our local monitor is in-sync and hasn't processed yet timeout
8511 check_added_monitors!(nodes[0], 1);
8512 let events = nodes[0].node.get_and_clear_pending_events();
8513 assert_eq!(events.len(), 1);
8517 fn test_concurrent_monitor_claim() {
8518 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8519 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8520 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8521 // state N+1 confirms. Alice claims output from state N+1.
8523 let chanmon_cfgs = create_chanmon_cfgs(2);
8524 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8525 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8526 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8528 // Create some initial channel
8529 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8530 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8532 // Rebalance the network to generate htlc in the two directions
8533 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8535 // Route a HTLC from node 0 to node 1 (but don't settle)
8536 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8538 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8539 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8540 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8541 let persister = test_utils::TestPersister::new();
8542 let alice_broadcaster = test_utils::TestBroadcaster::with_blocks(
8543 Arc::new(Mutex::new(nodes[0].blocks.lock().unwrap().clone())),
8545 let watchtower_alice = {
8547 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8548 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8549 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8550 assert!(new_monitor == *monitor);
8553 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &alice_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8554 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), Ok(ChannelMonitorUpdateStatus::Completed));
8557 let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8558 // Make Alice aware of enough blocks that it doesn't think we're violating transaction lock time
8559 // requirements here.
8560 const HTLC_TIMEOUT_BROADCAST: u32 = CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS;
8561 alice_broadcaster.blocks.lock().unwrap().resize((HTLC_TIMEOUT_BROADCAST) as usize, (block.clone(), HTLC_TIMEOUT_BROADCAST));
8562 watchtower_alice.chain_monitor.block_connected(&block, HTLC_TIMEOUT_BROADCAST);
8564 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8566 let mut txn = alice_broadcaster.txn_broadcast();
8567 assert_eq!(txn.len(), 2);
8571 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8572 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8573 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8574 let persister = test_utils::TestPersister::new();
8575 let bob_broadcaster = test_utils::TestBroadcaster::with_blocks(Arc::clone(&alice_broadcaster.blocks));
8576 let watchtower_bob = {
8578 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8579 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8580 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8581 assert!(new_monitor == *monitor);
8584 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &bob_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8585 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), Ok(ChannelMonitorUpdateStatus::Completed));
8588 watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST - 1);
8590 // Route another payment to generate another update with still previous HTLC pending
8591 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8592 nodes[1].node.send_payment_with_route(&route, payment_hash,
8593 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8594 check_added_monitors!(nodes[1], 1);
8596 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8597 assert_eq!(updates.update_add_htlcs.len(), 1);
8598 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8600 let mut node_0_per_peer_lock;
8601 let mut node_0_peer_state_lock;
8602 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) {
8603 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8604 // Watchtower Alice should already have seen the block and reject the update
8605 assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::InProgress);
8606 assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8607 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8608 } else { assert!(false); }
8613 // Our local monitor is in-sync and hasn't processed yet timeout
8614 check_added_monitors!(nodes[0], 1);
8616 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8617 watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST);
8619 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8622 let mut txn = bob_broadcaster.txn_broadcast();
8623 assert_eq!(txn.len(), 2);
8624 bob_state_y = txn.remove(0);
8627 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8628 let height = HTLC_TIMEOUT_BROADCAST + 1;
8629 connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
8630 check_closed_broadcast(&nodes[0], 1, true);
8631 check_closed_event!(&nodes[0], 1, ClosureReason::HolderForceClosed, false,
8632 [nodes[1].node.get_our_node_id()], 100000);
8633 watchtower_alice.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, vec![bob_state_y.clone()]), height);
8634 check_added_monitors(&nodes[0], 1);
8636 let htlc_txn = alice_broadcaster.txn_broadcast();
8637 assert_eq!(htlc_txn.len(), 2);
8638 check_spends!(htlc_txn[0], bob_state_y);
8639 // Alice doesn't clean up the old HTLC claim since it hasn't seen a conflicting spend for
8640 // it. However, she should, because it now has an invalid parent.
8641 check_spends!(htlc_txn[1], alice_state);
8646 fn test_pre_lockin_no_chan_closed_update() {
8647 // Test that if a peer closes a channel in response to a funding_created message we don't
8648 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8651 // Doing so would imply a channel monitor update before the initial channel monitor
8652 // registration, violating our API guarantees.
8654 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8655 // then opening a second channel with the same funding output as the first (which is not
8656 // rejected because the first channel does not exist in the ChannelManager) and closing it
8657 // before receiving funding_signed.
8658 let chanmon_cfgs = create_chanmon_cfgs(2);
8659 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8660 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8661 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8663 // Create an initial channel
8664 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
8665 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8666 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8667 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8668 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8670 // Move the first channel through the funding flow...
8671 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8673 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8674 check_added_monitors!(nodes[0], 0);
8676 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8677 let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8678 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8679 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8680 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("Hi".to_string()) }, true,
8681 [nodes[1].node.get_our_node_id()], 100000);
8685 fn test_htlc_no_detection() {
8686 // This test is a mutation to underscore the detection logic bug we had
8687 // before #653. HTLC value routed is above the remaining balance, thus
8688 // inverting HTLC and `to_remote` output. HTLC will come second and
8689 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8690 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8691 // outputs order detection for correct spending children filtring.
8693 let chanmon_cfgs = create_chanmon_cfgs(2);
8694 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8695 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8696 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8698 // Create some initial channels
8699 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8701 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8702 let (_, our_payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8703 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8704 assert_eq!(local_txn[0].input.len(), 1);
8705 assert_eq!(local_txn[0].output.len(), 3);
8706 check_spends!(local_txn[0], chan_1.3);
8708 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8709 let block = create_dummy_block(nodes[0].best_block_hash(), 42, vec![local_txn[0].clone()]);
8710 connect_block(&nodes[0], &block);
8711 // We deliberately connect the local tx twice as this should provoke a failure calling
8712 // this test before #653 fix.
8713 chain::Listen::block_connected(&nodes[0].chain_monitor.chain_monitor, &block, nodes[0].best_block_info().1 + 1);
8714 check_closed_broadcast!(nodes[0], true);
8715 check_added_monitors!(nodes[0], 1);
8716 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
8717 connect_blocks(&nodes[0], TEST_FINAL_CLTV);
8719 let htlc_timeout = {
8720 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8721 assert_eq!(node_txn.len(), 1);
8722 assert_eq!(node_txn[0].input.len(), 1);
8723 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8724 check_spends!(node_txn[0], local_txn[0]);
8728 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![htlc_timeout.clone()]));
8729 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8730 expect_payment_failed!(nodes[0], our_payment_hash, false);
8733 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8734 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8735 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8736 // Carol, Alice would be the upstream node, and Carol the downstream.)
8738 // Steps of the test:
8739 // 1) Alice sends a HTLC to Carol through Bob.
8740 // 2) Carol doesn't settle the HTLC.
8741 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8742 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8743 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8744 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8745 // 5) Carol release the preimage to Bob off-chain.
8746 // 6) Bob claims the offered output on the broadcasted commitment.
8747 let chanmon_cfgs = create_chanmon_cfgs(3);
8748 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8749 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8750 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8752 // Create some initial channels
8753 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8754 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8756 // Steps (1) and (2):
8757 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8758 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8760 // Check that Alice's commitment transaction now contains an output for this HTLC.
8761 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8762 check_spends!(alice_txn[0], chan_ab.3);
8763 assert_eq!(alice_txn[0].output.len(), 2);
8764 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8765 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8766 assert_eq!(alice_txn.len(), 2);
8768 // Steps (3) and (4):
8769 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8770 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8771 let mut force_closing_node = 0; // Alice force-closes
8772 let mut counterparty_node = 1; // Bob if Alice force-closes
8775 if !broadcast_alice {
8776 force_closing_node = 1;
8777 counterparty_node = 0;
8779 nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8780 check_closed_broadcast!(nodes[force_closing_node], true);
8781 check_added_monitors!(nodes[force_closing_node], 1);
8782 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed, [nodes[counterparty_node].node.get_our_node_id()], 100000);
8783 if go_onchain_before_fulfill {
8784 let txn_to_broadcast = match broadcast_alice {
8785 true => alice_txn.clone(),
8786 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8788 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8789 if broadcast_alice {
8790 check_closed_broadcast!(nodes[1], true);
8791 check_added_monitors!(nodes[1], 1);
8792 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
8797 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8798 // process of removing the HTLC from their commitment transactions.
8799 nodes[2].node.claim_funds(payment_preimage);
8800 check_added_monitors!(nodes[2], 1);
8801 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8803 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8804 assert!(carol_updates.update_add_htlcs.is_empty());
8805 assert!(carol_updates.update_fail_htlcs.is_empty());
8806 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8807 assert!(carol_updates.update_fee.is_none());
8808 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8810 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8811 let went_onchain = go_onchain_before_fulfill || force_closing_node == 1;
8812 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if went_onchain { None } else { Some(1000) }, went_onchain, false);
8813 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8814 if !go_onchain_before_fulfill && broadcast_alice {
8815 let events = nodes[1].node.get_and_clear_pending_msg_events();
8816 assert_eq!(events.len(), 1);
8818 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8819 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8821 _ => panic!("Unexpected event"),
8824 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8825 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8826 // Carol<->Bob's updated commitment transaction info.
8827 check_added_monitors!(nodes[1], 2);
8829 let events = nodes[1].node.get_and_clear_pending_msg_events();
8830 assert_eq!(events.len(), 2);
8831 let bob_revocation = match events[0] {
8832 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8833 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8836 _ => panic!("Unexpected event"),
8838 let bob_updates = match events[1] {
8839 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8840 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8843 _ => panic!("Unexpected event"),
8846 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8847 check_added_monitors!(nodes[2], 1);
8848 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8849 check_added_monitors!(nodes[2], 1);
8851 let events = nodes[2].node.get_and_clear_pending_msg_events();
8852 assert_eq!(events.len(), 1);
8853 let carol_revocation = match events[0] {
8854 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8855 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8858 _ => panic!("Unexpected event"),
8860 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8861 check_added_monitors!(nodes[1], 1);
8863 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8864 // here's where we put said channel's commitment tx on-chain.
8865 let mut txn_to_broadcast = alice_txn.clone();
8866 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8867 if !go_onchain_before_fulfill {
8868 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8869 // If Bob was the one to force-close, he will have already passed these checks earlier.
8870 if broadcast_alice {
8871 check_closed_broadcast!(nodes[1], true);
8872 check_added_monitors!(nodes[1], 1);
8873 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
8875 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8876 if broadcast_alice {
8877 assert_eq!(bob_txn.len(), 1);
8878 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8880 assert_eq!(bob_txn.len(), 2);
8881 check_spends!(bob_txn[0], chan_ab.3);
8886 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8887 // broadcasted commitment transaction.
8889 let script_weight = match broadcast_alice {
8890 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8891 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8893 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8894 // Bob force-closed and broadcasts the commitment transaction along with a
8895 // HTLC-output-claiming transaction.
8896 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8897 if broadcast_alice {
8898 assert_eq!(bob_txn.len(), 1);
8899 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8900 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8902 assert_eq!(bob_txn.len(), 2);
8903 check_spends!(bob_txn[1], txn_to_broadcast[0]);
8904 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8910 fn test_onchain_htlc_settlement_after_close() {
8911 do_test_onchain_htlc_settlement_after_close(true, true);
8912 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8913 do_test_onchain_htlc_settlement_after_close(true, false);
8914 do_test_onchain_htlc_settlement_after_close(false, false);
8918 fn test_duplicate_temporary_channel_id_from_different_peers() {
8919 // Tests that we can accept two different `OpenChannel` requests with the same
8920 // `temporary_channel_id`, as long as they are from different peers.
8921 let chanmon_cfgs = create_chanmon_cfgs(3);
8922 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8923 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8924 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8926 // Create an first channel channel
8927 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
8928 let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8930 // Create an second channel
8931 nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None, None).unwrap();
8932 let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8934 // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8935 // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8936 open_chan_msg_chan_2_0.temporary_channel_id = open_chan_msg_chan_1_0.temporary_channel_id;
8938 // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8939 // `temporary_channel_id` as they are from different peers.
8940 nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
8942 let events = nodes[0].node.get_and_clear_pending_msg_events();
8943 assert_eq!(events.len(), 1);
8945 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8946 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8947 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8949 _ => panic!("Unexpected event"),
8953 nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
8955 let events = nodes[0].node.get_and_clear_pending_msg_events();
8956 assert_eq!(events.len(), 1);
8958 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8959 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
8960 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8962 _ => panic!("Unexpected event"),
8968 fn test_duplicate_chan_id() {
8969 // Test that if a given peer tries to open a channel with the same channel_id as one that is
8970 // already open we reject it and keep the old channel.
8972 // Previously, full_stack_target managed to figure out that if you tried to open two channels
8973 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8974 // the existing channel when we detect the duplicate new channel, screwing up our monitor
8975 // updating logic for the existing channel.
8976 let chanmon_cfgs = create_chanmon_cfgs(2);
8977 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8978 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8979 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8981 // Create an initial channel
8982 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
8983 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8984 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8985 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()));
8987 // Try to create a second channel with the same temporary_channel_id as the first and check
8988 // that it is rejected.
8989 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8991 let events = nodes[1].node.get_and_clear_pending_msg_events();
8992 assert_eq!(events.len(), 1);
8994 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8995 // Technically, at this point, nodes[1] would be justified in thinking both the
8996 // first (valid) and second (invalid) channels are closed, given they both have
8997 // the same non-temporary channel_id. However, currently we do not, so we just
8998 // move forward with it.
8999 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9000 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9002 _ => panic!("Unexpected event"),
9006 // Move the first channel through the funding flow...
9007 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9009 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9010 check_added_monitors!(nodes[0], 0);
9012 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9013 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9015 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9016 assert_eq!(added_monitors.len(), 1);
9017 assert_eq!(added_monitors[0].0, funding_output);
9018 added_monitors.clear();
9020 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9022 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9024 let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
9025 let channel_id = funding_outpoint.to_channel_id();
9027 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
9030 // First try to open a second channel with a temporary channel id equal to the txid-based one.
9031 // Technically this is allowed by the spec, but we don't support it and there's little reason
9032 // to. Still, it shouldn't cause any other issues.
9033 open_chan_msg.temporary_channel_id = channel_id;
9034 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
9036 let events = nodes[1].node.get_and_clear_pending_msg_events();
9037 assert_eq!(events.len(), 1);
9039 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9040 // Technically, at this point, nodes[1] would be justified in thinking both
9041 // channels are closed, but currently we do not, so we just move forward with it.
9042 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9043 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9045 _ => panic!("Unexpected event"),
9049 // Now try to create a second channel which has a duplicate funding output.
9050 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
9051 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9052 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
9053 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()));
9054 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
9056 let (_, funding_created) = {
9057 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9058 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9059 // Once we call `get_funding_created` the channel has a duplicate channel_id as
9060 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
9061 // try to create another channel. Instead, we drop the channel entirely here (leaving the
9062 // channelmanager in a possibly nonsense state instead).
9063 match a_peer_state.channel_by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap() {
9064 ChannelPhase::UnfundedOutboundV1(chan) => {
9065 let logger = test_utils::TestLogger::new();
9066 chan.get_funding_created(tx.clone(), funding_outpoint, false, &&logger).map_err(|_| ()).unwrap()
9068 _ => panic!("Unexpected ChannelPhase variant"),
9071 check_added_monitors!(nodes[0], 0);
9072 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created.unwrap());
9073 // At this point we'll look up if the channel_id is present and immediately fail the channel
9074 // without trying to persist the `ChannelMonitor`.
9075 check_added_monitors!(nodes[1], 0);
9077 // ...still, nodes[1] will reject the duplicate channel.
9079 let events = nodes[1].node.get_and_clear_pending_msg_events();
9080 assert_eq!(events.len(), 1);
9082 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9083 // Technically, at this point, nodes[1] would be justified in thinking both
9084 // channels are closed, but currently we do not, so we just move forward with it.
9085 assert_eq!(msg.channel_id, channel_id);
9086 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9088 _ => panic!("Unexpected event"),
9092 // finally, finish creating the original channel and send a payment over it to make sure
9093 // everything is functional.
9094 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9096 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9097 assert_eq!(added_monitors.len(), 1);
9098 assert_eq!(added_monitors[0].0, funding_output);
9099 added_monitors.clear();
9101 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9103 let events_4 = nodes[0].node.get_and_clear_pending_events();
9104 assert_eq!(events_4.len(), 0);
9105 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9106 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9108 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9109 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9110 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9112 send_payment(&nodes[0], &[&nodes[1]], 8000000);
9116 fn test_error_chans_closed() {
9117 // Test that we properly handle error messages, closing appropriate channels.
9119 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9120 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9121 // we can test various edge cases around it to ensure we don't regress.
9122 let chanmon_cfgs = create_chanmon_cfgs(3);
9123 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9124 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9125 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9127 // Create some initial channels
9128 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9129 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9130 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
9132 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9133 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9134 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9136 // Closing a channel from a different peer has no effect
9137 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9138 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9140 // Closing one channel doesn't impact others
9141 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9142 check_added_monitors!(nodes[0], 1);
9143 check_closed_broadcast!(nodes[0], false);
9144 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) },
9145 [nodes[1].node.get_our_node_id()], 100000);
9146 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9147 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9148 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);
9149 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);
9151 // A null channel ID should close all channels
9152 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9153 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: ChannelId::new_zero(), data: "ERR".to_owned() });
9154 check_added_monitors!(nodes[0], 2);
9155 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) },
9156 [nodes[1].node.get_our_node_id(); 2], 100000);
9157 let events = nodes[0].node.get_and_clear_pending_msg_events();
9158 assert_eq!(events.len(), 2);
9160 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9161 assert_eq!(msg.contents.flags & 2, 2);
9163 _ => panic!("Unexpected event"),
9166 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9167 assert_eq!(msg.contents.flags & 2, 2);
9169 _ => panic!("Unexpected event"),
9171 // Note that at this point users of a standard PeerHandler will end up calling
9172 // peer_disconnected.
9173 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9174 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9176 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9177 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9178 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9182 fn test_invalid_funding_tx() {
9183 // Test that we properly handle invalid funding transactions sent to us from a peer.
9185 // Previously, all other major lightning implementations had failed to properly sanitize
9186 // funding transactions from their counterparties, leading to a multi-implementation critical
9187 // security vulnerability (though we always sanitized properly, we've previously had
9188 // un-released crashes in the sanitization process).
9190 // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9191 // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9192 // gave up on it. We test this here by generating such a transaction.
9193 let chanmon_cfgs = create_chanmon_cfgs(2);
9194 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9195 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9196 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9198 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None, None).unwrap();
9199 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()));
9200 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()));
9202 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9204 // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9205 // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9206 // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9208 let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9209 let wit_program_script: Script = wit_program.into();
9210 for output in tx.output.iter_mut() {
9211 // Make the confirmed funding transaction have a bogus script_pubkey
9212 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9215 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9216 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()));
9217 check_added_monitors!(nodes[1], 1);
9218 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9220 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()));
9221 check_added_monitors!(nodes[0], 1);
9222 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9224 let events_1 = nodes[0].node.get_and_clear_pending_events();
9225 assert_eq!(events_1.len(), 0);
9227 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9228 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9229 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9231 let expected_err = "funding tx had wrong script/value or output index";
9232 confirm_transaction_at(&nodes[1], &tx, 1);
9233 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() },
9234 [nodes[0].node.get_our_node_id()], 100000);
9235 check_added_monitors!(nodes[1], 1);
9236 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9237 assert_eq!(events_2.len(), 1);
9238 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9239 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9240 if let msgs::ErrorAction::DisconnectPeer { msg } = action {
9241 assert_eq!(msg.as_ref().unwrap().data, "Channel closed because of an exception: ".to_owned() + expected_err);
9242 } else { panic!(); }
9243 } else { panic!(); }
9244 assert_eq!(nodes[1].node.list_channels().len(), 0);
9246 // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9247 // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9248 // as its not 32 bytes long.
9249 let mut spend_tx = Transaction {
9250 version: 2i32, lock_time: PackedLockTime::ZERO,
9251 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9252 previous_output: BitcoinOutPoint {
9256 script_sig: Script::new(),
9257 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9258 witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9260 output: vec![TxOut {
9262 script_pubkey: Script::new(),
9265 check_spends!(spend_tx, tx);
9266 mine_transaction(&nodes[1], &spend_tx);
9270 fn test_coinbase_funding_tx() {
9271 // Miners are able to fund channels directly from coinbase transactions, however
9272 // by consensus rules, outputs of a coinbase transaction are encumbered by a 100
9273 // block maturity timelock. To ensure that a (non-0conf) channel like this is enforceable
9274 // on-chain, the minimum depth is updated to 100 blocks for coinbase funding transactions.
9276 // Note that 0conf channels with coinbase funding transactions are unaffected and are
9277 // immediately operational after opening.
9278 let chanmon_cfgs = create_chanmon_cfgs(2);
9279 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9280 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9281 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9283 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
9284 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9286 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9287 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9289 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9291 // Create the coinbase funding transaction.
9292 let (temporary_channel_id, tx, _) = create_coinbase_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9294 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9295 check_added_monitors!(nodes[0], 0);
9296 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9298 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9299 check_added_monitors!(nodes[1], 1);
9300 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9302 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9304 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
9305 check_added_monitors!(nodes[0], 1);
9307 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9308 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
9310 // Starting at height 0, we "confirm" the coinbase at height 1.
9311 confirm_transaction_at(&nodes[0], &tx, 1);
9312 // We connect 98 more blocks to have 99 confirmations for the coinbase transaction.
9313 connect_blocks(&nodes[0], COINBASE_MATURITY - 2);
9314 // Check that we have no pending message events (we have not queued a `channel_ready` yet).
9315 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
9316 // Now connect one more block which results in 100 confirmations of the coinbase transaction.
9317 connect_blocks(&nodes[0], 1);
9318 // There should now be a `channel_ready` which can be handled.
9319 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()));
9321 confirm_transaction_at(&nodes[1], &tx, 1);
9322 connect_blocks(&nodes[1], COINBASE_MATURITY - 2);
9323 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9324 connect_blocks(&nodes[1], 1);
9325 expect_channel_ready_event(&nodes[1], &nodes[0].node.get_our_node_id());
9326 create_chan_between_nodes_with_value_confirm_second(&nodes[0], &nodes[1]);
9329 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9330 // In the first version of the chain::Confirm interface, after a refactor was made to not
9331 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9332 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9333 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9334 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9335 // spending transaction until height N+1 (or greater). This was due to the way
9336 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9337 // spending transaction at the height the input transaction was confirmed at, not whether we
9338 // should broadcast a spending transaction at the current height.
9339 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9340 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9341 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9342 // until we learned about an additional block.
9344 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9345 // aren't broadcasting transactions too early (ie not broadcasting them at all).
9346 let chanmon_cfgs = create_chanmon_cfgs(3);
9347 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9348 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9349 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9350 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9352 create_announced_chan_between_nodes(&nodes, 0, 1);
9353 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
9354 let (_, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9355 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
9356 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9358 nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9359 check_closed_broadcast!(nodes[1], true);
9360 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[2].node.get_our_node_id()], 100000);
9361 check_added_monitors!(nodes[1], 1);
9362 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9363 assert_eq!(node_txn.len(), 1);
9365 let conf_height = nodes[1].best_block_info().1;
9366 if !test_height_before_timelock {
9367 connect_blocks(&nodes[1], 24 * 6);
9369 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9370 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9371 if test_height_before_timelock {
9372 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9373 // generate any events or broadcast any transactions
9374 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9375 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9377 // We should broadcast an HTLC transaction spending our funding transaction first
9378 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9379 assert_eq!(spending_txn.len(), 2);
9380 assert_eq!(spending_txn[0].txid(), node_txn[0].txid());
9381 check_spends!(spending_txn[1], node_txn[0]);
9382 // We should also generate a SpendableOutputs event with the to_self output (as its
9384 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9385 assert_eq!(descriptor_spend_txn.len(), 1);
9387 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9388 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9389 // additional block built on top of the current chain.
9390 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9391 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9392 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 }]);
9393 check_added_monitors!(nodes[1], 1);
9395 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9396 assert!(updates.update_add_htlcs.is_empty());
9397 assert!(updates.update_fulfill_htlcs.is_empty());
9398 assert_eq!(updates.update_fail_htlcs.len(), 1);
9399 assert!(updates.update_fail_malformed_htlcs.is_empty());
9400 assert!(updates.update_fee.is_none());
9401 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9402 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9403 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9408 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9409 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9410 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9413 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9414 let chanmon_cfgs = create_chanmon_cfgs(2);
9415 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9416 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9417 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9419 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9421 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9422 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
9423 let route = get_route!(nodes[0], payment_params, 10_000).unwrap();
9425 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9428 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9429 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9430 check_added_monitors!(nodes[0], 1);
9431 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9432 assert_eq!(events.len(), 1);
9433 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9434 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9435 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9437 expect_pending_htlcs_forwardable!(nodes[1]);
9438 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9441 // Note that we use a different PaymentId here to allow us to duplicativly pay
9442 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9443 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9444 check_added_monitors!(nodes[0], 1);
9445 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9446 assert_eq!(events.len(), 1);
9447 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9448 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9449 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9450 // At this point, nodes[1] would notice it has too much value for the payment. It will
9451 // assume the second is a privacy attack (no longer particularly relevant
9452 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9453 // the first HTLC delivered above.
9456 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9457 nodes[1].node.process_pending_htlc_forwards();
9459 if test_for_second_fail_panic {
9460 // Now we go fail back the first HTLC from the user end.
9461 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9463 let expected_destinations = vec![
9464 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9465 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9467 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], expected_destinations);
9468 nodes[1].node.process_pending_htlc_forwards();
9470 check_added_monitors!(nodes[1], 1);
9471 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9472 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9474 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9475 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9476 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9478 let failure_events = nodes[0].node.get_and_clear_pending_events();
9479 assert_eq!(failure_events.len(), 4);
9480 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9481 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9482 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9483 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9485 // Let the second HTLC fail and claim the first
9486 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9487 nodes[1].node.process_pending_htlc_forwards();
9489 check_added_monitors!(nodes[1], 1);
9490 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9491 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9492 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9494 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9496 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9501 fn test_dup_htlc_second_fail_panic() {
9502 // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9503 // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9504 // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9505 // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9506 do_test_dup_htlc_second_rejected(true);
9510 fn test_dup_htlc_second_rejected() {
9511 // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9512 // simply reject the second HTLC but are still able to claim the first HTLC.
9513 do_test_dup_htlc_second_rejected(false);
9517 fn test_inconsistent_mpp_params() {
9518 // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9519 // such HTLC and allow the second to stay.
9520 let chanmon_cfgs = create_chanmon_cfgs(4);
9521 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9522 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9523 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9525 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9526 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9527 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9528 let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9530 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9531 .with_bolt11_features(nodes[3].node.bolt11_invoice_features()).unwrap();
9532 let mut route = get_route!(nodes[0], payment_params, 15_000_000).unwrap();
9533 assert_eq!(route.paths.len(), 2);
9534 route.paths.sort_by(|path_a, _| {
9535 // Sort the path so that the path through nodes[1] comes first
9536 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9537 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9540 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9542 let cur_height = nodes[0].best_block_info().1;
9543 let payment_id = PaymentId([42; 32]);
9545 let session_privs = {
9546 // We create a fake route here so that we start with three pending HTLCs, which we'll
9547 // ultimately have, just not right away.
9548 let mut dup_route = route.clone();
9549 dup_route.paths.push(route.paths[1].clone());
9550 nodes[0].node.test_add_new_pending_payment(our_payment_hash,
9551 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &dup_route).unwrap()
9553 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
9554 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9555 &None, session_privs[0]).unwrap();
9556 check_added_monitors!(nodes[0], 1);
9559 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9560 assert_eq!(events.len(), 1);
9561 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9563 assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9565 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9566 RecipientOnionFields::secret_only(our_payment_secret), 14_000_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9567 check_added_monitors!(nodes[0], 1);
9570 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9571 assert_eq!(events.len(), 1);
9572 let payment_event = SendEvent::from_event(events.pop().unwrap());
9574 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9575 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9577 expect_pending_htlcs_forwardable!(nodes[2]);
9578 check_added_monitors!(nodes[2], 1);
9580 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9581 assert_eq!(events.len(), 1);
9582 let payment_event = SendEvent::from_event(events.pop().unwrap());
9584 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9585 check_added_monitors!(nodes[3], 0);
9586 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9588 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9589 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9590 // post-payment_secrets) and fail back the new HTLC.
9592 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9593 nodes[3].node.process_pending_htlc_forwards();
9594 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9595 nodes[3].node.process_pending_htlc_forwards();
9597 check_added_monitors!(nodes[3], 1);
9599 let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9600 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9601 commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9603 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 }]);
9604 check_added_monitors!(nodes[2], 1);
9606 let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9607 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9608 commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9610 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9612 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9613 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9614 &None, session_privs[2]).unwrap();
9615 check_added_monitors!(nodes[0], 1);
9617 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9618 assert_eq!(events.len(), 1);
9619 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9621 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9622 expect_payment_sent(&nodes[0], our_payment_preimage, Some(None), true, true);
9626 fn test_double_partial_claim() {
9627 // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9628 // time out, the sender resends only some of the MPP parts, then the user processes the
9629 // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9631 let chanmon_cfgs = create_chanmon_cfgs(4);
9632 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9633 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9634 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9636 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9637 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9638 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9639 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9641 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9642 assert_eq!(route.paths.len(), 2);
9643 route.paths.sort_by(|path_a, _| {
9644 // Sort the path so that the path through nodes[1] comes first
9645 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9646 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9649 send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9650 // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9651 // amount of time to respond to.
9653 // Connect some blocks to time out the payment
9654 connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9655 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9657 let failed_destinations = vec![
9658 HTLCDestination::FailedPayment { payment_hash },
9659 HTLCDestination::FailedPayment { payment_hash },
9661 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9663 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
9665 // nodes[1] now retries one of the two paths...
9666 nodes[0].node.send_payment_with_route(&route, payment_hash,
9667 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9668 check_added_monitors!(nodes[0], 2);
9670 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9671 assert_eq!(events.len(), 2);
9672 let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
9673 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9675 // At this point nodes[3] has received one half of the payment, and the user goes to handle
9676 // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9677 nodes[3].node.claim_funds(payment_preimage);
9678 check_added_monitors!(nodes[3], 0);
9679 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9682 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9683 #[derive(Clone, Copy, PartialEq)]
9684 enum ExposureEvent {
9685 /// Breach occurs at HTLC forwarding (see `send_htlc`)
9687 /// Breach occurs at HTLC reception (see `update_add_htlc`)
9689 /// Breach occurs at outbound update_fee (see `send_update_fee`)
9690 AtUpdateFeeOutbound,
9693 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool, multiplier_dust_limit: bool) {
9694 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9697 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9698 // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9699 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9700 // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9701 // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9702 // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9703 // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9704 // might be available again for HTLC processing once the dust bandwidth has cleared up.
9706 let chanmon_cfgs = create_chanmon_cfgs(2);
9707 let mut config = test_default_channel_config();
9708 config.channel_config.max_dust_htlc_exposure = if multiplier_dust_limit {
9709 // Default test fee estimator rate is 253 sat/kw, so we set the multiplier to 5_000_000 / 253
9710 // to get roughly the same initial value as the default setting when this test was
9711 // originally written.
9712 MaxDustHTLCExposure::FeeRateMultiplier(5_000_000 / 253)
9713 } else { MaxDustHTLCExposure::FixedLimitMsat(5_000_000) }; // initial default setting value
9714 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9715 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9716 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9718 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None, None).unwrap();
9719 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9720 open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9721 open_channel.max_accepted_htlcs = 60;
9723 open_channel.dust_limit_satoshis = 546;
9725 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9726 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9727 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9729 let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
9731 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9734 let mut node_0_per_peer_lock;
9735 let mut node_0_peer_state_lock;
9736 match get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, temporary_channel_id) {
9737 ChannelPhase::UnfundedOutboundV1(chan) => {
9738 chan.context.holder_dust_limit_satoshis = 546;
9740 _ => panic!("Unexpected ChannelPhase variant"),
9744 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9745 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()));
9746 check_added_monitors!(nodes[1], 1);
9747 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9749 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()));
9750 check_added_monitors!(nodes[0], 1);
9751 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9753 let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9754 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9755 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9757 // Fetch a route in advance as we will be unable to once we're unable to send.
9758 let (mut route, payment_hash, _, payment_secret) =
9759 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
9761 let (dust_buffer_feerate, max_dust_htlc_exposure_msat) = {
9762 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9763 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9764 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
9765 (chan.context().get_dust_buffer_feerate(None) as u64,
9766 chan.context().get_max_dust_htlc_exposure_msat(&LowerBoundedFeeEstimator(nodes[0].fee_estimator)))
9768 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;
9769 let dust_outbound_htlc_on_holder_tx: u64 = max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9771 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;
9772 let dust_inbound_htlc_on_holder_tx: u64 = max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9774 let dust_htlc_on_counterparty_tx: u64 = 4;
9775 let dust_htlc_on_counterparty_tx_msat: u64 = max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9778 if dust_outbound_balance {
9779 // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9780 // Outbound dust balance: 4372 sats
9781 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9782 for _ in 0..dust_outbound_htlc_on_holder_tx {
9783 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9784 nodes[0].node.send_payment_with_route(&route, payment_hash,
9785 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9788 // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9789 // Inbound dust balance: 4372 sats
9790 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9791 for _ in 0..dust_inbound_htlc_on_holder_tx {
9792 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9796 if dust_outbound_balance {
9797 // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9798 // Outbound dust balance: 5000 sats
9799 for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9800 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9801 nodes[0].node.send_payment_with_route(&route, payment_hash,
9802 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9805 // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9806 // Inbound dust balance: 5000 sats
9807 for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9808 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9813 if exposure_breach_event == ExposureEvent::AtHTLCForward {
9814 route.paths[0].hops.last_mut().unwrap().fee_msat =
9815 if on_holder_tx { dust_outbound_htlc_on_holder_tx_msat } else { dust_htlc_on_counterparty_tx_msat + 1 };
9816 // With default dust exposure: 5000 sats
9818 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9819 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9820 ), true, APIError::ChannelUnavailable { .. }, {});
9822 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9823 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9824 ), true, APIError::ChannelUnavailable { .. }, {});
9826 } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9827 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 });
9828 nodes[1].node.send_payment_with_route(&route, payment_hash,
9829 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9830 check_added_monitors!(nodes[1], 1);
9831 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9832 assert_eq!(events.len(), 1);
9833 let payment_event = SendEvent::from_event(events.remove(0));
9834 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9835 // With default dust exposure: 5000 sats
9837 // Outbound dust balance: 6399 sats
9838 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9839 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9840 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);
9842 // Outbound dust balance: 5200 sats
9843 nodes[0].logger.assert_log("lightning::ln::channel".to_string(),
9844 format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx",
9845 dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx - 1) + dust_htlc_on_counterparty_tx_msat + 4,
9846 max_dust_htlc_exposure_msat), 1);
9848 } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9849 route.paths[0].hops.last_mut().unwrap().fee_msat = 2_500_000;
9850 // For the multiplier dust exposure limit, since it scales with feerate,
9851 // we need to add a lot of HTLCs that will become dust at the new feerate
9852 // to cross the threshold.
9854 let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[1], Some(1_000), None);
9855 nodes[0].node.send_payment_with_route(&route, payment_hash,
9856 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9859 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9860 *feerate_lock = *feerate_lock * 10;
9862 nodes[0].node.timer_tick_occurred();
9863 check_added_monitors!(nodes[0], 1);
9864 nodes[0].logger.assert_log_contains("lightning::ln::channel", "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure", 1);
9867 let _ = nodes[0].node.get_and_clear_pending_msg_events();
9868 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9869 added_monitors.clear();
9872 fn do_test_max_dust_htlc_exposure_by_threshold_type(multiplier_dust_limit: bool) {
9873 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true, multiplier_dust_limit);
9874 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true, multiplier_dust_limit);
9875 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true, multiplier_dust_limit);
9876 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false, multiplier_dust_limit);
9877 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false, multiplier_dust_limit);
9878 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false, multiplier_dust_limit);
9879 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true, multiplier_dust_limit);
9880 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false, multiplier_dust_limit);
9881 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true, multiplier_dust_limit);
9882 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false, multiplier_dust_limit);
9883 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false, multiplier_dust_limit);
9884 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true, multiplier_dust_limit);
9888 fn test_max_dust_htlc_exposure() {
9889 do_test_max_dust_htlc_exposure_by_threshold_type(false);
9890 do_test_max_dust_htlc_exposure_by_threshold_type(true);
9894 fn test_non_final_funding_tx() {
9895 let chanmon_cfgs = create_chanmon_cfgs(2);
9896 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9897 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9898 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9900 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
9901 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9902 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9903 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9904 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
9906 let best_height = nodes[0].node.best_block.read().unwrap().height();
9908 let chan_id = *nodes[0].network_chan_count.borrow();
9909 let events = nodes[0].node.get_and_clear_pending_events();
9910 let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
9911 assert_eq!(events.len(), 1);
9912 let mut tx = match events[0] {
9913 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9914 // Timelock the transaction _beyond_ the best client height + 1.
9915 Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 2), input: vec![input], output: vec![TxOut {
9916 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9919 _ => panic!("Unexpected event"),
9921 // Transaction should fail as it's evaluated as non-final for propagation.
9922 match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
9923 Err(APIError::APIMisuseError { err }) => {
9924 assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
9928 let events = nodes[0].node.get_and_clear_pending_events();
9929 assert_eq!(events.len(), 1);
9931 Event::ChannelClosed { channel_id, .. } => {
9932 assert_eq!(channel_id, temp_channel_id);
9934 _ => panic!("Unexpected event"),
9939 fn test_non_final_funding_tx_within_headroom() {
9940 let chanmon_cfgs = create_chanmon_cfgs(2);
9941 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9942 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9943 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9945 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
9946 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9947 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9948 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9949 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
9951 let best_height = nodes[0].node.best_block.read().unwrap().height();
9953 let chan_id = *nodes[0].network_chan_count.borrow();
9954 let events = nodes[0].node.get_and_clear_pending_events();
9955 let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
9956 assert_eq!(events.len(), 1);
9957 let mut tx = match events[0] {
9958 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9959 // Timelock the transaction within a +1 headroom from the best block.
9960 Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 1), input: vec![input], output: vec![TxOut {
9961 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9964 _ => panic!("Unexpected event"),
9967 // Transaction should be accepted if it's in a +1 headroom from best block.
9968 assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
9969 get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9973 fn accept_busted_but_better_fee() {
9974 // If a peer sends us a fee update that is too low, but higher than our previous channel
9975 // feerate, we should accept it. In the future we may want to consider closing the channel
9976 // later, but for now we only accept the update.
9977 let mut chanmon_cfgs = create_chanmon_cfgs(2);
9978 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9979 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9980 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9982 create_chan_between_nodes(&nodes[0], &nodes[1]);
9984 // Set nodes[1] to expect 5,000 sat/kW.
9986 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
9987 *feerate_lock = 5000;
9990 // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
9992 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9993 *feerate_lock = 1000;
9995 nodes[0].node.timer_tick_occurred();
9996 check_added_monitors!(nodes[0], 1);
9998 let events = nodes[0].node.get_and_clear_pending_msg_events();
9999 assert_eq!(events.len(), 1);
10001 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
10002 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
10003 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
10005 _ => panic!("Unexpected event"),
10008 // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
10011 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10012 *feerate_lock = 2000;
10014 nodes[0].node.timer_tick_occurred();
10015 check_added_monitors!(nodes[0], 1);
10017 let events = nodes[0].node.get_and_clear_pending_msg_events();
10018 assert_eq!(events.len(), 1);
10020 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
10021 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
10022 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
10024 _ => panic!("Unexpected event"),
10027 // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
10030 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10031 *feerate_lock = 1000;
10033 nodes[0].node.timer_tick_occurred();
10034 check_added_monitors!(nodes[0], 1);
10036 let events = nodes[0].node.get_and_clear_pending_msg_events();
10037 assert_eq!(events.len(), 1);
10039 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
10040 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
10041 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
10042 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000".to_owned() },
10043 [nodes[0].node.get_our_node_id()], 100000);
10044 check_closed_broadcast!(nodes[1], true);
10045 check_added_monitors!(nodes[1], 1);
10047 _ => panic!("Unexpected event"),
10051 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
10052 let mut chanmon_cfgs = create_chanmon_cfgs(2);
10053 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10054 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10055 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10056 let min_final_cltv_expiry_delta = 120;
10057 let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
10058 min_final_cltv_expiry_delta - 2 };
10059 let recv_value = 100_000;
10061 create_chan_between_nodes(&nodes[0], &nodes[1]);
10063 let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), final_cltv_expiry_delta as u32);
10064 let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
10065 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
10066 Some(recv_value), Some(min_final_cltv_expiry_delta));
10067 (payment_hash, payment_preimage, payment_secret)
10069 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
10070 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
10072 let route = get_route!(nodes[0], payment_parameters, recv_value).unwrap();
10073 nodes[0].node.send_payment_with_route(&route, payment_hash,
10074 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
10075 check_added_monitors!(nodes[0], 1);
10076 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10077 assert_eq!(events.len(), 1);
10078 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
10079 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
10080 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
10081 expect_pending_htlcs_forwardable!(nodes[1]);
10084 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
10085 None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
10087 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
10089 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
10091 check_added_monitors!(nodes[1], 1);
10093 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
10094 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
10095 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
10097 expect_payment_failed!(nodes[0], payment_hash, true);
10102 fn test_payment_with_custom_min_cltv_expiry_delta() {
10103 do_payment_with_custom_min_final_cltv_expiry(false, false);
10104 do_payment_with_custom_min_final_cltv_expiry(false, true);
10105 do_payment_with_custom_min_final_cltv_expiry(true, false);
10106 do_payment_with_custom_min_final_cltv_expiry(true, true);
10110 fn test_disconnects_peer_awaiting_response_ticks() {
10111 // Tests that nodes which are awaiting on a response critical for channel responsiveness
10112 // disconnect their counterparty after `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10113 let mut chanmon_cfgs = create_chanmon_cfgs(2);
10114 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10115 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10116 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10118 // Asserts a disconnect event is queued to the user.
10119 let check_disconnect_event = |node: &Node, should_disconnect: bool| {
10120 let disconnect_event = node.node.get_and_clear_pending_msg_events().iter().find_map(|event|
10121 if let MessageSendEvent::HandleError { action, .. } = event {
10122 if let msgs::ErrorAction::DisconnectPeerWithWarning { .. } = action {
10131 assert_eq!(disconnect_event.is_some(), should_disconnect);
10134 // Fires timer ticks ensuring we only attempt to disconnect peers after reaching
10135 // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10136 let check_disconnect = |node: &Node| {
10137 // No disconnect without any timer ticks.
10138 check_disconnect_event(node, false);
10140 // No disconnect with 1 timer tick less than required.
10141 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS - 1 {
10142 node.node.timer_tick_occurred();
10143 check_disconnect_event(node, false);
10146 // Disconnect after reaching the required ticks.
10147 node.node.timer_tick_occurred();
10148 check_disconnect_event(node, true);
10150 // Disconnect again on the next tick if the peer hasn't been disconnected yet.
10151 node.node.timer_tick_occurred();
10152 check_disconnect_event(node, true);
10155 create_chan_between_nodes(&nodes[0], &nodes[1]);
10157 // We'll start by performing a fee update with Alice (nodes[0]) on the channel.
10158 *nodes[0].fee_estimator.sat_per_kw.lock().unwrap() *= 2;
10159 nodes[0].node.timer_tick_occurred();
10160 check_added_monitors!(&nodes[0], 1);
10161 let alice_fee_update = get_htlc_update_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
10162 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), alice_fee_update.update_fee.as_ref().unwrap());
10163 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &alice_fee_update.commitment_signed);
10164 check_added_monitors!(&nodes[1], 1);
10166 // This will prompt Bob (nodes[1]) to respond with his `CommitmentSigned` and `RevokeAndACK`.
10167 let (bob_revoke_and_ack, bob_commitment_signed) = get_revoke_commit_msgs!(&nodes[1], nodes[0].node.get_our_node_id());
10168 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revoke_and_ack);
10169 check_added_monitors!(&nodes[0], 1);
10170 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_commitment_signed);
10171 check_added_monitors(&nodes[0], 1);
10173 // Alice then needs to send her final `RevokeAndACK` to complete the commitment dance. We
10174 // pretend Bob hasn't received the message and check whether he'll disconnect Alice after
10175 // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10176 let alice_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
10177 check_disconnect(&nodes[1]);
10179 // Now, we'll reconnect them to test awaiting a `ChannelReestablish` message.
10181 // Note that since the commitment dance didn't complete above, Alice is expected to resend her
10182 // final `RevokeAndACK` to Bob to complete it.
10183 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
10184 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10185 let bob_init = msgs::Init {
10186 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
10188 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &bob_init, true).unwrap();
10189 let alice_init = msgs::Init {
10190 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
10192 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &alice_init, true).unwrap();
10194 // Upon reconnection, Alice sends her `ChannelReestablish` to Bob. Alice, however, hasn't
10195 // received Bob's yet, so she should disconnect him after reaching
10196 // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10197 let alice_channel_reestablish = get_event_msg!(
10198 nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id()
10200 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &alice_channel_reestablish);
10201 check_disconnect(&nodes[0]);
10203 // Bob now sends his `ChannelReestablish` to Alice to resume the channel and consider it "live".
10204 let bob_channel_reestablish = nodes[1].node.get_and_clear_pending_msg_events().iter().find_map(|event|
10205 if let MessageSendEvent::SendChannelReestablish { node_id, msg } = event {
10206 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
10212 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bob_channel_reestablish);
10214 // Sanity check that Alice won't disconnect Bob since she's no longer waiting for any messages.
10215 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
10216 nodes[0].node.timer_tick_occurred();
10217 check_disconnect_event(&nodes[0], false);
10220 // However, Bob is still waiting on Alice's `RevokeAndACK`, so he should disconnect her after
10221 // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10222 check_disconnect(&nodes[1]);
10224 // Finally, have Bob process the last message.
10225 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &alice_revoke_and_ack);
10226 check_added_monitors(&nodes[1], 1);
10228 // At this point, neither node should attempt to disconnect each other, since they aren't
10229 // waiting on any messages.
10230 for node in &nodes {
10231 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
10232 node.node.timer_tick_occurred();
10233 check_disconnect_event(node, false);
10239 fn test_remove_expired_outbound_unfunded_channels() {
10240 let chanmon_cfgs = create_chanmon_cfgs(2);
10241 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10242 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10243 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10245 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
10246 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10247 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10248 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10249 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10251 let events = nodes[0].node.get_and_clear_pending_events();
10252 assert_eq!(events.len(), 1);
10254 Event::FundingGenerationReady { .. } => (),
10255 _ => panic!("Unexpected event"),
10258 // Asserts the outbound channel has been removed from a nodes[0]'s peer state map.
10259 let check_outbound_channel_existence = |should_exist: bool| {
10260 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
10261 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
10262 assert_eq!(chan_lock.channel_by_id.contains_key(&temp_channel_id), should_exist);
10265 // Channel should exist without any timer ticks.
10266 check_outbound_channel_existence(true);
10268 // Channel should exist with 1 timer tick less than required.
10269 for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS - 1 {
10270 nodes[0].node.timer_tick_occurred();
10271 check_outbound_channel_existence(true)
10274 // Remove channel after reaching the required ticks.
10275 nodes[0].node.timer_tick_occurred();
10276 check_outbound_channel_existence(false);
10278 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
10279 assert_eq!(msg_events.len(), 1);
10280 match msg_events[0] {
10281 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
10282 assert_eq!(msg.data, "Force-closing pending channel due to timeout awaiting establishment handshake");
10284 _ => panic!("Unexpected event"),
10286 check_closed_event(&nodes[0], 1, ClosureReason::HolderForceClosed, false, &[nodes[1].node.get_our_node_id()], 100000);
10290 fn test_remove_expired_inbound_unfunded_channels() {
10291 let chanmon_cfgs = create_chanmon_cfgs(2);
10292 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10293 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10294 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10296 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
10297 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10298 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10299 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10300 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10302 let events = nodes[0].node.get_and_clear_pending_events();
10303 assert_eq!(events.len(), 1);
10305 Event::FundingGenerationReady { .. } => (),
10306 _ => panic!("Unexpected event"),
10309 // Asserts the inbound channel has been removed from a nodes[1]'s peer state map.
10310 let check_inbound_channel_existence = |should_exist: bool| {
10311 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
10312 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
10313 assert_eq!(chan_lock.channel_by_id.contains_key(&temp_channel_id), should_exist);
10316 // Channel should exist without any timer ticks.
10317 check_inbound_channel_existence(true);
10319 // Channel should exist with 1 timer tick less than required.
10320 for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS - 1 {
10321 nodes[1].node.timer_tick_occurred();
10322 check_inbound_channel_existence(true)
10325 // Remove channel after reaching the required ticks.
10326 nodes[1].node.timer_tick_occurred();
10327 check_inbound_channel_existence(false);
10329 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
10330 assert_eq!(msg_events.len(), 1);
10331 match msg_events[0] {
10332 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
10333 assert_eq!(msg.data, "Force-closing pending channel due to timeout awaiting establishment handshake");
10335 _ => panic!("Unexpected event"),
10337 check_closed_event(&nodes[1], 1, ClosureReason::HolderForceClosed, false, &[nodes[0].node.get_our_node_id()], 100000);
10340 fn do_test_multi_post_event_actions(do_reload: bool) {
10341 // Tests handling multiple post-Event actions at once.
10342 // There is specific code in ChannelManager to handle channels where multiple post-Event
10343 // `ChannelMonitorUpdates` are pending at once. This test exercises that code.
10345 // Specifically, we test calling `get_and_clear_pending_events` while there are two
10346 // PaymentSents from different channels and one channel has two pending `ChannelMonitorUpdate`s
10347 // - one from an RAA and one from an inbound commitment_signed.
10348 let chanmon_cfgs = create_chanmon_cfgs(3);
10349 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10350 let (persister, chain_monitor);
10351 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10352 let nodes_0_deserialized;
10353 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10355 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
10356 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 0, 2).2;
10358 send_payment(&nodes[0], &[&nodes[1]], 1_000_000);
10359 send_payment(&nodes[0], &[&nodes[2]], 1_000_000);
10361 let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
10362 let (payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[2]], 1_000_000);
10364 nodes[1].node.claim_funds(our_payment_preimage);
10365 check_added_monitors!(nodes[1], 1);
10366 expect_payment_claimed!(nodes[1], our_payment_hash, 1_000_000);
10368 nodes[2].node.claim_funds(payment_preimage_2);
10369 check_added_monitors!(nodes[2], 1);
10370 expect_payment_claimed!(nodes[2], payment_hash_2, 1_000_000);
10372 for dest in &[1, 2] {
10373 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[*dest], nodes[0].node.get_our_node_id());
10374 nodes[0].node.handle_update_fulfill_htlc(&nodes[*dest].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
10375 commitment_signed_dance!(nodes[0], nodes[*dest], htlc_fulfill_updates.commitment_signed, false);
10376 check_added_monitors(&nodes[0], 0);
10379 let (route, payment_hash_3, _, payment_secret_3) =
10380 get_route_and_payment_hash!(nodes[1], nodes[0], 100_000);
10381 let payment_id = PaymentId(payment_hash_3.0);
10382 nodes[1].node.send_payment_with_route(&route, payment_hash_3,
10383 RecipientOnionFields::secret_only(payment_secret_3), payment_id).unwrap();
10384 check_added_monitors(&nodes[1], 1);
10386 let send_event = SendEvent::from_node(&nodes[1]);
10387 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event.msgs[0]);
10388 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_event.commitment_msg);
10389 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
10392 let nodes_0_serialized = nodes[0].node.encode();
10393 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
10394 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_2).encode();
10395 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);
10397 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10398 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10400 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
10401 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[2]));
10404 let events = nodes[0].node.get_and_clear_pending_events();
10405 assert_eq!(events.len(), 4);
10406 if let Event::PaymentSent { payment_preimage, .. } = events[0] {
10407 assert!(payment_preimage == our_payment_preimage || payment_preimage == payment_preimage_2);
10408 } else { panic!(); }
10409 if let Event::PaymentSent { payment_preimage, .. } = events[1] {
10410 assert!(payment_preimage == our_payment_preimage || payment_preimage == payment_preimage_2);
10411 } else { panic!(); }
10412 if let Event::PaymentPathSuccessful { .. } = events[2] {} else { panic!(); }
10413 if let Event::PaymentPathSuccessful { .. } = events[3] {} else { panic!(); }
10415 // After the events are processed, the ChannelMonitorUpdates will be released and, upon their
10416 // completion, we'll respond to nodes[1] with an RAA + CS.
10417 get_revoke_commit_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
10418 check_added_monitors(&nodes[0], 3);
10422 fn test_multi_post_event_actions() {
10423 do_test_multi_post_event_actions(true);
10424 do_test_multi_post_event_actions(false);
10428 fn test_batch_channel_open() {
10429 let chanmon_cfgs = create_chanmon_cfgs(3);
10430 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10431 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10432 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10434 // Initiate channel opening and create the batch channel funding transaction.
10435 let (tx, funding_created_msgs) = create_batch_channel_funding(&nodes[0], &[
10436 (&nodes[1], 100_000, 0, 42, None),
10437 (&nodes[2], 200_000, 0, 43, None),
10440 // Go through the funding_created and funding_signed flow with node 1.
10441 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[0]);
10442 check_added_monitors(&nodes[1], 1);
10443 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
10445 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10446 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
10447 check_added_monitors(&nodes[0], 1);
10449 // The transaction should not have been broadcast before all channels are ready.
10450 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
10452 // Go through the funding_created and funding_signed flow with node 2.
10453 nodes[2].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[1]);
10454 check_added_monitors(&nodes[2], 1);
10455 expect_channel_pending_event(&nodes[2], &nodes[0].node.get_our_node_id());
10457 let funding_signed_msg = get_event_msg!(nodes[2], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10458 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
10459 nodes[0].node.handle_funding_signed(&nodes[2].node.get_our_node_id(), &funding_signed_msg);
10460 check_added_monitors(&nodes[0], 1);
10462 // The transaction should not have been broadcast before persisting all monitors has been
10464 assert_eq!(nodes[0].tx_broadcaster.txn_broadcast().len(), 0);
10465 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
10467 // Complete the persistence of the monitor.
10468 nodes[0].chain_monitor.complete_sole_pending_chan_update(
10469 &OutPoint { txid: tx.txid(), index: 1 }.to_channel_id()
10471 let events = nodes[0].node.get_and_clear_pending_events();
10473 // The transaction should only have been broadcast now.
10474 let broadcasted_txs = nodes[0].tx_broadcaster.txn_broadcast();
10475 assert_eq!(broadcasted_txs.len(), 1);
10476 assert_eq!(broadcasted_txs[0], tx);
10478 assert_eq!(events.len(), 2);
10479 assert!(events.iter().any(|e| matches!(
10481 crate::events::Event::ChannelPending {
10482 ref counterparty_node_id,
10484 } if counterparty_node_id == &nodes[1].node.get_our_node_id(),
10486 assert!(events.iter().any(|e| matches!(
10488 crate::events::Event::ChannelPending {
10489 ref counterparty_node_id,
10491 } if counterparty_node_id == &nodes[2].node.get_our_node_id(),
10496 fn test_disconnect_in_funding_batch() {
10497 let chanmon_cfgs = create_chanmon_cfgs(3);
10498 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10499 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10500 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10502 // Initiate channel opening and create the batch channel funding transaction.
10503 let (tx, funding_created_msgs) = create_batch_channel_funding(&nodes[0], &[
10504 (&nodes[1], 100_000, 0, 42, None),
10505 (&nodes[2], 200_000, 0, 43, None),
10508 // Go through the funding_created and funding_signed flow with node 1.
10509 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[0]);
10510 check_added_monitors(&nodes[1], 1);
10511 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
10513 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10514 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
10515 check_added_monitors(&nodes[0], 1);
10517 // The transaction should not have been broadcast before all channels are ready.
10518 assert_eq!(nodes[0].tx_broadcaster.txn_broadcast().len(), 0);
10520 // The remaining peer in the batch disconnects.
10521 nodes[0].node.peer_disconnected(&nodes[2].node.get_our_node_id());
10523 // The channels in the batch will close immediately.
10524 let channel_id_1 = OutPoint { txid: tx.txid(), index: 0 }.to_channel_id();
10525 let channel_id_2 = OutPoint { txid: tx.txid(), index: 1 }.to_channel_id();
10526 check_closed_events(&nodes[0], &[
10527 ExpectedCloseEvent {
10528 channel_id: Some(channel_id_1),
10529 discard_funding: true,
10530 ..Default::default()
10532 ExpectedCloseEvent {
10533 channel_id: Some(channel_id_2),
10534 discard_funding: true,
10535 ..Default::default()
10539 // The monitor should become closed.
10540 check_added_monitors(&nodes[0], 1);
10542 let mut monitor_updates = nodes[0].chain_monitor.monitor_updates.lock().unwrap();
10543 let monitor_updates_1 = monitor_updates.get(&channel_id_1).unwrap();
10544 assert_eq!(monitor_updates_1.len(), 1);
10545 assert_eq!(monitor_updates_1[0].update_id, CLOSED_CHANNEL_UPDATE_ID);
10548 // The funding transaction should not have been broadcast, and therefore, we don't need
10549 // to broadcast a force-close transaction for the closed monitor.
10550 assert_eq!(nodes[0].tx_broadcaster.txn_broadcast().len(), 0);
10552 // Ensure the channels don't exist anymore.
10553 assert!(nodes[0].node.list_channels().is_empty());
10557 fn test_batch_funding_close_after_funding_signed() {
10558 let chanmon_cfgs = create_chanmon_cfgs(3);
10559 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10560 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10561 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10563 // Initiate channel opening and create the batch channel funding transaction.
10564 let (tx, funding_created_msgs) = create_batch_channel_funding(&nodes[0], &[
10565 (&nodes[1], 100_000, 0, 42, None),
10566 (&nodes[2], 200_000, 0, 43, None),
10569 // Go through the funding_created and funding_signed flow with node 1.
10570 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[0]);
10571 check_added_monitors(&nodes[1], 1);
10572 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
10574 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10575 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
10576 check_added_monitors(&nodes[0], 1);
10578 // Go through the funding_created and funding_signed flow with node 2.
10579 nodes[2].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[1]);
10580 check_added_monitors(&nodes[2], 1);
10581 expect_channel_pending_event(&nodes[2], &nodes[0].node.get_our_node_id());
10583 let funding_signed_msg = get_event_msg!(nodes[2], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10584 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
10585 nodes[0].node.handle_funding_signed(&nodes[2].node.get_our_node_id(), &funding_signed_msg);
10586 check_added_monitors(&nodes[0], 1);
10588 // The transaction should not have been broadcast before all channels are ready.
10589 assert_eq!(nodes[0].tx_broadcaster.txn_broadcast().len(), 0);
10591 // Force-close the channel for which we've completed the initial monitor.
10592 let channel_id_1 = OutPoint { txid: tx.txid(), index: 0 }.to_channel_id();
10593 let channel_id_2 = OutPoint { txid: tx.txid(), index: 1 }.to_channel_id();
10594 nodes[0].node.force_close_broadcasting_latest_txn(&channel_id_1, &nodes[1].node.get_our_node_id()).unwrap();
10595 check_added_monitors(&nodes[0], 2);
10597 let mut monitor_updates = nodes[0].chain_monitor.monitor_updates.lock().unwrap();
10598 let monitor_updates_1 = monitor_updates.get(&channel_id_1).unwrap();
10599 assert_eq!(monitor_updates_1.len(), 1);
10600 assert_eq!(monitor_updates_1[0].update_id, CLOSED_CHANNEL_UPDATE_ID);
10601 let monitor_updates_2 = monitor_updates.get(&channel_id_2).unwrap();
10602 assert_eq!(monitor_updates_2.len(), 1);
10603 assert_eq!(monitor_updates_2[0].update_id, CLOSED_CHANNEL_UPDATE_ID);
10605 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
10606 match msg_events[0] {
10607 MessageSendEvent::HandleError { .. } => (),
10608 _ => panic!("Unexpected message."),
10611 // We broadcast the commitment transaction as part of the force-close.
10613 let broadcasted_txs = nodes[0].tx_broadcaster.txn_broadcast();
10614 assert_eq!(broadcasted_txs.len(), 1);
10615 assert!(broadcasted_txs[0].txid() != tx.txid());
10616 assert_eq!(broadcasted_txs[0].input.len(), 1);
10617 assert_eq!(broadcasted_txs[0].input[0].previous_output.txid, tx.txid());
10620 // All channels in the batch should close immediately.
10621 check_closed_events(&nodes[0], &[
10622 ExpectedCloseEvent {
10623 channel_id: Some(channel_id_1),
10624 discard_funding: true,
10625 ..Default::default()
10627 ExpectedCloseEvent {
10628 channel_id: Some(channel_id_2),
10629 discard_funding: true,
10630 ..Default::default()
10634 // Ensure the channels don't exist anymore.
10635 assert!(nodes[0].node.list_channels().is_empty());
10638 fn do_test_funding_and_commitment_tx_confirm_same_block(confirm_remote_commitment: bool) {
10639 // Tests that a node will forget the channel (when it only requires 1 confirmation) if the
10640 // funding and commitment transaction confirm in the same block.
10641 let chanmon_cfgs = create_chanmon_cfgs(2);
10642 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10643 let mut min_depth_1_block_cfg = test_default_channel_config();
10644 min_depth_1_block_cfg.channel_handshake_config.minimum_depth = 1;
10645 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(min_depth_1_block_cfg), Some(min_depth_1_block_cfg)]);
10646 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10648 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
10649 let chan_id = chain::transaction::OutPoint { txid: funding_tx.txid(), index: 0 }.to_channel_id();
10651 assert_eq!(nodes[0].node.list_channels().len(), 1);
10652 assert_eq!(nodes[1].node.list_channels().len(), 1);
10654 let (closing_node, other_node) = if confirm_remote_commitment {
10655 (&nodes[1], &nodes[0])
10657 (&nodes[0], &nodes[1])
10660 closing_node.node.force_close_broadcasting_latest_txn(&chan_id, &other_node.node.get_our_node_id()).unwrap();
10661 let mut msg_events = closing_node.node.get_and_clear_pending_msg_events();
10662 assert_eq!(msg_events.len(), 1);
10663 match msg_events.pop().unwrap() {
10664 MessageSendEvent::HandleError { action: msgs::ErrorAction::DisconnectPeer { .. }, .. } => {},
10665 _ => panic!("Unexpected event"),
10667 check_added_monitors(closing_node, 1);
10668 check_closed_event(closing_node, 1, ClosureReason::HolderForceClosed, false, &[other_node.node.get_our_node_id()], 1_000_000);
10670 let commitment_tx = {
10671 let mut txn = closing_node.tx_broadcaster.txn_broadcast();
10672 assert_eq!(txn.len(), 1);
10673 let commitment_tx = txn.pop().unwrap();
10674 check_spends!(commitment_tx, funding_tx);
10678 mine_transactions(&nodes[0], &[&funding_tx, &commitment_tx]);
10679 mine_transactions(&nodes[1], &[&funding_tx, &commitment_tx]);
10681 check_closed_broadcast(other_node, 1, true);
10682 check_added_monitors(other_node, 1);
10683 check_closed_event(other_node, 1, ClosureReason::CommitmentTxConfirmed, false, &[closing_node.node.get_our_node_id()], 1_000_000);
10685 assert!(nodes[0].node.list_channels().is_empty());
10686 assert!(nodes[1].node.list_channels().is_empty());
10690 fn test_funding_and_commitment_tx_confirm_same_block() {
10691 do_test_funding_and_commitment_tx_confirm_same_block(false);
10692 do_test_funding_and_commitment_tx_confirm_same_block(true);