1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
15 use crate::chain::{ChannelMonitorUpdateStatus, Confirm, Listen, Watch};
16 use crate::chain::chaininterface::LowerBoundedFeeEstimator;
17 use crate::chain::channelmonitor;
18 use crate::chain::channelmonitor::{CLOSED_CHANNEL_UPDATE_ID, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
19 use crate::chain::transaction::OutPoint;
20 use crate::sign::{ecdsa::EcdsaChannelSigner, EntropySource, OutputSpender, SignerProvider};
21 use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentPurpose, ClosureReason, HTLCDestination, PaymentFailureReason};
22 use crate::ln::types::{ChannelId, PaymentPreimage, PaymentSecret, PaymentHash};
23 use crate::ln::channel::{commitment_tx_base_weight, COMMITMENT_TX_WEIGHT_PER_HTLC, CONCURRENT_INBOUND_HTLC_FEE_BUFFER, FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE, MIN_AFFORDABLE_HTLC_COUNT, get_holder_selected_channel_reserve_satoshis, OutboundV1Channel, InboundV1Channel, COINBASE_MATURITY, ChannelPhase};
24 use crate::ln::channelmanager::{self, PaymentId, RAACommitmentOrder, PaymentSendFailure, RecipientOnionFields, BREAKDOWN_TIMEOUT, ENABLE_GOSSIP_TICKS, DISABLE_GOSSIP_TICKS, MIN_CLTV_EXPIRY_DELTA};
25 use crate::ln::channel::{DISCONNECT_PEER_AWAITING_RESPONSE_TICKS, ChannelError};
26 use crate::ln::{chan_utils, onion_utils};
27 use crate::ln::chan_utils::{OFFERED_HTLC_SCRIPT_WEIGHT, htlc_success_tx_weight, htlc_timeout_tx_weight, HTLCOutputInCommitment};
28 use crate::routing::gossip::{NetworkGraph, NetworkUpdate};
29 use crate::routing::router::{Path, PaymentParameters, Route, RouteHop, get_route, RouteParameters};
30 use crate::ln::features::{ChannelFeatures, ChannelTypeFeatures, NodeFeatures};
32 use crate::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction};
33 use crate::util::test_channel_signer::TestChannelSigner;
34 use crate::util::test_utils::{self, WatchtowerPersister};
35 use crate::util::errors::APIError;
36 use crate::util::ser::{Writeable, ReadableArgs};
37 use crate::util::string::UntrustedString;
38 use crate::util::config::{UserConfig, MaxDustHTLCExposure};
40 use bitcoin::hash_types::BlockHash;
41 use bitcoin::blockdata::locktime::absolute::LockTime;
42 use bitcoin::blockdata::script::{Builder, ScriptBuf};
43 use bitcoin::blockdata::opcodes;
44 use bitcoin::blockdata::constants::ChainHash;
45 use bitcoin::network::Network;
46 use bitcoin::{Amount, Sequence, Transaction, TxIn, TxOut, Witness};
47 use bitcoin::OutPoint as BitcoinOutPoint;
48 use bitcoin::transaction::Version;
50 use bitcoin::secp256k1::Secp256k1;
51 use bitcoin::secp256k1::{PublicKey,SecretKey};
54 use crate::prelude::*;
55 use alloc::collections::BTreeSet;
56 use core::iter::repeat;
57 use bitcoin::hashes::Hash;
58 use crate::sync::{Arc, Mutex, RwLock};
60 use crate::ln::functional_test_utils::*;
61 use crate::ln::chan_utils::CommitmentTransaction;
63 use super::channel::UNFUNDED_CHANNEL_AGE_LIMIT_TICKS;
66 fn test_channel_resumption_fail_post_funding() {
67 // If we fail to exchange funding with a peer prior to it disconnecting we'll resume the
68 // channel open on reconnect, however if we do exchange funding we do not currently support
69 // replaying it and here test that the channel closes.
70 let chanmon_cfgs = create_chanmon_cfgs(2);
71 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
72 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
73 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
75 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 0, 42, None, None).unwrap();
76 let open_chan = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
77 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan);
78 let accept_chan = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
79 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan);
81 let (temp_chan_id, tx, funding_output) =
82 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
83 let new_chan_id = ChannelId::v1_from_funding_outpoint(funding_output);
84 nodes[0].node.funding_transaction_generated(&temp_chan_id, &nodes[1].node.get_our_node_id(), tx).unwrap();
86 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
87 check_closed_events(&nodes[0], &[ExpectedCloseEvent::from_id_reason(new_chan_id, true, ClosureReason::DisconnectedPeer)]);
89 // After ddf75afd16 we'd panic on reconnection if we exchanged funding info, so test that
91 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
92 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
94 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events(), Vec::new());
98 fn test_insane_channel_opens() {
99 // Stand up a network of 2 nodes
100 use crate::ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
101 let mut cfg = UserConfig::default();
102 cfg.channel_handshake_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
103 let chanmon_cfgs = create_chanmon_cfgs(2);
104 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
105 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
106 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
108 // Instantiate channel parameters where we push the maximum msats given our
110 let channel_value_sat = 31337; // same as funding satoshis
111 let channel_reserve_satoshis = get_holder_selected_channel_reserve_satoshis(channel_value_sat, &cfg);
112 let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
114 // Have node0 initiate a channel to node1 with aforementioned parameters
115 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None, None).unwrap();
117 // Extract the channel open message from node0 to node1
118 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
120 // Test helper that asserts we get the correct error string given a mutator
121 // that supposedly makes the channel open message insane
122 let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
123 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &message_mutator(open_channel_message.clone()));
124 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
125 assert_eq!(msg_events.len(), 1);
126 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
127 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
129 &ErrorAction::SendErrorMessage { .. } => {
130 nodes[1].logger.assert_log_regex("lightning::ln::channelmanager", expected_regex, 1);
132 _ => panic!("unexpected event!"),
134 } else { assert!(false); }
137 use crate::ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
139 // Test all mutations that would make the channel open message insane
140 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.common_fields.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2; msg });
141 insane_open_helper(format!("Funding must be smaller than the total bitcoin supply. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS).as_str(), |mut msg| { msg.common_fields.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS; msg });
143 insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.common_fields.funding_satoshis + 1; msg });
145 insane_open_helper(r"push_msat \d+ was larger than channel amount minus reserve \(\d+\)", |mut msg| { msg.push_msat = (msg.common_fields.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
147 insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.common_fields.dust_limit_satoshis = msg.common_fields.funding_satoshis + 1 ; msg });
149 insane_open_helper(r"Minimum htlc value \(\d+\) was larger than full channel value \(\d+\)", |mut msg| { msg.common_fields.htlc_minimum_msat = (msg.common_fields.funding_satoshis - msg.channel_reserve_satoshis) * 1000; msg });
151 insane_open_helper("They wanted our payments to be delayed by a needlessly long period", |mut msg| { msg.common_fields.to_self_delay = MAX_LOCAL_BREAKDOWN_TIMEOUT + 1; msg });
153 insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.common_fields.max_accepted_htlcs = 0; msg });
155 insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.common_fields.max_accepted_htlcs = 484; msg });
159 fn test_funding_exceeds_no_wumbo_limit() {
160 // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
162 use crate::ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
163 let chanmon_cfgs = create_chanmon_cfgs(2);
164 let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
165 *node_cfgs[1].override_init_features.borrow_mut() = Some(channelmanager::provided_init_features(&test_default_channel_config()).clear_wumbo());
166 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
167 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
169 match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None, None) {
170 Err(APIError::APIMisuseError { err }) => {
171 assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
177 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
178 // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
179 // but only for them. Because some LSPs do it with some level of trust of the clients (for a
180 // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
181 // in normal testing, we test it explicitly here.
182 let chanmon_cfgs = create_chanmon_cfgs(2);
183 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
184 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
185 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
186 let default_config = UserConfig::default();
188 // Have node0 initiate a channel to node1 with aforementioned parameters
189 let mut push_amt = 100_000_000;
190 let feerate_per_kw = 253;
191 let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
192 push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(&channel_type_features) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
193 push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
195 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();
196 let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
197 if !send_from_initiator {
198 open_channel_message.channel_reserve_satoshis = 0;
199 open_channel_message.common_fields.max_htlc_value_in_flight_msat = 100_000_000;
201 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
203 // Extract the channel accept message from node1 to node0
204 let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
205 if send_from_initiator {
206 accept_channel_message.channel_reserve_satoshis = 0;
207 accept_channel_message.common_fields.max_htlc_value_in_flight_msat = 100_000_000;
209 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
211 let sender_node = if send_from_initiator { &nodes[1] } else { &nodes[0] };
212 let counterparty_node = if send_from_initiator { &nodes[0] } else { &nodes[1] };
213 let mut sender_node_per_peer_lock;
214 let mut sender_node_peer_state_lock;
216 let channel_phase = get_channel_ref!(sender_node, counterparty_node, sender_node_per_peer_lock, sender_node_peer_state_lock, temp_channel_id);
217 match channel_phase {
218 ChannelPhase::UnfundedInboundV1(_) | ChannelPhase::UnfundedOutboundV1(_) => {
219 let chan_context = channel_phase.context_mut();
220 chan_context.holder_selected_channel_reserve_satoshis = 0;
221 chan_context.holder_max_htlc_value_in_flight_msat = 100_000_000;
227 let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
228 let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
229 create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
231 // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
232 // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
233 if send_from_initiator {
234 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
235 // Note that for outbound channels we have to consider the commitment tx fee and the
236 // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
237 // well as an additional HTLC.
238 - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, &channel_type_features));
240 send_payment(&nodes[1], &[&nodes[0]], push_amt);
245 fn test_counterparty_no_reserve() {
246 do_test_counterparty_no_reserve(true);
247 do_test_counterparty_no_reserve(false);
251 fn test_async_inbound_update_fee() {
252 let chanmon_cfgs = create_chanmon_cfgs(2);
253 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
254 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
255 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
256 create_announced_chan_between_nodes(&nodes, 0, 1);
259 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
263 // send (1) commitment_signed -.
264 // <- update_add_htlc/commitment_signed
265 // send (2) RAA (awaiting remote revoke) -.
266 // (1) commitment_signed is delivered ->
267 // .- send (3) RAA (awaiting remote revoke)
268 // (2) RAA is delivered ->
269 // .- send (4) commitment_signed
270 // <- (3) RAA is delivered
271 // send (5) commitment_signed -.
272 // <- (4) commitment_signed is delivered
274 // (5) commitment_signed is delivered ->
276 // (6) RAA is delivered ->
278 // First nodes[0] generates an update_fee
280 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
283 nodes[0].node.timer_tick_occurred();
284 check_added_monitors!(nodes[0], 1);
286 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
287 assert_eq!(events_0.len(), 1);
288 let (update_msg, commitment_signed) = match events_0[0] { // (1)
289 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
290 (update_fee.as_ref(), commitment_signed)
292 _ => panic!("Unexpected event"),
295 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
297 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
298 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
299 nodes[1].node.send_payment_with_route(&route, our_payment_hash,
300 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
301 check_added_monitors!(nodes[1], 1);
303 let payment_event = {
304 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
305 assert_eq!(events_1.len(), 1);
306 SendEvent::from_event(events_1.remove(0))
308 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
309 assert_eq!(payment_event.msgs.len(), 1);
311 // ...now when the messages get delivered everyone should be happy
312 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
313 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
314 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
315 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
316 check_added_monitors!(nodes[0], 1);
318 // deliver(1), generate (3):
319 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
320 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
321 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
322 check_added_monitors!(nodes[1], 1);
324 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
325 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
326 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
327 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
328 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
329 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
330 assert!(bs_update.update_fee.is_none()); // (4)
331 check_added_monitors!(nodes[1], 1);
333 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
334 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
335 assert!(as_update.update_add_htlcs.is_empty()); // (5)
336 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
337 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
338 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
339 assert!(as_update.update_fee.is_none()); // (5)
340 check_added_monitors!(nodes[0], 1);
342 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
343 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
344 // only (6) so get_event_msg's assert(len == 1) passes
345 check_added_monitors!(nodes[0], 1);
347 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
348 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
349 check_added_monitors!(nodes[1], 1);
351 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
352 check_added_monitors!(nodes[0], 1);
354 let events_2 = nodes[0].node.get_and_clear_pending_events();
355 assert_eq!(events_2.len(), 1);
357 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
358 _ => panic!("Unexpected event"),
361 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
362 check_added_monitors!(nodes[1], 1);
366 fn test_update_fee_unordered_raa() {
367 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
368 // crash in an earlier version of the update_fee patch)
369 let chanmon_cfgs = create_chanmon_cfgs(2);
370 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
371 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
372 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
373 create_announced_chan_between_nodes(&nodes, 0, 1);
376 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
378 // First nodes[0] generates an update_fee
380 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
383 nodes[0].node.timer_tick_occurred();
384 check_added_monitors!(nodes[0], 1);
386 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
387 assert_eq!(events_0.len(), 1);
388 let update_msg = match events_0[0] { // (1)
389 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
392 _ => panic!("Unexpected event"),
395 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
397 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
398 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
399 nodes[1].node.send_payment_with_route(&route, our_payment_hash,
400 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
401 check_added_monitors!(nodes[1], 1);
403 let payment_event = {
404 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
405 assert_eq!(events_1.len(), 1);
406 SendEvent::from_event(events_1.remove(0))
408 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
409 assert_eq!(payment_event.msgs.len(), 1);
411 // ...now when the messages get delivered everyone should be happy
412 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
413 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
414 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
415 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
416 check_added_monitors!(nodes[0], 1);
418 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
419 check_added_monitors!(nodes[1], 1);
421 // We can't continue, sadly, because our (1) now has a bogus signature
425 fn test_multi_flight_update_fee() {
426 let chanmon_cfgs = create_chanmon_cfgs(2);
427 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
428 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
429 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
430 create_announced_chan_between_nodes(&nodes, 0, 1);
433 // update_fee/commitment_signed ->
434 // .- send (1) RAA and (2) commitment_signed
435 // update_fee (never committed) ->
437 // We have to manually generate the above update_fee, it is allowed by the protocol but we
438 // don't track which updates correspond to which revoke_and_ack responses so we're in
439 // AwaitingRAA mode and will not generate the update_fee yet.
440 // <- (1) RAA delivered
441 // (3) is generated and send (4) CS -.
442 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
443 // know the per_commitment_point to use for it.
444 // <- (2) commitment_signed delivered
446 // B should send no response here
447 // (4) commitment_signed delivered ->
448 // <- RAA/commitment_signed delivered
451 // First nodes[0] generates an update_fee
454 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
455 initial_feerate = *feerate_lock;
456 *feerate_lock = initial_feerate + 20;
458 nodes[0].node.timer_tick_occurred();
459 check_added_monitors!(nodes[0], 1);
461 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
462 assert_eq!(events_0.len(), 1);
463 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
464 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
465 (update_fee.as_ref().unwrap(), commitment_signed)
467 _ => panic!("Unexpected event"),
470 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
471 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
472 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
473 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
474 check_added_monitors!(nodes[1], 1);
476 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
479 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
480 *feerate_lock = initial_feerate + 40;
482 nodes[0].node.timer_tick_occurred();
483 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
484 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
486 // Create the (3) update_fee message that nodes[0] will generate before it does...
487 let mut update_msg_2 = msgs::UpdateFee {
488 channel_id: update_msg_1.channel_id.clone(),
489 feerate_per_kw: (initial_feerate + 30) as u32,
492 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
494 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
496 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
498 // Deliver (1), generating (3) and (4)
499 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
500 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
501 check_added_monitors!(nodes[0], 1);
502 assert!(as_second_update.update_add_htlcs.is_empty());
503 assert!(as_second_update.update_fulfill_htlcs.is_empty());
504 assert!(as_second_update.update_fail_htlcs.is_empty());
505 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
506 // Check that the update_fee newly generated matches what we delivered:
507 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
508 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
510 // Deliver (2) commitment_signed
511 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
512 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
513 check_added_monitors!(nodes[0], 1);
514 // No commitment_signed so get_event_msg's assert(len == 1) passes
516 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
517 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
518 check_added_monitors!(nodes[1], 1);
521 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
522 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
523 check_added_monitors!(nodes[1], 1);
525 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
526 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
527 check_added_monitors!(nodes[0], 1);
529 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
530 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
531 // No commitment_signed so get_event_msg's assert(len == 1) passes
532 check_added_monitors!(nodes[0], 1);
534 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
535 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
536 check_added_monitors!(nodes[1], 1);
539 fn do_test_sanity_on_in_flight_opens(steps: u8) {
540 // Previously, we had issues deserializing channels when we hadn't connected the first block
541 // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
542 // serialization round-trips and simply do steps towards opening a channel and then drop the
545 let chanmon_cfgs = create_chanmon_cfgs(2);
546 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
547 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
548 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
550 if steps & 0b1000_0000 != 0{
551 let block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
552 connect_block(&nodes[0], &block);
553 connect_block(&nodes[1], &block);
556 if steps & 0x0f == 0 { return; }
557 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
558 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
560 if steps & 0x0f == 1 { return; }
561 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
562 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
564 if steps & 0x0f == 2 { return; }
565 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
567 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
569 if steps & 0x0f == 3 { return; }
570 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
571 check_added_monitors!(nodes[0], 0);
572 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
574 if steps & 0x0f == 4 { return; }
575 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
577 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
578 assert_eq!(added_monitors.len(), 1);
579 assert_eq!(added_monitors[0].0, funding_output);
580 added_monitors.clear();
582 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
584 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
586 if steps & 0x0f == 5 { return; }
587 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
589 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
590 assert_eq!(added_monitors.len(), 1);
591 assert_eq!(added_monitors[0].0, funding_output);
592 added_monitors.clear();
595 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
596 let events_4 = nodes[0].node.get_and_clear_pending_events();
597 assert_eq!(events_4.len(), 0);
599 if steps & 0x0f == 6 { return; }
600 create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
602 if steps & 0x0f == 7 { return; }
603 confirm_transaction_at(&nodes[0], &tx, 2);
604 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
605 create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
606 expect_channel_ready_event(&nodes[0], &nodes[1].node.get_our_node_id());
610 fn test_sanity_on_in_flight_opens() {
611 do_test_sanity_on_in_flight_opens(0);
612 do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
613 do_test_sanity_on_in_flight_opens(1);
614 do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
615 do_test_sanity_on_in_flight_opens(2);
616 do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
617 do_test_sanity_on_in_flight_opens(3);
618 do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
619 do_test_sanity_on_in_flight_opens(4);
620 do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
621 do_test_sanity_on_in_flight_opens(5);
622 do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
623 do_test_sanity_on_in_flight_opens(6);
624 do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
625 do_test_sanity_on_in_flight_opens(7);
626 do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
627 do_test_sanity_on_in_flight_opens(8);
628 do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
632 fn test_update_fee_vanilla() {
633 let chanmon_cfgs = create_chanmon_cfgs(2);
634 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
635 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
636 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
637 create_announced_chan_between_nodes(&nodes, 0, 1);
640 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
643 nodes[0].node.timer_tick_occurred();
644 check_added_monitors!(nodes[0], 1);
646 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
647 assert_eq!(events_0.len(), 1);
648 let (update_msg, commitment_signed) = match events_0[0] {
649 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 } } => {
650 (update_fee.as_ref(), commitment_signed)
652 _ => panic!("Unexpected event"),
654 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
656 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
657 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
658 check_added_monitors!(nodes[1], 1);
660 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
661 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
662 check_added_monitors!(nodes[0], 1);
664 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
665 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
666 // No commitment_signed so get_event_msg's assert(len == 1) passes
667 check_added_monitors!(nodes[0], 1);
669 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
670 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
671 check_added_monitors!(nodes[1], 1);
675 fn test_update_fee_that_funder_cannot_afford() {
676 let chanmon_cfgs = create_chanmon_cfgs(2);
677 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
678 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
679 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
680 let channel_value = 5000;
682 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000);
683 let channel_id = chan.2;
684 let secp_ctx = Secp256k1::new();
685 let default_config = UserConfig::default();
686 let bs_channel_reserve_sats = get_holder_selected_channel_reserve_satoshis(channel_value, &default_config);
688 let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
690 // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
691 // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
692 // calculate two different feerates here - the expected local limit as well as the expected
694 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;
695 let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(&channel_type_features)) as u32;
697 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
698 *feerate_lock = feerate;
700 nodes[0].node.timer_tick_occurred();
701 check_added_monitors!(nodes[0], 1);
702 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
704 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
706 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
708 // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
710 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
712 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
713 assert_eq!(commitment_tx.output.len(), 2);
714 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, &channel_type_features) / 1000;
715 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value.to_sat());
716 actual_fee = channel_value - actual_fee;
717 assert_eq!(total_fee, actual_fee);
721 // Increment the feerate by a small constant, accounting for rounding errors
722 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
725 nodes[0].node.timer_tick_occurred();
726 nodes[0].logger.assert_log("lightning::ln::channel", format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
727 check_added_monitors!(nodes[0], 0);
729 const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
731 // Get the TestChannelSigner for each channel, which will be used to (1) get the keys
732 // needed to sign the new commitment tx and (2) sign the new commitment tx.
733 let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
734 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
735 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
736 let local_chan = chan_lock.channel_by_id.get(&chan.2).map(
737 |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
738 ).flatten().unwrap();
739 let chan_signer = local_chan.get_signer();
740 let pubkeys = chan_signer.as_ref().pubkeys();
741 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
742 pubkeys.funding_pubkey)
744 let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
745 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
746 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
747 let remote_chan = chan_lock.channel_by_id.get(&chan.2).map(
748 |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
749 ).flatten().unwrap();
750 let chan_signer = remote_chan.get_signer();
751 let pubkeys = chan_signer.as_ref().pubkeys();
752 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
753 chan_signer.as_ref().get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
754 pubkeys.funding_pubkey)
757 // Assemble the set of keys we can use for signatures for our commitment_signed message.
758 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
759 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
762 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
763 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
764 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).map(
765 |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
766 ).flatten().unwrap();
767 let local_chan_signer = local_chan.get_signer();
768 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
769 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
770 INITIAL_COMMITMENT_NUMBER - 1,
772 channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, &channel_type_features) / 1000,
773 local_funding, remote_funding,
774 commit_tx_keys.clone(),
775 non_buffer_feerate + 4,
777 &local_chan.context.channel_transaction_parameters.as_counterparty_broadcastable()
779 local_chan_signer.as_ecdsa().unwrap().sign_counterparty_commitment(&commitment_tx, Vec::new(), Vec::new(), &secp_ctx).unwrap()
782 let commit_signed_msg = msgs::CommitmentSigned {
785 htlc_signatures: res.1,
788 partial_signature_with_nonce: None,
791 let update_fee = msgs::UpdateFee {
793 feerate_per_kw: non_buffer_feerate + 4,
796 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
798 //While producing the commitment_signed response after handling a received update_fee request the
799 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
800 //Should produce and error.
801 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
802 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Funding remote cannot afford proposed new fee", 3);
803 check_added_monitors!(nodes[1], 1);
804 check_closed_broadcast!(nodes[1], true);
805 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") },
806 [nodes[0].node.get_our_node_id()], channel_value);
810 fn test_update_fee_with_fundee_update_add_htlc() {
811 let chanmon_cfgs = create_chanmon_cfgs(2);
812 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
813 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
814 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
815 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
818 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
821 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
824 nodes[0].node.timer_tick_occurred();
825 check_added_monitors!(nodes[0], 1);
827 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
828 assert_eq!(events_0.len(), 1);
829 let (update_msg, commitment_signed) = match events_0[0] {
830 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 } } => {
831 (update_fee.as_ref(), commitment_signed)
833 _ => panic!("Unexpected event"),
835 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
836 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
837 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
838 check_added_monitors!(nodes[1], 1);
840 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
842 // nothing happens since node[1] is in AwaitingRemoteRevoke
843 nodes[1].node.send_payment_with_route(&route, our_payment_hash,
844 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
846 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
847 assert_eq!(added_monitors.len(), 0);
848 added_monitors.clear();
850 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
851 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
852 // node[1] has nothing to do
854 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
855 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
856 check_added_monitors!(nodes[0], 1);
858 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
859 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
860 // No commitment_signed so get_event_msg's assert(len == 1) passes
861 check_added_monitors!(nodes[0], 1);
862 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
863 check_added_monitors!(nodes[1], 1);
864 // AwaitingRemoteRevoke ends here
866 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
867 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
868 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
869 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
870 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
871 assert_eq!(commitment_update.update_fee.is_none(), true);
873 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
874 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
875 check_added_monitors!(nodes[0], 1);
876 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
878 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
879 check_added_monitors!(nodes[1], 1);
880 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
882 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
883 check_added_monitors!(nodes[1], 1);
884 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
885 // No commitment_signed so get_event_msg's assert(len == 1) passes
887 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
888 check_added_monitors!(nodes[0], 1);
889 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
891 expect_pending_htlcs_forwardable!(nodes[0]);
893 let events = nodes[0].node.get_and_clear_pending_events();
894 assert_eq!(events.len(), 1);
896 Event::PaymentClaimable { .. } => { },
897 _ => panic!("Unexpected event"),
900 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
902 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
903 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
904 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
905 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyInitiatedCooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
906 check_closed_event!(nodes[1], 1, ClosureReason::LocallyInitiatedCooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
910 fn test_update_fee() {
911 let chanmon_cfgs = create_chanmon_cfgs(2);
912 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
913 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
914 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
915 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
916 let channel_id = chan.2;
919 // (1) update_fee/commitment_signed ->
920 // <- (2) revoke_and_ack
921 // .- send (3) commitment_signed
922 // (4) update_fee/commitment_signed ->
923 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
924 // <- (3) commitment_signed delivered
925 // send (6) revoke_and_ack -.
926 // <- (5) deliver revoke_and_ack
927 // (6) deliver revoke_and_ack ->
928 // .- send (7) commitment_signed in response to (4)
929 // <- (7) deliver commitment_signed
932 // Create and deliver (1)...
935 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
936 feerate = *feerate_lock;
937 *feerate_lock = feerate + 20;
939 nodes[0].node.timer_tick_occurred();
940 check_added_monitors!(nodes[0], 1);
942 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
943 assert_eq!(events_0.len(), 1);
944 let (update_msg, commitment_signed) = match events_0[0] {
945 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 } } => {
946 (update_fee.as_ref(), commitment_signed)
948 _ => panic!("Unexpected event"),
950 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
952 // Generate (2) and (3):
953 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
954 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
955 check_added_monitors!(nodes[1], 1);
958 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
959 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
960 check_added_monitors!(nodes[0], 1);
962 // Create and deliver (4)...
964 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
965 *feerate_lock = feerate + 30;
967 nodes[0].node.timer_tick_occurred();
968 check_added_monitors!(nodes[0], 1);
969 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
970 assert_eq!(events_0.len(), 1);
971 let (update_msg, commitment_signed) = match events_0[0] {
972 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 } } => {
973 (update_fee.as_ref(), commitment_signed)
975 _ => panic!("Unexpected event"),
978 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
979 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
980 check_added_monitors!(nodes[1], 1);
982 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
983 // No commitment_signed so get_event_msg's assert(len == 1) passes
985 // Handle (3), creating (6):
986 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
987 check_added_monitors!(nodes[0], 1);
988 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
989 // No commitment_signed so get_event_msg's assert(len == 1) passes
992 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
993 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
994 check_added_monitors!(nodes[0], 1);
996 // Deliver (6), creating (7):
997 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
998 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
999 assert!(commitment_update.update_add_htlcs.is_empty());
1000 assert!(commitment_update.update_fulfill_htlcs.is_empty());
1001 assert!(commitment_update.update_fail_htlcs.is_empty());
1002 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
1003 assert!(commitment_update.update_fee.is_none());
1004 check_added_monitors!(nodes[1], 1);
1007 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
1008 check_added_monitors!(nodes[0], 1);
1009 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1010 // No commitment_signed so get_event_msg's assert(len == 1) passes
1012 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
1013 check_added_monitors!(nodes[1], 1);
1014 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1016 assert_eq!(get_feerate!(nodes[0], nodes[1], channel_id), feerate + 30);
1017 assert_eq!(get_feerate!(nodes[1], nodes[0], channel_id), feerate + 30);
1018 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
1019 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyInitiatedCooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1020 check_closed_event!(nodes[1], 1, ClosureReason::LocallyInitiatedCooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
1024 fn fake_network_test() {
1025 // Simple test which builds a network of ChannelManagers, connects them to each other, and
1026 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
1027 let chanmon_cfgs = create_chanmon_cfgs(4);
1028 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1029 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1030 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1032 // Create some initial channels
1033 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1034 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1035 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
1037 // Rebalance the network a bit by relaying one payment through all the channels...
1038 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1039 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1040 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1041 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1043 // Send some more payments
1044 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
1045 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
1046 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
1048 // Test failure packets
1049 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1050 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1052 // Add a new channel that skips 3
1053 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
1055 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
1056 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
1057 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1058 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1059 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1060 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1061 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1063 // Do some rebalance loop payments, simultaneously
1064 let mut hops = Vec::with_capacity(3);
1065 hops.push(RouteHop {
1066 pubkey: nodes[2].node.get_our_node_id(),
1067 node_features: NodeFeatures::empty(),
1068 short_channel_id: chan_2.0.contents.short_channel_id,
1069 channel_features: ChannelFeatures::empty(),
1071 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32,
1072 maybe_announced_channel: true,
1074 hops.push(RouteHop {
1075 pubkey: nodes[3].node.get_our_node_id(),
1076 node_features: NodeFeatures::empty(),
1077 short_channel_id: chan_3.0.contents.short_channel_id,
1078 channel_features: ChannelFeatures::empty(),
1080 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32,
1081 maybe_announced_channel: true,
1083 hops.push(RouteHop {
1084 pubkey: nodes[1].node.get_our_node_id(),
1085 node_features: nodes[1].node.node_features(),
1086 short_channel_id: chan_4.0.contents.short_channel_id,
1087 channel_features: nodes[1].node.channel_features(),
1089 cltv_expiry_delta: TEST_FINAL_CLTV,
1090 maybe_announced_channel: true,
1092 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;
1093 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;
1094 let payment_preimage_1 = send_along_route(&nodes[1],
1095 Route { paths: vec![Path { hops, blinded_tail: None }], route_params: None },
1096 &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1098 let mut hops = Vec::with_capacity(3);
1099 hops.push(RouteHop {
1100 pubkey: nodes[3].node.get_our_node_id(),
1101 node_features: NodeFeatures::empty(),
1102 short_channel_id: chan_4.0.contents.short_channel_id,
1103 channel_features: ChannelFeatures::empty(),
1105 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32,
1106 maybe_announced_channel: true,
1108 hops.push(RouteHop {
1109 pubkey: nodes[2].node.get_our_node_id(),
1110 node_features: NodeFeatures::empty(),
1111 short_channel_id: chan_3.0.contents.short_channel_id,
1112 channel_features: ChannelFeatures::empty(),
1114 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32,
1115 maybe_announced_channel: true,
1117 hops.push(RouteHop {
1118 pubkey: nodes[1].node.get_our_node_id(),
1119 node_features: nodes[1].node.node_features(),
1120 short_channel_id: chan_2.0.contents.short_channel_id,
1121 channel_features: nodes[1].node.channel_features(),
1123 cltv_expiry_delta: TEST_FINAL_CLTV,
1124 maybe_announced_channel: true,
1126 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;
1127 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;
1128 let payment_hash_2 = send_along_route(&nodes[1],
1129 Route { paths: vec![Path { hops, blinded_tail: None }], route_params: None },
1130 &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1132 // Claim the rebalances...
1133 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1134 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1136 // Close down the channels...
1137 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1138 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyInitiatedCooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1139 check_closed_event!(nodes[1], 1, ClosureReason::LocallyInitiatedCooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
1140 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1141 check_closed_event!(nodes[1], 1, ClosureReason::LocallyInitiatedCooperativeClosure, [nodes[2].node.get_our_node_id()], 100000);
1142 check_closed_event!(nodes[2], 1, ClosureReason::CounterpartyInitiatedCooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1143 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1144 check_closed_event!(nodes[2], 1, ClosureReason::CounterpartyInitiatedCooperativeClosure, [nodes[3].node.get_our_node_id()], 100000);
1145 check_closed_event!(nodes[3], 1, ClosureReason::LocallyInitiatedCooperativeClosure, [nodes[2].node.get_our_node_id()], 100000);
1146 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1147 check_closed_event!(nodes[1], 1, ClosureReason::LocallyInitiatedCooperativeClosure, [nodes[3].node.get_our_node_id()], 100000);
1148 check_closed_event!(nodes[3], 1, ClosureReason::CounterpartyInitiatedCooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1152 fn holding_cell_htlc_counting() {
1153 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1154 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1155 // commitment dance rounds.
1156 let chanmon_cfgs = create_chanmon_cfgs(3);
1157 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1158 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1159 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1160 create_announced_chan_between_nodes(&nodes, 0, 1);
1161 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1163 // Fetch a route in advance as we will be unable to once we're unable to send.
1164 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1166 let mut payments = Vec::new();
1168 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1169 nodes[1].node.send_payment_with_route(&route, payment_hash,
1170 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1171 payments.push((payment_preimage, payment_hash));
1173 check_added_monitors!(nodes[1], 1);
1175 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1176 assert_eq!(events.len(), 1);
1177 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1178 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1180 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1181 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1184 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, payment_hash_1,
1185 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)
1186 ), true, APIError::ChannelUnavailable { .. }, {});
1187 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1190 // This should also be true if we try to forward a payment.
1191 let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1193 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1194 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1195 check_added_monitors!(nodes[0], 1);
1198 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1199 assert_eq!(events.len(), 1);
1200 let payment_event = SendEvent::from_event(events.pop().unwrap());
1201 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1203 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1204 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1205 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1206 // fails), the second will process the resulting failure and fail the HTLC backward.
1207 expect_pending_htlcs_forwardable!(nodes[1]);
1208 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 }]);
1209 check_added_monitors!(nodes[1], 1);
1211 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1212 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1213 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1215 expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1217 // Now forward all the pending HTLCs and claim them back
1218 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1219 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1220 check_added_monitors!(nodes[2], 1);
1222 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1223 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1224 check_added_monitors!(nodes[1], 1);
1225 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1227 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1228 check_added_monitors!(nodes[1], 1);
1229 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1231 for ref update in as_updates.update_add_htlcs.iter() {
1232 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1234 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1235 check_added_monitors!(nodes[2], 1);
1236 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1237 check_added_monitors!(nodes[2], 1);
1238 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1240 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1241 check_added_monitors!(nodes[1], 1);
1242 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1243 check_added_monitors!(nodes[1], 1);
1244 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1246 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1247 check_added_monitors!(nodes[2], 1);
1249 expect_pending_htlcs_forwardable!(nodes[2]);
1251 let events = nodes[2].node.get_and_clear_pending_events();
1252 assert_eq!(events.len(), payments.len());
1253 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1255 &Event::PaymentClaimable { ref payment_hash, .. } => {
1256 assert_eq!(*payment_hash, *hash);
1258 _ => panic!("Unexpected event"),
1262 for (preimage, _) in payments.drain(..) {
1263 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1266 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1270 fn duplicate_htlc_test() {
1271 // Test that we accept duplicate payment_hash HTLCs across the network and that
1272 // claiming/failing them are all separate and don't affect each other
1273 let chanmon_cfgs = create_chanmon_cfgs(6);
1274 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1275 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1276 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1278 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1279 create_announced_chan_between_nodes(&nodes, 0, 3);
1280 create_announced_chan_between_nodes(&nodes, 1, 3);
1281 create_announced_chan_between_nodes(&nodes, 2, 3);
1282 create_announced_chan_between_nodes(&nodes, 3, 4);
1283 create_announced_chan_between_nodes(&nodes, 3, 5);
1285 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1287 *nodes[0].network_payment_count.borrow_mut() -= 1;
1288 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1290 *nodes[0].network_payment_count.borrow_mut() -= 1;
1291 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1293 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1294 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1295 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1299 fn test_duplicate_htlc_different_direction_onchain() {
1300 // Test that ChannelMonitor doesn't generate 2 preimage txn
1301 // when we have 2 HTLCs with same preimage that go across a node
1302 // in opposite directions, even with the same payment secret.
1303 let chanmon_cfgs = create_chanmon_cfgs(2);
1304 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1305 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1306 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1308 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1311 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1313 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1315 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1316 let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
1317 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1319 // Provide preimage to node 0 by claiming payment
1320 nodes[0].node.claim_funds(payment_preimage);
1321 expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1322 check_added_monitors!(nodes[0], 1);
1324 // Broadcast node 1 commitment txn
1325 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1327 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1328 let mut has_both_htlcs = 0; // check htlcs match ones committed
1329 for outp in remote_txn[0].output.iter() {
1330 if outp.value.to_sat() == 800_000 / 1000 {
1331 has_both_htlcs += 1;
1332 } else if outp.value.to_sat() == 900_000 / 1000 {
1333 has_both_htlcs += 1;
1336 assert_eq!(has_both_htlcs, 2);
1338 mine_transaction(&nodes[0], &remote_txn[0]);
1339 check_added_monitors!(nodes[0], 1);
1340 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
1341 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
1343 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1344 assert_eq!(claim_txn.len(), 3);
1346 check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1347 check_spends!(claim_txn[1], remote_txn[0]);
1348 check_spends!(claim_txn[2], remote_txn[0]);
1349 let preimage_tx = &claim_txn[0];
1350 let (preimage_bump_tx, timeout_tx) = if claim_txn[1].input[0].previous_output == preimage_tx.input[0].previous_output {
1351 (&claim_txn[1], &claim_txn[2])
1353 (&claim_txn[2], &claim_txn[1])
1356 assert_eq!(preimage_tx.input.len(), 1);
1357 assert_eq!(preimage_bump_tx.input.len(), 1);
1359 assert_eq!(preimage_tx.input.len(), 1);
1360 assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1361 assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value.to_sat(), 800);
1363 assert_eq!(timeout_tx.input.len(), 1);
1364 assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1365 check_spends!(timeout_tx, remote_txn[0]);
1366 assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value.to_sat(), 900);
1368 let events = nodes[0].node.get_and_clear_pending_msg_events();
1369 assert_eq!(events.len(), 3);
1372 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1373 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::DisconnectPeer { ref msg } } => {
1374 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1375 assert_eq!(msg.as_ref().unwrap().data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1377 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, .. } } => {
1378 assert!(update_add_htlcs.is_empty());
1379 assert!(update_fail_htlcs.is_empty());
1380 assert_eq!(update_fulfill_htlcs.len(), 1);
1381 assert!(update_fail_malformed_htlcs.is_empty());
1382 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1384 _ => panic!("Unexpected event"),
1390 fn test_basic_channel_reserve() {
1391 let chanmon_cfgs = create_chanmon_cfgs(2);
1392 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1393 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1394 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1395 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1397 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1398 let channel_reserve = chan_stat.channel_reserve_msat;
1400 // The 2* and +1 are for the fee spike reserve.
1401 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));
1402 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1403 let (mut route, our_payment_hash, _, our_payment_secret) =
1404 get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
1405 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1406 let err = nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1407 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1409 PaymentSendFailure::AllFailedResendSafe(ref fails) => {
1410 if let &APIError::ChannelUnavailable { .. } = &fails[0] {}
1411 else { panic!("Unexpected error variant"); }
1413 _ => panic!("Unexpected error variant"),
1415 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1417 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1421 fn test_fee_spike_violation_fails_htlc() {
1422 let chanmon_cfgs = create_chanmon_cfgs(2);
1423 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1424 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1425 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1426 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1428 let (mut route, payment_hash, _, payment_secret) =
1429 get_route_and_payment_hash!(nodes[0], nodes[1], 3460000);
1430 route.paths[0].hops[0].fee_msat += 1;
1431 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1432 let secp_ctx = Secp256k1::new();
1433 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1435 let cur_height = nodes[1].node.best_block.read().unwrap().height + 1;
1437 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1438 let recipient_onion_fields = RecipientOnionFields::secret_only(payment_secret);
1439 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1440 3460001, &recipient_onion_fields, cur_height, &None).unwrap();
1441 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1442 let msg = msgs::UpdateAddHTLC {
1445 amount_msat: htlc_msat,
1446 payment_hash: payment_hash,
1447 cltv_expiry: htlc_cltv,
1448 onion_routing_packet: onion_packet,
1449 skimmed_fee_msat: None,
1450 blinding_point: None,
1453 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1455 // Now manually create the commitment_signed message corresponding to the update_add
1456 // nodes[0] just sent. In the code for construction of this message, "local" refers
1457 // to the sender of the message, and "remote" refers to the receiver.
1459 let feerate_per_kw = get_feerate!(nodes[0], nodes[1], chan.2);
1461 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1463 // Get the TestChannelSigner for each channel, which will be used to (1) get the keys
1464 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1465 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1466 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1467 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1468 let local_chan = chan_lock.channel_by_id.get(&chan.2).map(
1469 |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
1470 ).flatten().unwrap();
1471 let chan_signer = local_chan.get_signer();
1472 // Make the signer believe we validated another commitment, so we can release the secret
1473 chan_signer.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
1475 let pubkeys = chan_signer.as_ref().pubkeys();
1476 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1477 chan_signer.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1478 chan_signer.as_ref().get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1479 chan_signer.as_ref().pubkeys().funding_pubkey)
1481 let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1482 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
1483 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
1484 let remote_chan = chan_lock.channel_by_id.get(&chan.2).map(
1485 |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
1486 ).flatten().unwrap();
1487 let chan_signer = remote_chan.get_signer();
1488 let pubkeys = chan_signer.as_ref().pubkeys();
1489 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1490 chan_signer.as_ref().get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1491 chan_signer.as_ref().pubkeys().funding_pubkey)
1494 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1495 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1496 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
1498 // Build the remote commitment transaction so we can sign it, and then later use the
1499 // signature for the commitment_signed message.
1500 let local_chan_balance = 1313;
1502 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1504 amount_msat: 3460001,
1505 cltv_expiry: htlc_cltv,
1507 transaction_output_index: Some(1),
1510 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1513 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1514 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1515 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).map(
1516 |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
1517 ).flatten().unwrap();
1518 let local_chan_signer = local_chan.get_signer();
1519 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1523 local_funding, remote_funding,
1524 commit_tx_keys.clone(),
1526 &mut vec![(accepted_htlc_info, ())],
1527 &local_chan.context.channel_transaction_parameters.as_counterparty_broadcastable()
1529 local_chan_signer.as_ecdsa().unwrap().sign_counterparty_commitment(&commitment_tx, Vec::new(), Vec::new(), &secp_ctx).unwrap()
1532 let commit_signed_msg = msgs::CommitmentSigned {
1535 htlc_signatures: res.1,
1538 partial_signature_with_nonce: None,
1541 // Send the commitment_signed message to the nodes[1].
1542 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1543 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1545 // Send the RAA to nodes[1].
1546 let raa_msg = msgs::RevokeAndACK {
1548 per_commitment_secret: local_secret,
1549 next_per_commitment_point: next_local_point,
1551 next_local_nonce: None,
1553 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1555 let events = nodes[1].node.get_and_clear_pending_msg_events();
1556 assert_eq!(events.len(), 1);
1557 // Make sure the HTLC failed in the way we expect.
1559 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1560 assert_eq!(update_fail_htlcs.len(), 1);
1561 update_fail_htlcs[0].clone()
1563 _ => panic!("Unexpected event"),
1565 nodes[1].logger.assert_log("lightning::ln::channel",
1566 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", raa_msg.channel_id), 1);
1568 check_added_monitors!(nodes[1], 2);
1572 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1573 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1574 // Set the fee rate for the channel very high, to the point where the fundee
1575 // sending any above-dust amount would result in a channel reserve violation.
1576 // In this test we check that we would be prevented from sending an HTLC in
1578 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1579 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1580 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1581 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1582 let default_config = UserConfig::default();
1583 let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1585 let mut push_amt = 100_000_000;
1586 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1588 push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1590 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1592 // Fetch a route in advance as we will be unable to once we're unable to send.
1593 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1594 // Sending exactly enough to hit the reserve amount should be accepted
1595 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1596 route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1599 // However one more HTLC should be significantly over the reserve amount and fail.
1600 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1601 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1602 ), true, APIError::ChannelUnavailable { .. }, {});
1603 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1607 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1608 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1609 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1610 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1611 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1612 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1613 let default_config = UserConfig::default();
1614 let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1616 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1617 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1618 // transaction fee with 0 HTLCs (183 sats)).
1619 let mut push_amt = 100_000_000;
1620 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1621 push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1622 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1624 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1625 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1626 route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1629 let (mut route, payment_hash, _, payment_secret) =
1630 get_route_and_payment_hash!(nodes[1], nodes[0], 1000);
1631 route.paths[0].hops[0].fee_msat = 700_000;
1632 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1633 let secp_ctx = Secp256k1::new();
1634 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1635 let cur_height = nodes[1].node.best_block.read().unwrap().height + 1;
1636 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1637 let recipient_onion_fields = RecipientOnionFields::secret_only(payment_secret);
1638 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1639 700_000, &recipient_onion_fields, cur_height, &None).unwrap();
1640 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1641 let msg = msgs::UpdateAddHTLC {
1643 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1644 amount_msat: htlc_msat,
1645 payment_hash: payment_hash,
1646 cltv_expiry: htlc_cltv,
1647 onion_routing_packet: onion_packet,
1648 skimmed_fee_msat: None,
1649 blinding_point: None,
1652 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1653 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1654 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value", 3);
1655 assert_eq!(nodes[0].node.list_channels().len(), 0);
1656 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1657 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1658 check_added_monitors!(nodes[0], 1);
1659 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() },
1660 [nodes[1].node.get_our_node_id()], 100000);
1664 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1665 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1666 // calculating our commitment transaction fee (this was previously broken).
1667 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1668 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1670 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1671 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1672 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1673 let default_config = UserConfig::default();
1674 let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1676 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1677 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1678 // transaction fee with 0 HTLCs (183 sats)).
1679 let mut push_amt = 100_000_000;
1680 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1681 push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1682 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt);
1684 let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1685 + feerate_per_kw as u64 * htlc_success_tx_weight(&channel_type_features) / 1000 * 1000 - 1;
1686 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1687 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1688 // commitment transaction fee.
1689 route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1691 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1692 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1693 route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1696 // One more than the dust amt should fail, however.
1697 let (mut route, our_payment_hash, _, our_payment_secret) =
1698 get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt);
1699 route.paths[0].hops[0].fee_msat += 1;
1700 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1701 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1702 ), true, APIError::ChannelUnavailable { .. }, {});
1706 fn test_chan_init_feerate_unaffordability() {
1707 // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1708 // channel reserve and feerate requirements.
1709 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1710 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1711 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1712 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1713 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1714 let default_config = UserConfig::default();
1715 let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1717 // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1719 let mut push_amt = 100_000_000;
1720 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1721 assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None, None).unwrap_err(),
1722 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1724 // During open, we don't have a "counterparty channel reserve" to check against, so that
1725 // requirement only comes into play on the open_channel handling side.
1726 push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1727 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None, None).unwrap();
1728 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1729 open_channel_msg.push_msat += 1;
1730 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
1732 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1733 assert_eq!(msg_events.len(), 1);
1734 match msg_events[0] {
1735 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1736 assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1738 _ => panic!("Unexpected event"),
1743 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1744 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1745 // calculating our counterparty's commitment transaction fee (this was previously broken).
1746 let chanmon_cfgs = create_chanmon_cfgs(2);
1747 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1748 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1749 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1750 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000);
1752 let payment_amt = 46000; // Dust amount
1753 // In the previous code, these first four payments would succeed.
1754 route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1755 route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1756 route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1757 route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1759 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1760 route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1761 route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1762 route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1763 route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1764 route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1766 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1767 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1768 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1769 route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1773 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1774 let chanmon_cfgs = create_chanmon_cfgs(3);
1775 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1776 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1777 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1778 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1779 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
1782 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1783 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1784 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
1785 let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
1787 // Add a 2* and +1 for the fee spike reserve.
1788 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features);
1789 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;
1790 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1792 // Add a pending HTLC.
1793 let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1794 let payment_event_1 = {
1795 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1796 RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1797 check_added_monitors!(nodes[0], 1);
1799 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1800 assert_eq!(events.len(), 1);
1801 SendEvent::from_event(events.remove(0))
1803 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1805 // Attempt to trigger a channel reserve violation --> payment failure.
1806 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, &channel_type_features);
1807 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;
1808 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1809 let mut route_2 = route_1.clone();
1810 route_2.paths[0].hops.last_mut().unwrap().fee_msat = amt_msat_2;
1812 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1813 let secp_ctx = Secp256k1::new();
1814 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1815 let cur_height = nodes[0].node.best_block.read().unwrap().height + 1;
1816 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1817 let recipient_onion_fields = RecipientOnionFields::spontaneous_empty();
1818 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
1819 &route_2.paths[0], recv_value_2, &recipient_onion_fields, cur_height, &None).unwrap();
1820 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1).unwrap();
1821 let msg = msgs::UpdateAddHTLC {
1824 amount_msat: htlc_msat + 1,
1825 payment_hash: our_payment_hash_1,
1826 cltv_expiry: htlc_cltv,
1827 onion_routing_packet: onion_packet,
1828 skimmed_fee_msat: None,
1829 blinding_point: None,
1832 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1833 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1834 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Remote HTLC add would put them under remote reserve value", 3);
1835 assert_eq!(nodes[1].node.list_channels().len(), 1);
1836 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1837 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1838 check_added_monitors!(nodes[1], 1);
1839 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() },
1840 [nodes[0].node.get_our_node_id()], 100000);
1844 fn test_inbound_outbound_capacity_is_not_zero() {
1845 let chanmon_cfgs = create_chanmon_cfgs(2);
1846 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1847 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1848 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1849 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1850 let channels0 = node_chanmgrs[0].list_channels();
1851 let channels1 = node_chanmgrs[1].list_channels();
1852 let default_config = UserConfig::default();
1853 assert_eq!(channels0.len(), 1);
1854 assert_eq!(channels1.len(), 1);
1856 let reserve = get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1857 assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1858 assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1860 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1861 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1864 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, channel_type_features: &ChannelTypeFeatures) -> u64 {
1865 (commitment_tx_base_weight(channel_type_features) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1869 fn test_channel_reserve_holding_cell_htlcs() {
1870 let chanmon_cfgs = create_chanmon_cfgs(3);
1871 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1872 // When this test was written, the default base fee floated based on the HTLC count.
1873 // It is now fixed, so we simply set the fee to the expected value here.
1874 let mut config = test_default_channel_config();
1875 config.channel_config.forwarding_fee_base_msat = 239;
1876 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1877 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1878 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001);
1879 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001);
1881 let mut stat01 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1882 let mut stat11 = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
1884 let mut stat12 = get_channel_value_stat!(nodes[1], nodes[2], chan_2.2);
1885 let mut stat22 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
1887 macro_rules! expect_forward {
1889 let mut events = $node.node.get_and_clear_pending_msg_events();
1890 assert_eq!(events.len(), 1);
1891 check_added_monitors!($node, 1);
1892 let payment_event = SendEvent::from_event(events.remove(0));
1897 let feemsat = 239; // set above
1898 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1899 let feerate = get_feerate!(nodes[0], nodes[1], chan_1.2);
1900 let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_1.2);
1902 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1904 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1906 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1907 .with_bolt11_features(nodes[2].node.bolt11_invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1908 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, recv_value_0);
1909 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1910 assert!(route.paths[0].hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1912 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1913 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1914 ), true, APIError::ChannelUnavailable { .. }, {});
1915 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1918 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1919 // nodes[0]'s wealth
1921 let amt_msat = recv_value_0 + total_fee_msat;
1922 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1923 // Also, ensure that each payment has enough to be over the dust limit to
1924 // ensure it'll be included in each commit tx fee calculation.
1925 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, &channel_type_features);
1926 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1927 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1931 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1932 .with_bolt11_features(nodes[2].node.bolt11_invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1933 let route = get_route!(nodes[0], payment_params, recv_value_0).unwrap();
1934 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1935 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1937 let (stat01_, stat11_, stat12_, stat22_) = (
1938 get_channel_value_stat!(nodes[0], nodes[1], chan_1.2),
1939 get_channel_value_stat!(nodes[1], nodes[0], chan_1.2),
1940 get_channel_value_stat!(nodes[1], nodes[2], chan_2.2),
1941 get_channel_value_stat!(nodes[2], nodes[1], chan_2.2),
1944 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1945 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1946 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1947 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1948 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1951 // adding pending output.
1952 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1953 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1954 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1955 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1956 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1957 // cases where 1 msat over X amount will cause a payment failure, but anything less than
1958 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1959 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1960 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1962 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features);
1963 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1964 let amt_msat_1 = recv_value_1 + total_fee_msat;
1966 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);
1967 let payment_event_1 = {
1968 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1969 RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1970 check_added_monitors!(nodes[0], 1);
1972 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1973 assert_eq!(events.len(), 1);
1974 SendEvent::from_event(events.remove(0))
1976 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1978 // channel reserve test with htlc pending output > 0
1979 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1981 let mut route = route_1.clone();
1982 route.paths[0].hops.last_mut().unwrap().fee_msat = recv_value_2 + 1;
1983 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
1984 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1985 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1986 ), true, APIError::ChannelUnavailable { .. }, {});
1987 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1990 // split the rest to test holding cell
1991 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, &channel_type_features);
1992 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1993 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1994 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1996 let stat = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1997 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);
2000 // now see if they go through on both sides
2001 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);
2002 // but this will stuck in the holding cell
2003 nodes[0].node.send_payment_with_route(&route_21, our_payment_hash_21,
2004 RecipientOnionFields::secret_only(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
2005 check_added_monitors!(nodes[0], 0);
2006 let events = nodes[0].node.get_and_clear_pending_events();
2007 assert_eq!(events.len(), 0);
2009 // test with outbound holding cell amount > 0
2011 let (mut route, our_payment_hash, _, our_payment_secret) =
2012 get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22);
2013 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
2014 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
2015 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
2016 ), true, APIError::ChannelUnavailable { .. }, {});
2017 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2020 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);
2021 // this will also stuck in the holding cell
2022 nodes[0].node.send_payment_with_route(&route_22, our_payment_hash_22,
2023 RecipientOnionFields::secret_only(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
2024 check_added_monitors!(nodes[0], 0);
2025 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
2026 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2028 // flush the pending htlc
2029 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
2030 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2031 check_added_monitors!(nodes[1], 1);
2033 // the pending htlc should be promoted to committed
2034 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
2035 check_added_monitors!(nodes[0], 1);
2036 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2038 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
2039 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2040 // No commitment_signed so get_event_msg's assert(len == 1) passes
2041 check_added_monitors!(nodes[0], 1);
2043 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
2044 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2045 check_added_monitors!(nodes[1], 1);
2047 expect_pending_htlcs_forwardable!(nodes[1]);
2049 let ref payment_event_11 = expect_forward!(nodes[1]);
2050 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
2051 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
2053 expect_pending_htlcs_forwardable!(nodes[2]);
2054 expect_payment_claimable!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
2056 // flush the htlcs in the holding cell
2057 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
2058 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
2059 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
2060 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
2061 expect_pending_htlcs_forwardable!(nodes[1]);
2063 let ref payment_event_3 = expect_forward!(nodes[1]);
2064 assert_eq!(payment_event_3.msgs.len(), 2);
2065 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
2066 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
2068 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2069 expect_pending_htlcs_forwardable!(nodes[2]);
2071 let events = nodes[2].node.get_and_clear_pending_events();
2072 assert_eq!(events.len(), 2);
2074 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2075 assert_eq!(our_payment_hash_21, *payment_hash);
2076 assert_eq!(recv_value_21, amount_msat);
2077 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2078 assert_eq!(via_channel_id, Some(chan_2.2));
2080 PaymentPurpose::Bolt11InvoicePayment { payment_preimage, payment_secret, .. } => {
2081 assert!(payment_preimage.is_none());
2082 assert_eq!(our_payment_secret_21, *payment_secret);
2084 _ => panic!("expected PaymentPurpose::Bolt11InvoicePayment")
2087 _ => panic!("Unexpected event"),
2090 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2091 assert_eq!(our_payment_hash_22, *payment_hash);
2092 assert_eq!(recv_value_22, amount_msat);
2093 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2094 assert_eq!(via_channel_id, Some(chan_2.2));
2096 PaymentPurpose::Bolt11InvoicePayment { payment_preimage, payment_secret, .. } => {
2097 assert!(payment_preimage.is_none());
2098 assert_eq!(our_payment_secret_22, *payment_secret);
2100 _ => panic!("expected PaymentPurpose::Bolt11InvoicePayment")
2103 _ => panic!("Unexpected event"),
2106 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2107 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2108 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2110 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, &channel_type_features);
2111 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2112 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2114 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
2115 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);
2116 let stat0 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
2117 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2118 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2120 let stat2 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
2121 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2125 fn channel_reserve_in_flight_removes() {
2126 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2127 // can send to its counterparty, but due to update ordering, the other side may not yet have
2128 // considered those HTLCs fully removed.
2129 // This tests that we don't count HTLCs which will not be included in the next remote
2130 // commitment transaction towards the reserve value (as it implies no commitment transaction
2131 // will be generated which violates the remote reserve value).
2132 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2134 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2135 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2136 // you only consider the value of the first HTLC, it may not),
2137 // * start routing a third HTLC from A to B,
2138 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2139 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2140 // * deliver the first fulfill from B
2141 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2143 // * deliver A's response CS and RAA.
2144 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2145 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
2146 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2147 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2148 let chanmon_cfgs = create_chanmon_cfgs(2);
2149 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2150 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2151 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2152 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2154 let b_chan_values = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
2155 // Route the first two HTLCs.
2156 let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2157 let (payment_preimage_1, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2158 let (payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2160 // Start routing the third HTLC (this is just used to get everyone in the right state).
2161 let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2163 nodes[0].node.send_payment_with_route(&route, payment_hash_3,
2164 RecipientOnionFields::secret_only(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2165 check_added_monitors!(nodes[0], 1);
2166 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2167 assert_eq!(events.len(), 1);
2168 SendEvent::from_event(events.remove(0))
2171 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2172 // initial fulfill/CS.
2173 nodes[1].node.claim_funds(payment_preimage_1);
2174 expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2175 check_added_monitors!(nodes[1], 1);
2176 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2178 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2179 // remove the second HTLC when we send the HTLC back from B to A.
2180 nodes[1].node.claim_funds(payment_preimage_2);
2181 expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2182 check_added_monitors!(nodes[1], 1);
2183 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2185 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2186 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2187 check_added_monitors!(nodes[0], 1);
2188 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2189 expect_payment_sent(&nodes[0], payment_preimage_1, None, false, false);
2191 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2192 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2193 check_added_monitors!(nodes[1], 1);
2194 // B is already AwaitingRAA, so cant generate a CS here
2195 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2197 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2198 check_added_monitors!(nodes[1], 1);
2199 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2201 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2202 check_added_monitors!(nodes[0], 1);
2203 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2205 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2206 check_added_monitors!(nodes[1], 1);
2207 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2209 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2210 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2211 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2212 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2213 // on-chain as necessary).
2214 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2215 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2216 check_added_monitors!(nodes[0], 1);
2217 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2218 expect_payment_sent(&nodes[0], payment_preimage_2, None, false, false);
2220 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2221 check_added_monitors!(nodes[1], 1);
2222 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2224 expect_pending_htlcs_forwardable!(nodes[1]);
2225 expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2227 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2228 // resolve the second HTLC from A's point of view.
2229 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2230 check_added_monitors!(nodes[0], 1);
2231 expect_payment_path_successful!(nodes[0]);
2232 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2234 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2235 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2236 let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2238 nodes[1].node.send_payment_with_route(&route, payment_hash_4,
2239 RecipientOnionFields::secret_only(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2240 check_added_monitors!(nodes[1], 1);
2241 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2242 assert_eq!(events.len(), 1);
2243 SendEvent::from_event(events.remove(0))
2246 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2247 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2248 check_added_monitors!(nodes[0], 1);
2249 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2251 // Now just resolve all the outstanding messages/HTLCs for completeness...
2253 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2254 check_added_monitors!(nodes[1], 1);
2255 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2257 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2258 check_added_monitors!(nodes[1], 1);
2260 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2261 check_added_monitors!(nodes[0], 1);
2262 expect_payment_path_successful!(nodes[0]);
2263 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2265 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2266 check_added_monitors!(nodes[1], 1);
2267 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2269 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2270 check_added_monitors!(nodes[0], 1);
2272 expect_pending_htlcs_forwardable!(nodes[0]);
2273 expect_payment_claimable!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2275 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2276 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2280 fn channel_monitor_network_test() {
2281 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2282 // tests that ChannelMonitor is able to recover from various states.
2283 let chanmon_cfgs = create_chanmon_cfgs(5);
2284 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2285 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2286 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2288 // Create some initial channels
2289 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2290 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2291 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2292 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
2294 // Make sure all nodes are at the same starting height
2295 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2296 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2297 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2298 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2299 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2301 // Rebalance the network a bit by relaying one payment through all the channels...
2302 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2303 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2304 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2305 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2307 // Simple case with no pending HTLCs:
2308 let error_message = "Channel force-closed";
2309 nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id(), error_message.to_string()).unwrap();
2310 check_added_monitors!(nodes[1], 1);
2311 check_closed_broadcast!(nodes[1], true);
2312 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(true) }, [nodes[0].node.get_our_node_id()], 100000);
2314 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2315 assert_eq!(node_txn.len(), 1);
2316 mine_transaction(&nodes[1], &node_txn[0]);
2317 if nodes[1].connect_style.borrow().updates_best_block_first() {
2318 let _ = nodes[1].tx_broadcaster.txn_broadcast();
2321 mine_transaction(&nodes[0], &node_txn[0]);
2322 check_added_monitors!(nodes[0], 1);
2323 test_txn_broadcast(&nodes[0], &chan_1, Some(node_txn[0].clone()), HTLCType::NONE);
2325 check_closed_broadcast!(nodes[0], true);
2326 assert_eq!(nodes[0].node.list_channels().len(), 0);
2327 assert_eq!(nodes[1].node.list_channels().len(), 1);
2328 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2330 // One pending HTLC is discarded by the force-close:
2331 let (payment_preimage_1, payment_hash_1, ..) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2333 // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2334 // broadcasted until we reach the timelock time).
2335 let error_message = "Channel force-closed";
2336 nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id(), error_message.to_string()).unwrap();
2337 check_closed_broadcast!(nodes[1], true);
2338 check_added_monitors!(nodes[1], 1);
2340 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2341 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2342 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2343 mine_transaction(&nodes[2], &node_txn[0]);
2344 check_added_monitors!(nodes[2], 1);
2345 test_txn_broadcast(&nodes[2], &chan_2, Some(node_txn[0].clone()), HTLCType::NONE);
2347 check_closed_broadcast!(nodes[2], true);
2348 assert_eq!(nodes[1].node.list_channels().len(), 0);
2349 assert_eq!(nodes[2].node.list_channels().len(), 1);
2350 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(true) }, [nodes[2].node.get_our_node_id()], 100000);
2351 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2353 macro_rules! claim_funds {
2354 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2356 $node.node.claim_funds($preimage);
2357 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2358 check_added_monitors!($node, 1);
2360 let events = $node.node.get_and_clear_pending_msg_events();
2361 assert_eq!(events.len(), 1);
2363 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2364 assert!(update_add_htlcs.is_empty());
2365 assert!(update_fail_htlcs.is_empty());
2366 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2368 _ => panic!("Unexpected event"),
2374 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2375 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2376 let error_message = "Channel force-closed";
2377 nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id(), error_message.to_string()).unwrap();
2378 check_added_monitors!(nodes[2], 1);
2379 check_closed_broadcast!(nodes[2], true);
2380 let node2_commitment_txid;
2382 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2383 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2384 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2385 node2_commitment_txid = node_txn[0].txid();
2387 // Claim the payment on nodes[3], giving it knowledge of the preimage
2388 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2389 mine_transaction(&nodes[3], &node_txn[0]);
2390 check_added_monitors!(nodes[3], 1);
2391 check_preimage_claim(&nodes[3], &node_txn);
2393 check_closed_broadcast!(nodes[3], true);
2394 assert_eq!(nodes[2].node.list_channels().len(), 0);
2395 assert_eq!(nodes[3].node.list_channels().len(), 1);
2396 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(true) }, [nodes[3].node.get_our_node_id()], 100000);
2397 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
2399 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2400 // confusing us in the following tests.
2401 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2403 // One pending HTLC to time out:
2404 let (payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2405 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2408 let (close_chan_update_1, close_chan_update_2) = {
2409 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2410 let events = nodes[3].node.get_and_clear_pending_msg_events();
2411 assert_eq!(events.len(), 2);
2412 let close_chan_update_1 = match events[1] {
2413 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2416 _ => panic!("Unexpected event"),
2419 MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { .. }, node_id } => {
2420 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2422 _ => panic!("Unexpected event"),
2424 check_added_monitors!(nodes[3], 1);
2426 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2428 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2429 node_txn.retain(|tx| {
2430 if tx.input[0].previous_output.txid == node2_commitment_txid {
2436 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2438 // Claim the payment on nodes[4], giving it knowledge of the preimage
2439 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2441 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2442 let events = nodes[4].node.get_and_clear_pending_msg_events();
2443 assert_eq!(events.len(), 2);
2444 let close_chan_update_2 = match events[1] {
2445 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2448 _ => panic!("Unexpected event"),
2451 MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { .. }, node_id } => {
2452 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2454 _ => panic!("Unexpected event"),
2456 check_added_monitors!(nodes[4], 1);
2457 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2458 check_closed_event!(nodes[4], 1, ClosureReason::HTLCsTimedOut, [nodes[3].node.get_our_node_id()], 100000);
2460 mine_transaction(&nodes[4], &node_txn[0]);
2461 check_preimage_claim(&nodes[4], &node_txn);
2462 (close_chan_update_1, close_chan_update_2)
2464 nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2465 nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2466 assert_eq!(nodes[3].node.list_channels().len(), 0);
2467 assert_eq!(nodes[4].node.list_channels().len(), 0);
2469 assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2470 Ok(ChannelMonitorUpdateStatus::Completed));
2471 check_closed_event!(nodes[3], 1, ClosureReason::HTLCsTimedOut, [nodes[4].node.get_our_node_id()], 100000);
2475 fn test_justice_tx_htlc_timeout() {
2476 // Test justice txn built on revoked HTLC-Timeout tx, against both sides
2477 let mut alice_config = test_default_channel_config();
2478 alice_config.channel_handshake_config.announced_channel = true;
2479 alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2480 alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2481 let mut bob_config = test_default_channel_config();
2482 bob_config.channel_handshake_config.announced_channel = true;
2483 bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2484 bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2485 let user_cfgs = [Some(alice_config), Some(bob_config)];
2486 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2487 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2488 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2489 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2490 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2491 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2492 // Create some new channels:
2493 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
2495 // A pending HTLC which will be revoked:
2496 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2497 // Get the will-be-revoked local txn from nodes[0]
2498 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2499 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2500 assert_eq!(revoked_local_txn[0].input.len(), 1);
2501 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2502 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2503 assert_eq!(revoked_local_txn[1].input.len(), 1);
2504 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2505 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2506 // Revoke the old state
2507 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2510 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2512 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2513 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2514 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2515 check_spends!(node_txn[0], revoked_local_txn[0]);
2516 node_txn.swap_remove(0);
2518 check_added_monitors!(nodes[1], 1);
2519 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2520 test_txn_broadcast(&nodes[1], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2522 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2523 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2524 // Verify broadcast of revoked HTLC-timeout
2525 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2526 check_added_monitors!(nodes[0], 1);
2527 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2528 // Broadcast revoked HTLC-timeout on node 1
2529 mine_transaction(&nodes[1], &node_txn[1]);
2530 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2532 get_announce_close_broadcast_events(&nodes, 0, 1);
2533 assert_eq!(nodes[0].node.list_channels().len(), 0);
2534 assert_eq!(nodes[1].node.list_channels().len(), 0);
2538 fn test_justice_tx_htlc_success() {
2539 // Test justice txn built on revoked HTLC-Success tx, against both sides
2540 let mut alice_config = test_default_channel_config();
2541 alice_config.channel_handshake_config.announced_channel = true;
2542 alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2543 alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2544 let mut bob_config = test_default_channel_config();
2545 bob_config.channel_handshake_config.announced_channel = true;
2546 bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2547 bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2548 let user_cfgs = [Some(alice_config), Some(bob_config)];
2549 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2550 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2551 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2552 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2553 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2554 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2555 // Create some new channels:
2556 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
2558 // A pending HTLC which will be revoked:
2559 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2560 // Get the will-be-revoked local txn from B
2561 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2562 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2563 assert_eq!(revoked_local_txn[0].input.len(), 1);
2564 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2565 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2566 // Revoke the old state
2567 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2569 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2571 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2572 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2573 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2575 check_spends!(node_txn[0], revoked_local_txn[0]);
2576 node_txn.swap_remove(0);
2578 check_added_monitors!(nodes[0], 1);
2579 test_txn_broadcast(&nodes[0], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2581 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2582 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2583 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2584 check_added_monitors!(nodes[1], 1);
2585 mine_transaction(&nodes[0], &node_txn[1]);
2586 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2587 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2589 get_announce_close_broadcast_events(&nodes, 0, 1);
2590 assert_eq!(nodes[0].node.list_channels().len(), 0);
2591 assert_eq!(nodes[1].node.list_channels().len(), 0);
2595 fn revoked_output_claim() {
2596 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2597 // transaction is broadcast by its counterparty
2598 let chanmon_cfgs = create_chanmon_cfgs(2);
2599 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2600 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2601 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2602 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2603 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2604 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2605 assert_eq!(revoked_local_txn.len(), 1);
2606 // Only output is the full channel value back to nodes[0]:
2607 assert_eq!(revoked_local_txn[0].output.len(), 1);
2608 // Send a payment through, updating everyone's latest commitment txn
2609 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2611 // Inform nodes[1] that nodes[0] broadcast a stale tx
2612 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2613 check_added_monitors!(nodes[1], 1);
2614 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2615 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2616 assert_eq!(node_txn.len(), 1); // ChannelMonitor: justice tx against revoked to_local output
2618 check_spends!(node_txn[0], revoked_local_txn[0]);
2620 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2621 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2622 get_announce_close_broadcast_events(&nodes, 0, 1);
2623 check_added_monitors!(nodes[0], 1);
2624 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2628 fn test_forming_justice_tx_from_monitor_updates() {
2629 do_test_forming_justice_tx_from_monitor_updates(true);
2630 do_test_forming_justice_tx_from_monitor_updates(false);
2633 fn do_test_forming_justice_tx_from_monitor_updates(broadcast_initial_commitment: bool) {
2634 // Simple test to make sure that the justice tx formed in WatchtowerPersister
2635 // is properly formed and can be broadcasted/confirmed successfully in the event
2636 // that a revoked commitment transaction is broadcasted
2637 // (Similar to `revoked_output_claim` test but we get the justice tx + broadcast manually)
2638 let chanmon_cfgs = create_chanmon_cfgs(2);
2639 let destination_script0 = chanmon_cfgs[0].keys_manager.get_destination_script([0; 32]).unwrap();
2640 let destination_script1 = chanmon_cfgs[1].keys_manager.get_destination_script([0; 32]).unwrap();
2641 let persisters = vec![WatchtowerPersister::new(destination_script0),
2642 WatchtowerPersister::new(destination_script1)];
2643 let node_cfgs = create_node_cfgs_with_persisters(2, &chanmon_cfgs, persisters.iter().collect());
2644 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2645 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2646 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
2647 let funding_txo = OutPoint { txid: funding_tx.txid(), index: 0 };
2649 if !broadcast_initial_commitment {
2650 // Send a payment to move the channel forward
2651 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5_000_000);
2654 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output.
2655 // We'll keep this commitment transaction to broadcast once it's revoked.
2656 let revoked_local_txn = get_local_commitment_txn!(nodes[0], channel_id);
2657 assert_eq!(revoked_local_txn.len(), 1);
2658 let revoked_commitment_tx = &revoked_local_txn[0];
2660 // Send another payment, now revoking the previous commitment tx
2661 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5_000_000);
2663 let justice_tx = persisters[1].justice_tx(funding_txo, &revoked_commitment_tx.txid()).unwrap();
2664 check_spends!(justice_tx, revoked_commitment_tx);
2666 mine_transactions(&nodes[1], &[revoked_commitment_tx, &justice_tx]);
2667 mine_transactions(&nodes[0], &[revoked_commitment_tx, &justice_tx]);
2669 check_added_monitors!(nodes[1], 1);
2670 check_closed_event(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false,
2671 &[nodes[0].node.get_our_node_id()], 100_000);
2672 get_announce_close_broadcast_events(&nodes, 1, 0);
2674 check_added_monitors!(nodes[0], 1);
2675 check_closed_event(&nodes[0], 1, ClosureReason::CommitmentTxConfirmed, false,
2676 &[nodes[1].node.get_our_node_id()], 100_000);
2678 // Check that the justice tx has sent the revoked output value to nodes[1]
2679 let monitor = get_monitor!(nodes[1], channel_id);
2680 let total_claimable_balance = monitor.get_claimable_balances().iter().fold(0, |sum, balance| {
2682 channelmonitor::Balance::ClaimableAwaitingConfirmations { amount_satoshis, .. } => sum + amount_satoshis,
2683 _ => panic!("Unexpected balance type"),
2686 // On the first commitment, node[1]'s balance was below dust so it didn't have an output
2687 let node1_channel_balance = if broadcast_initial_commitment { 0 } else { revoked_commitment_tx.output[0].value.to_sat() };
2688 let expected_claimable_balance = node1_channel_balance + justice_tx.output[0].value.to_sat();
2689 assert_eq!(total_claimable_balance, expected_claimable_balance);
2694 fn claim_htlc_outputs_shared_tx() {
2695 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2696 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2697 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2698 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2699 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2700 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2702 // Create some new channel:
2703 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2705 // Rebalance the network to generate htlc in the two directions
2706 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2707 // 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
2708 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2709 let (_payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2711 // Get the will-be-revoked local txn from node[0]
2712 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2713 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2714 assert_eq!(revoked_local_txn[0].input.len(), 1);
2715 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2716 assert_eq!(revoked_local_txn[1].input.len(), 1);
2717 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2718 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2719 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2721 //Revoke the old state
2722 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2725 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2726 check_added_monitors!(nodes[0], 1);
2727 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2728 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2729 check_added_monitors!(nodes[1], 1);
2730 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2731 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2732 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2734 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2735 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2737 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2738 check_spends!(node_txn[0], revoked_local_txn[0]);
2740 let mut witness_lens = BTreeSet::new();
2741 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2742 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2743 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2744 assert_eq!(witness_lens.len(), 3);
2745 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2746 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2747 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2749 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2750 // ANTI_REORG_DELAY confirmations.
2751 mine_transaction(&nodes[1], &node_txn[0]);
2752 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2753 expect_payment_failed!(nodes[1], payment_hash_2, false);
2755 get_announce_close_broadcast_events(&nodes, 0, 1);
2756 assert_eq!(nodes[0].node.list_channels().len(), 0);
2757 assert_eq!(nodes[1].node.list_channels().len(), 0);
2761 fn claim_htlc_outputs_single_tx() {
2762 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2763 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2764 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2765 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2766 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2767 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2769 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2771 // Rebalance the network to generate htlc in the two directions
2772 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2773 // 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
2774 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2775 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2776 let (_payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2778 // Get the will-be-revoked local txn from node[0]
2779 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2781 //Revoke the old state
2782 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2785 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2786 check_added_monitors!(nodes[0], 1);
2787 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2788 check_added_monitors!(nodes[1], 1);
2789 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2790 let mut events = nodes[0].node.get_and_clear_pending_events();
2791 expect_pending_htlcs_forwardable_conditions(events[0..2].to_vec(), &[HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
2792 match events.last().unwrap() {
2793 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2794 _ => panic!("Unexpected event"),
2797 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2798 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2800 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcast();
2802 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2803 assert_eq!(node_txn[0].input.len(), 1);
2804 check_spends!(node_txn[0], chan_1.3);
2805 assert_eq!(node_txn[1].input.len(), 1);
2806 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2807 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2808 check_spends!(node_txn[1], node_txn[0]);
2810 // Filter out any non justice transactions.
2811 node_txn.retain(|tx| tx.input[0].previous_output.txid == revoked_local_txn[0].txid());
2812 assert!(node_txn.len() > 3);
2814 assert_eq!(node_txn[0].input.len(), 1);
2815 assert_eq!(node_txn[1].input.len(), 1);
2816 assert_eq!(node_txn[2].input.len(), 1);
2818 check_spends!(node_txn[0], revoked_local_txn[0]);
2819 check_spends!(node_txn[1], revoked_local_txn[0]);
2820 check_spends!(node_txn[2], revoked_local_txn[0]);
2822 let mut witness_lens = BTreeSet::new();
2823 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2824 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2825 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2826 assert_eq!(witness_lens.len(), 3);
2827 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2828 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2829 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2831 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2832 // ANTI_REORG_DELAY confirmations.
2833 mine_transaction(&nodes[1], &node_txn[0]);
2834 mine_transaction(&nodes[1], &node_txn[1]);
2835 mine_transaction(&nodes[1], &node_txn[2]);
2836 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2837 expect_payment_failed!(nodes[1], payment_hash_2, false);
2839 get_announce_close_broadcast_events(&nodes, 0, 1);
2840 assert_eq!(nodes[0].node.list_channels().len(), 0);
2841 assert_eq!(nodes[1].node.list_channels().len(), 0);
2845 fn test_htlc_on_chain_success() {
2846 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2847 // the preimage backward accordingly. So here we test that ChannelManager is
2848 // broadcasting the right event to other nodes in payment path.
2849 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2850 // A --------------------> B ----------------------> C (preimage)
2851 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2852 // commitment transaction was broadcast.
2853 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2855 // B should be able to claim via preimage if A then broadcasts its local tx.
2856 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2857 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2858 // PaymentSent event).
2860 let chanmon_cfgs = create_chanmon_cfgs(3);
2861 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2862 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2863 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2865 // Create some initial channels
2866 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2867 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2869 // Ensure all nodes are at the same height
2870 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2871 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2872 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2873 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2875 // Rebalance the network a bit by relaying one payment through all the channels...
2876 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2877 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2879 let (our_payment_preimage, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2880 let (our_payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2882 // Broadcast legit commitment tx from C on B's chain
2883 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2884 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2885 assert_eq!(commitment_tx.len(), 1);
2886 check_spends!(commitment_tx[0], chan_2.3);
2887 nodes[2].node.claim_funds(our_payment_preimage);
2888 expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2889 nodes[2].node.claim_funds(our_payment_preimage_2);
2890 expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2891 check_added_monitors!(nodes[2], 2);
2892 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2893 assert!(updates.update_add_htlcs.is_empty());
2894 assert!(updates.update_fail_htlcs.is_empty());
2895 assert!(updates.update_fail_malformed_htlcs.is_empty());
2896 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2898 mine_transaction(&nodes[2], &commitment_tx[0]);
2899 check_closed_broadcast!(nodes[2], true);
2900 check_added_monitors!(nodes[2], 1);
2901 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2902 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 2 (2 * HTLC-Success tx)
2903 assert_eq!(node_txn.len(), 2);
2904 check_spends!(node_txn[0], commitment_tx[0]);
2905 check_spends!(node_txn[1], commitment_tx[0]);
2906 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2907 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2908 assert!(node_txn[0].output[0].script_pubkey.is_p2wsh()); // revokeable output
2909 assert!(node_txn[1].output[0].script_pubkey.is_p2wsh()); // revokeable output
2910 assert_eq!(node_txn[0].lock_time, LockTime::ZERO);
2911 assert_eq!(node_txn[1].lock_time, LockTime::ZERO);
2913 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2914 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()]));
2915 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2917 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2918 assert_eq!(added_monitors.len(), 1);
2919 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2920 added_monitors.clear();
2922 let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2923 assert_eq!(forwarded_events.len(), 3);
2924 match forwarded_events[0] {
2925 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2926 _ => panic!("Unexpected event"),
2928 let chan_id = Some(chan_1.2);
2929 match forwarded_events[1] {
2930 Event::PaymentForwarded { total_fee_earned_msat, prev_channel_id, claim_from_onchain_tx,
2931 next_channel_id, outbound_amount_forwarded_msat, ..
2933 assert_eq!(total_fee_earned_msat, Some(1000));
2934 assert_eq!(prev_channel_id, chan_id);
2935 assert_eq!(claim_from_onchain_tx, true);
2936 assert_eq!(next_channel_id, Some(chan_2.2));
2937 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2941 match forwarded_events[2] {
2942 Event::PaymentForwarded { total_fee_earned_msat, prev_channel_id, claim_from_onchain_tx,
2943 next_channel_id, outbound_amount_forwarded_msat, ..
2945 assert_eq!(total_fee_earned_msat, Some(1000));
2946 assert_eq!(prev_channel_id, chan_id);
2947 assert_eq!(claim_from_onchain_tx, true);
2948 assert_eq!(next_channel_id, Some(chan_2.2));
2949 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2953 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2955 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2956 assert_eq!(added_monitors.len(), 2);
2957 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2958 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2959 added_monitors.clear();
2961 assert_eq!(events.len(), 3);
2963 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
2964 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
2966 match nodes_2_event {
2967 MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { .. }, node_id: _ } => {},
2968 _ => panic!("Unexpected event"),
2971 match nodes_0_event {
2972 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, .. } } => {
2973 assert!(update_add_htlcs.is_empty());
2974 assert!(update_fail_htlcs.is_empty());
2975 assert_eq!(update_fulfill_htlcs.len(), 1);
2976 assert!(update_fail_malformed_htlcs.is_empty());
2977 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2979 _ => panic!("Unexpected event"),
2982 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
2984 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2985 _ => panic!("Unexpected event"),
2988 macro_rules! check_tx_local_broadcast {
2989 ($node: expr, $htlc_offered: expr, $commitment_tx: expr) => { {
2990 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2991 assert_eq!(node_txn.len(), 2);
2992 // Node[1]: 2 * HTLC-timeout tx
2993 // Node[0]: 2 * HTLC-timeout tx
2994 check_spends!(node_txn[0], $commitment_tx);
2995 check_spends!(node_txn[1], $commitment_tx);
2996 assert_ne!(node_txn[0].lock_time, LockTime::ZERO);
2997 assert_ne!(node_txn[1].lock_time, LockTime::ZERO);
2999 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3000 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3001 assert!(node_txn[0].output[0].script_pubkey.is_p2wsh()); // revokeable output
3002 assert!(node_txn[1].output[0].script_pubkey.is_p2wsh()); // revokeable output
3004 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3005 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3006 assert!(node_txn[0].output[0].script_pubkey.is_p2wpkh()); // direct payment
3007 assert!(node_txn[1].output[0].script_pubkey.is_p2wpkh()); // direct payment
3012 // nodes[1] now broadcasts its own timeout-claim of the output that nodes[2] just claimed via success.
3013 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0]);
3015 // Broadcast legit commitment tx from A on B's chain
3016 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
3017 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
3018 check_spends!(node_a_commitment_tx[0], chan_1.3);
3019 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
3020 check_closed_broadcast!(nodes[1], true);
3021 check_added_monitors!(nodes[1], 1);
3022 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
3023 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
3024 assert!(node_txn.len() == 1 || node_txn.len() == 3); // HTLC-Success, 2* RBF bumps of above HTLC txn
3025 let commitment_spend =
3026 if node_txn.len() == 1 {
3029 // Certain `ConnectStyle`s will cause RBF bumps of the previous HTLC transaction to be broadcast.
3030 // FullBlockViaListen
3031 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
3032 check_spends!(node_txn[1], commitment_tx[0]);
3033 check_spends!(node_txn[2], commitment_tx[0]);
3034 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
3037 check_spends!(node_txn[0], commitment_tx[0]);
3038 check_spends!(node_txn[1], commitment_tx[0]);
3039 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
3044 check_spends!(commitment_spend, node_a_commitment_tx[0]);
3045 assert_eq!(commitment_spend.input.len(), 2);
3046 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3047 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3048 assert_eq!(commitment_spend.lock_time.to_consensus_u32(), nodes[1].best_block_info().1);
3049 assert!(commitment_spend.output[0].script_pubkey.is_p2wpkh()); // direct payment
3050 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
3051 // we already checked the same situation with A.
3053 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
3054 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()]));
3055 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
3056 check_closed_broadcast!(nodes[0], true);
3057 check_added_monitors!(nodes[0], 1);
3058 let events = nodes[0].node.get_and_clear_pending_events();
3059 assert_eq!(events.len(), 5);
3060 let mut first_claimed = false;
3061 for event in events {
3063 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3064 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
3065 assert!(!first_claimed);
3066 first_claimed = true;
3068 assert_eq!(payment_preimage, our_payment_preimage_2);
3069 assert_eq!(payment_hash, payment_hash_2);
3072 Event::PaymentPathSuccessful { .. } => {},
3073 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
3074 _ => panic!("Unexpected event"),
3077 check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0]);
3080 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
3081 // Test that in case of a unilateral close onchain, we detect the state of output and
3082 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
3083 // broadcasting the right event to other nodes in payment path.
3084 // A ------------------> B ----------------------> C (timeout)
3085 // B's commitment tx C's commitment tx
3087 // B's HTLC timeout tx B's timeout tx
3089 let chanmon_cfgs = create_chanmon_cfgs(3);
3090 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3091 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3092 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3093 *nodes[0].connect_style.borrow_mut() = connect_style;
3094 *nodes[1].connect_style.borrow_mut() = connect_style;
3095 *nodes[2].connect_style.borrow_mut() = connect_style;
3097 // Create some intial channels
3098 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
3099 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3101 // Rebalance the network a bit by relaying one payment thorugh all the channels...
3102 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
3103 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
3105 let (_payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
3107 // Broadcast legit commitment tx from C on B's chain
3108 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
3109 check_spends!(commitment_tx[0], chan_2.3);
3110 nodes[2].node.fail_htlc_backwards(&payment_hash);
3111 check_added_monitors!(nodes[2], 0);
3112 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
3113 check_added_monitors!(nodes[2], 1);
3115 let events = nodes[2].node.get_and_clear_pending_msg_events();
3116 assert_eq!(events.len(), 1);
3118 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, .. } } => {
3119 assert!(update_add_htlcs.is_empty());
3120 assert!(!update_fail_htlcs.is_empty());
3121 assert!(update_fulfill_htlcs.is_empty());
3122 assert!(update_fail_malformed_htlcs.is_empty());
3123 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
3125 _ => panic!("Unexpected event"),
3127 mine_transaction(&nodes[2], &commitment_tx[0]);
3128 check_closed_broadcast!(nodes[2], true);
3129 check_added_monitors!(nodes[2], 1);
3130 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
3131 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
3132 assert_eq!(node_txn.len(), 0);
3134 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
3135 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
3136 mine_transaction(&nodes[1], &commitment_tx[0]);
3137 check_closed_event!(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false
3138 , [nodes[2].node.get_our_node_id()], 100000);
3139 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
3141 let mut txn = nodes[1].tx_broadcaster.txn_broadcast();
3142 if nodes[1].connect_style.borrow().skips_blocks() {
3143 assert_eq!(txn.len(), 1);
3145 assert_eq!(txn.len(), 3); // Two extra fee bumps for timeout transaction
3147 txn.iter().for_each(|tx| check_spends!(tx, commitment_tx[0]));
3148 assert_eq!(txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3152 mine_transaction(&nodes[1], &timeout_tx);
3153 check_added_monitors!(nodes[1], 1);
3154 check_closed_broadcast!(nodes[1], true);
3156 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3158 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 }]);
3159 check_added_monitors!(nodes[1], 1);
3160 let events = nodes[1].node.get_and_clear_pending_msg_events();
3161 assert_eq!(events.len(), 1);
3163 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, .. } } => {
3164 assert!(update_add_htlcs.is_empty());
3165 assert!(!update_fail_htlcs.is_empty());
3166 assert!(update_fulfill_htlcs.is_empty());
3167 assert!(update_fail_malformed_htlcs.is_empty());
3168 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3170 _ => panic!("Unexpected event"),
3173 // Broadcast legit commitment tx from B on A's chain
3174 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3175 check_spends!(commitment_tx[0], chan_1.3);
3177 mine_transaction(&nodes[0], &commitment_tx[0]);
3178 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
3180 check_closed_broadcast!(nodes[0], true);
3181 check_added_monitors!(nodes[0], 1);
3182 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
3183 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // 1 timeout tx
3184 assert_eq!(node_txn.len(), 1);
3185 check_spends!(node_txn[0], commitment_tx[0]);
3186 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3190 fn test_htlc_on_chain_timeout() {
3191 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3192 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3193 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3197 fn test_simple_commitment_revoked_fail_backward() {
3198 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3199 // and fail backward accordingly.
3201 let chanmon_cfgs = create_chanmon_cfgs(3);
3202 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3203 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3204 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3206 // Create some initial channels
3207 create_announced_chan_between_nodes(&nodes, 0, 1);
3208 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3210 let (payment_preimage, _payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3211 // Get the will-be-revoked local txn from nodes[2]
3212 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3213 // Revoke the old state
3214 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3216 let (_, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3218 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3219 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
3220 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3221 check_added_monitors!(nodes[1], 1);
3222 check_closed_broadcast!(nodes[1], true);
3224 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 }]);
3225 check_added_monitors!(nodes[1], 1);
3226 let events = nodes[1].node.get_and_clear_pending_msg_events();
3227 assert_eq!(events.len(), 1);
3229 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, .. } } => {
3230 assert!(update_add_htlcs.is_empty());
3231 assert_eq!(update_fail_htlcs.len(), 1);
3232 assert!(update_fulfill_htlcs.is_empty());
3233 assert!(update_fail_malformed_htlcs.is_empty());
3234 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3236 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3237 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3238 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3240 _ => panic!("Unexpected event"),
3244 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3245 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3246 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3247 // commitment transaction anymore.
3248 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3249 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3250 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3251 // technically disallowed and we should probably handle it reasonably.
3252 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3253 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3255 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3256 // commitment_signed (implying it will be in the latest remote commitment transaction).
3257 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3258 // and once they revoke the previous commitment transaction (allowing us to send a new
3259 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3260 let chanmon_cfgs = create_chanmon_cfgs(3);
3261 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3262 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3263 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3265 // Create some initial channels
3266 create_announced_chan_between_nodes(&nodes, 0, 1);
3267 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3269 let (payment_preimage, _payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3270 // Get the will-be-revoked local txn from nodes[2]
3271 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3272 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3273 // Revoke the old state
3274 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3276 let value = if use_dust {
3277 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3278 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3279 nodes[2].node.per_peer_state.read().unwrap().get(&nodes[1].node.get_our_node_id())
3280 .unwrap().lock().unwrap().channel_by_id.get(&chan_2.2).unwrap().context().holder_dust_limit_satoshis * 1000
3283 let (_, first_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3284 let (_, second_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3285 let (_, third_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3287 nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3288 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3289 check_added_monitors!(nodes[2], 1);
3290 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3291 assert!(updates.update_add_htlcs.is_empty());
3292 assert!(updates.update_fulfill_htlcs.is_empty());
3293 assert!(updates.update_fail_malformed_htlcs.is_empty());
3294 assert_eq!(updates.update_fail_htlcs.len(), 1);
3295 assert!(updates.update_fee.is_none());
3296 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3297 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3298 // Drop the last RAA from 3 -> 2
3300 nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3301 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3302 check_added_monitors!(nodes[2], 1);
3303 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3304 assert!(updates.update_add_htlcs.is_empty());
3305 assert!(updates.update_fulfill_htlcs.is_empty());
3306 assert!(updates.update_fail_malformed_htlcs.is_empty());
3307 assert_eq!(updates.update_fail_htlcs.len(), 1);
3308 assert!(updates.update_fee.is_none());
3309 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3310 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3311 check_added_monitors!(nodes[1], 1);
3312 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3313 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3314 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3315 check_added_monitors!(nodes[2], 1);
3317 nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3318 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3319 check_added_monitors!(nodes[2], 1);
3320 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3321 assert!(updates.update_add_htlcs.is_empty());
3322 assert!(updates.update_fulfill_htlcs.is_empty());
3323 assert!(updates.update_fail_malformed_htlcs.is_empty());
3324 assert_eq!(updates.update_fail_htlcs.len(), 1);
3325 assert!(updates.update_fee.is_none());
3326 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3327 // At this point first_payment_hash has dropped out of the latest two commitment
3328 // transactions that nodes[1] is tracking...
3329 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3330 check_added_monitors!(nodes[1], 1);
3331 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3332 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3333 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3334 check_added_monitors!(nodes[2], 1);
3336 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3337 // on nodes[2]'s RAA.
3338 let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3339 nodes[1].node.send_payment_with_route(&route, fourth_payment_hash,
3340 RecipientOnionFields::secret_only(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3341 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3342 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3343 check_added_monitors!(nodes[1], 0);
3346 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3347 // One monitor for the new revocation preimage, no second on as we won't generate a new
3348 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3349 check_added_monitors!(nodes[1], 1);
3350 let events = nodes[1].node.get_and_clear_pending_events();
3351 assert_eq!(events.len(), 2);
3353 Event::HTLCHandlingFailed { .. } => { },
3354 _ => panic!("Unexpected event"),
3357 Event::PendingHTLCsForwardable { .. } => { },
3358 _ => panic!("Unexpected event"),
3360 // Deliberately don't process the pending fail-back so they all fail back at once after
3361 // block connection just like the !deliver_bs_raa case
3364 let mut failed_htlcs = new_hash_set();
3365 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3367 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3368 check_added_monitors!(nodes[1], 1);
3369 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3371 let events = nodes[1].node.get_and_clear_pending_events();
3372 assert_eq!(events.len(), if deliver_bs_raa { 3 + nodes.len() - 1 } else { 4 + nodes.len() });
3373 assert!(events.iter().any(|ev| matches!(
3375 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. }
3377 assert!(events.iter().any(|ev| matches!(
3379 Event::PaymentPathFailed { ref payment_hash, .. } if *payment_hash == fourth_payment_hash
3381 assert!(events.iter().any(|ev| matches!(
3383 Event::PaymentFailed { ref payment_hash, .. } if *payment_hash == fourth_payment_hash
3386 nodes[1].node.process_pending_htlc_forwards();
3387 check_added_monitors!(nodes[1], 1);
3389 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
3390 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3393 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3394 match nodes_2_event {
3395 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, .. } } => {
3396 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3397 assert_eq!(update_add_htlcs.len(), 1);
3398 assert!(update_fulfill_htlcs.is_empty());
3399 assert!(update_fail_htlcs.is_empty());
3400 assert!(update_fail_malformed_htlcs.is_empty());
3402 _ => panic!("Unexpected event"),
3406 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3407 match nodes_2_event {
3408 MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { msg: Some(msgs::ErrorMessage { channel_id, ref data }) }, node_id: _ } => {
3409 assert_eq!(channel_id, chan_2.2);
3410 assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3412 _ => panic!("Unexpected event"),
3415 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
3416 match nodes_0_event {
3417 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, .. } } => {
3418 assert!(update_add_htlcs.is_empty());
3419 assert_eq!(update_fail_htlcs.len(), 3);
3420 assert!(update_fulfill_htlcs.is_empty());
3421 assert!(update_fail_malformed_htlcs.is_empty());
3422 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3424 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3425 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3426 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3428 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3430 let events = nodes[0].node.get_and_clear_pending_events();
3431 assert_eq!(events.len(), 6);
3433 Event::PaymentPathFailed { ref payment_hash, ref failure, .. } => {
3434 assert!(failed_htlcs.insert(payment_hash.0));
3435 // If we delivered B's RAA we got an unknown preimage error, not something
3436 // that we should update our routing table for.
3437 if !deliver_bs_raa {
3438 if let PathFailure::OnPath { network_update: Some(_) } = failure { } else { panic!("Unexpected path failure") }
3441 _ => panic!("Unexpected event"),
3444 Event::PaymentFailed { ref payment_hash, .. } => {
3445 assert_eq!(*payment_hash, first_payment_hash);
3447 _ => panic!("Unexpected event"),
3450 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3451 assert!(failed_htlcs.insert(payment_hash.0));
3453 _ => panic!("Unexpected event"),
3456 Event::PaymentFailed { ref payment_hash, .. } => {
3457 assert_eq!(*payment_hash, second_payment_hash);
3459 _ => panic!("Unexpected event"),
3462 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3463 assert!(failed_htlcs.insert(payment_hash.0));
3465 _ => panic!("Unexpected event"),
3468 Event::PaymentFailed { ref payment_hash, .. } => {
3469 assert_eq!(*payment_hash, third_payment_hash);
3471 _ => panic!("Unexpected event"),
3474 _ => panic!("Unexpected event"),
3477 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
3479 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3480 _ => panic!("Unexpected event"),
3483 assert!(failed_htlcs.contains(&first_payment_hash.0));
3484 assert!(failed_htlcs.contains(&second_payment_hash.0));
3485 assert!(failed_htlcs.contains(&third_payment_hash.0));
3489 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3490 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3491 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3492 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3493 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3497 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3498 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3499 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3500 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3501 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3505 fn fail_backward_pending_htlc_upon_channel_failure() {
3506 let chanmon_cfgs = create_chanmon_cfgs(2);
3507 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3508 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3509 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3510 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
3512 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3514 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3515 nodes[0].node.send_payment_with_route(&route, payment_hash, RecipientOnionFields::secret_only(payment_secret),
3516 PaymentId(payment_hash.0)).unwrap();
3517 check_added_monitors!(nodes[0], 1);
3519 let payment_event = {
3520 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3521 assert_eq!(events.len(), 1);
3522 SendEvent::from_event(events.remove(0))
3524 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3525 assert_eq!(payment_event.msgs.len(), 1);
3528 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3529 let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3531 nodes[0].node.send_payment_with_route(&route, failed_payment_hash,
3532 RecipientOnionFields::secret_only(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3533 check_added_monitors!(nodes[0], 0);
3535 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3538 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3540 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3542 let secp_ctx = Secp256k1::new();
3543 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3544 let current_height = nodes[1].node.best_block.read().unwrap().height + 1;
3545 let recipient_onion_fields = RecipientOnionFields::secret_only(payment_secret);
3546 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(
3547 &route.paths[0], 50_000, &recipient_onion_fields, current_height, &None).unwrap();
3548 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3549 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
3551 // Send a 0-msat update_add_htlc to fail the channel.
3552 let update_add_htlc = msgs::UpdateAddHTLC {
3558 onion_routing_packet,
3559 skimmed_fee_msat: None,
3560 blinding_point: None,
3562 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3564 let events = nodes[0].node.get_and_clear_pending_events();
3565 assert_eq!(events.len(), 3);
3566 // Check that Alice fails backward the pending HTLC from the second payment.
3568 Event::PaymentPathFailed { payment_hash, .. } => {
3569 assert_eq!(payment_hash, failed_payment_hash);
3571 _ => panic!("Unexpected event"),
3574 Event::PaymentFailed { payment_hash, .. } => {
3575 assert_eq!(payment_hash, failed_payment_hash);
3577 _ => panic!("Unexpected event"),
3580 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3581 assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3583 _ => panic!("Unexpected event {:?}", events[1]),
3585 check_closed_broadcast!(nodes[0], true);
3586 check_added_monitors!(nodes[0], 1);
3590 fn test_htlc_ignore_latest_remote_commitment() {
3591 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3592 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3593 let chanmon_cfgs = create_chanmon_cfgs(2);
3594 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3595 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3596 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3597 if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3598 // We rely on the ability to connect a block redundantly, which isn't allowed via
3599 // `chain::Listen`, so we never run the test if we randomly get assigned that
3603 let funding_tx = create_announced_chan_between_nodes(&nodes, 0, 1).3;
3604 let error_message = "Channel force-closed";
3605 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3606 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id(), error_message.to_string()).unwrap();
3607 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3608 check_closed_broadcast!(nodes[0], true);
3609 check_added_monitors!(nodes[0], 1);
3610 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(true) }, [nodes[1].node.get_our_node_id()], 100000);
3612 let node_txn = nodes[0].tx_broadcaster.unique_txn_broadcast();
3613 assert_eq!(node_txn.len(), 2);
3614 check_spends!(node_txn[0], funding_tx);
3615 check_spends!(node_txn[1], node_txn[0]);
3617 let block = create_dummy_block(nodes[1].best_block_hash(), 42, vec![node_txn[0].clone()]);
3618 connect_block(&nodes[1], &block);
3619 check_closed_broadcast!(nodes[1], true);
3620 check_added_monitors!(nodes[1], 1);
3621 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
3623 // Duplicate the connect_block call since this may happen due to other listeners
3624 // registering new transactions
3625 connect_block(&nodes[1], &block);
3629 fn test_force_close_fail_back() {
3630 // Check which HTLCs are failed-backwards on channel force-closure
3631 let chanmon_cfgs = create_chanmon_cfgs(3);
3632 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3633 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3634 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3635 create_announced_chan_between_nodes(&nodes, 0, 1);
3636 create_announced_chan_between_nodes(&nodes, 1, 2);
3638 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3640 let mut payment_event = {
3641 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
3642 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3643 check_added_monitors!(nodes[0], 1);
3645 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3646 assert_eq!(events.len(), 1);
3647 SendEvent::from_event(events.remove(0))
3650 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3651 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3653 expect_pending_htlcs_forwardable!(nodes[1]);
3655 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3656 assert_eq!(events_2.len(), 1);
3657 payment_event = SendEvent::from_event(events_2.remove(0));
3658 assert_eq!(payment_event.msgs.len(), 1);
3660 check_added_monitors!(nodes[1], 1);
3661 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3662 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3663 check_added_monitors!(nodes[2], 1);
3664 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3666 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3667 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3668 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3669 let error_message = "Channel force-closed";
3670 nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id(), error_message.to_string()).unwrap();
3671 check_closed_broadcast!(nodes[2], true);
3672 check_added_monitors!(nodes[2], 1);
3673 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(true) }, [nodes[1].node.get_our_node_id()], 100000);
3674 let commitment_tx = {
3675 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3676 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3677 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3678 // back to nodes[1] upon timeout otherwise.
3679 assert_eq!(node_txn.len(), 1);
3683 mine_transaction(&nodes[1], &commitment_tx);
3685 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3686 check_closed_broadcast!(nodes[1], true);
3687 check_added_monitors!(nodes[1], 1);
3688 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
3690 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3692 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3693 .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);
3695 mine_transaction(&nodes[2], &commitment_tx);
3696 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcast();
3697 assert_eq!(node_txn.len(), if nodes[2].connect_style.borrow().updates_best_block_first() { 2 } else { 1 });
3698 let htlc_tx = node_txn.pop().unwrap();
3699 assert_eq!(htlc_tx.input.len(), 1);
3700 assert_eq!(htlc_tx.input[0].previous_output.txid, commitment_tx.txid());
3701 assert_eq!(htlc_tx.lock_time, LockTime::ZERO); // Must be an HTLC-Success
3702 assert_eq!(htlc_tx.input[0].witness.len(), 5); // Must be an HTLC-Success
3704 check_spends!(htlc_tx, commitment_tx);
3708 fn test_dup_events_on_peer_disconnect() {
3709 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3710 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3711 // as we used to generate the event immediately upon receipt of the payment preimage in the
3712 // update_fulfill_htlc message.
3714 let chanmon_cfgs = create_chanmon_cfgs(2);
3715 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3716 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3717 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3718 create_announced_chan_between_nodes(&nodes, 0, 1);
3720 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3722 nodes[1].node.claim_funds(payment_preimage);
3723 expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3724 check_added_monitors!(nodes[1], 1);
3725 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3726 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3727 expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
3729 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3730 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3732 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3733 reconnect_args.pending_htlc_claims.0 = 1;
3734 reconnect_nodes(reconnect_args);
3735 expect_payment_path_successful!(nodes[0]);
3739 fn test_peer_disconnected_before_funding_broadcasted() {
3740 // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3741 // before the funding transaction has been broadcasted, and doesn't reconnect back within time.
3742 let chanmon_cfgs = create_chanmon_cfgs(2);
3743 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3744 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3745 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3747 // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3748 // broadcasted, even though it's created by `nodes[0]`.
3749 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();
3750 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3751 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
3752 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3753 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
3755 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3756 assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3758 assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3760 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3761 assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3763 // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3764 // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3767 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3770 // The peers disconnect before the funding is broadcasted.
3771 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3772 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3774 // The time for peers to reconnect expires.
3775 for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS {
3776 nodes[0].node.timer_tick_occurred();
3779 // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` and a
3780 // `DiscardFunding` event when the peers are disconnected and do not reconnect before the
3781 // funding transaction is broadcasted.
3782 check_closed_event!(&nodes[0], 2, ClosureReason::DisconnectedPeer, true
3783 , [nodes[1].node.get_our_node_id()], 1000000);
3784 check_closed_event!(&nodes[1], 1, ClosureReason::DisconnectedPeer, false
3785 , [nodes[0].node.get_our_node_id()], 1000000);
3789 fn test_simple_peer_disconnect() {
3790 // Test that we can reconnect when there are no lost messages
3791 let chanmon_cfgs = create_chanmon_cfgs(3);
3792 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3793 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3794 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3795 create_announced_chan_between_nodes(&nodes, 0, 1);
3796 create_announced_chan_between_nodes(&nodes, 1, 2);
3798 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3799 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3800 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3801 reconnect_args.send_channel_ready = (true, true);
3802 reconnect_nodes(reconnect_args);
3804 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3805 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3806 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3807 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3809 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3810 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3811 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3813 let (payment_preimage_3, payment_hash_3, ..) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3814 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3815 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3816 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3818 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3819 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3821 claim_payment_along_route(
3822 ClaimAlongRouteArgs::new(&nodes[0], &[&[&nodes[1], &nodes[2]]], payment_preimage_3)
3825 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3827 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3828 reconnect_args.pending_cell_htlc_fails.0 = 1;
3829 reconnect_args.pending_cell_htlc_claims.0 = 1;
3830 reconnect_nodes(reconnect_args);
3832 let events = nodes[0].node.get_and_clear_pending_events();
3833 assert_eq!(events.len(), 4);
3835 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3836 assert_eq!(payment_preimage, payment_preimage_3);
3837 assert_eq!(payment_hash, payment_hash_3);
3839 _ => panic!("Unexpected event"),
3842 Event::PaymentPathSuccessful { .. } => {},
3843 _ => panic!("Unexpected event"),
3846 Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3847 assert_eq!(payment_hash, payment_hash_5);
3848 assert!(payment_failed_permanently);
3850 _ => panic!("Unexpected event"),
3853 Event::PaymentFailed { payment_hash, .. } => {
3854 assert_eq!(payment_hash, payment_hash_5);
3856 _ => panic!("Unexpected event"),
3859 check_added_monitors(&nodes[0], 1);
3861 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3862 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3865 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3866 // Test that we can reconnect when in-flight HTLC updates get dropped
3867 let chanmon_cfgs = create_chanmon_cfgs(2);
3868 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3869 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3870 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3872 let mut as_channel_ready = None;
3873 let channel_id = if messages_delivered == 0 {
3874 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3875 as_channel_ready = Some(channel_ready);
3876 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3877 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3878 // it before the channel_reestablish message.
3881 create_announced_chan_between_nodes(&nodes, 0, 1).2
3884 let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3886 let payment_event = {
3887 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
3888 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3889 check_added_monitors!(nodes[0], 1);
3891 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3892 assert_eq!(events.len(), 1);
3893 SendEvent::from_event(events.remove(0))
3895 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3897 if messages_delivered < 2 {
3898 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3900 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3901 if messages_delivered >= 3 {
3902 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3903 check_added_monitors!(nodes[1], 1);
3904 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3906 if messages_delivered >= 4 {
3907 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3908 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3909 check_added_monitors!(nodes[0], 1);
3911 if messages_delivered >= 5 {
3912 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3913 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3914 // No commitment_signed so get_event_msg's assert(len == 1) passes
3915 check_added_monitors!(nodes[0], 1);
3917 if messages_delivered >= 6 {
3918 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3919 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3920 check_added_monitors!(nodes[1], 1);
3927 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3928 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3929 if messages_delivered < 3 {
3930 if simulate_broken_lnd {
3931 // lnd has a long-standing bug where they send a channel_ready prior to a
3932 // channel_reestablish if you reconnect prior to channel_ready time.
3934 // Here we simulate that behavior, delivering a channel_ready immediately on
3935 // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3936 // in `reconnect_nodes` but we currently don't fail based on that.
3938 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3939 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3941 // Even if the channel_ready messages get exchanged, as long as nothing further was
3942 // received on either side, both sides will need to resend them.
3943 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3944 reconnect_args.send_channel_ready = (true, true);
3945 reconnect_args.pending_htlc_adds.1 = 1;
3946 reconnect_nodes(reconnect_args);
3947 } else if messages_delivered == 3 {
3948 // nodes[0] still wants its RAA + commitment_signed
3949 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3950 reconnect_args.pending_responding_commitment_signed.0 = true;
3951 reconnect_args.pending_raa.0 = true;
3952 reconnect_nodes(reconnect_args);
3953 } else if messages_delivered == 4 {
3954 // nodes[0] still wants its commitment_signed
3955 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3956 reconnect_args.pending_responding_commitment_signed.0 = true;
3957 reconnect_nodes(reconnect_args);
3958 } else if messages_delivered == 5 {
3959 // nodes[1] still wants its final RAA
3960 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3961 reconnect_args.pending_raa.1 = true;
3962 reconnect_nodes(reconnect_args);
3963 } else if messages_delivered == 6 {
3964 // Everything was delivered...
3965 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3968 let events_1 = nodes[1].node.get_and_clear_pending_events();
3969 if messages_delivered == 0 {
3970 assert_eq!(events_1.len(), 2);
3972 Event::ChannelReady { .. } => { },
3973 _ => panic!("Unexpected event"),
3976 Event::PendingHTLCsForwardable { .. } => { },
3977 _ => panic!("Unexpected event"),
3980 assert_eq!(events_1.len(), 1);
3982 Event::PendingHTLCsForwardable { .. } => { },
3983 _ => panic!("Unexpected event"),
3987 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3988 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3989 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3991 nodes[1].node.process_pending_htlc_forwards();
3993 let events_2 = nodes[1].node.get_and_clear_pending_events();
3994 assert_eq!(events_2.len(), 1);
3996 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
3997 assert_eq!(payment_hash_1, *payment_hash);
3998 assert_eq!(amount_msat, 1_000_000);
3999 assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
4000 assert_eq!(via_channel_id, Some(channel_id));
4002 PaymentPurpose::Bolt11InvoicePayment { payment_preimage, payment_secret, .. } => {
4003 assert!(payment_preimage.is_none());
4004 assert_eq!(payment_secret_1, *payment_secret);
4006 _ => panic!("expected PaymentPurpose::Bolt11InvoicePayment")
4009 _ => panic!("Unexpected event"),
4012 nodes[1].node.claim_funds(payment_preimage_1);
4013 check_added_monitors!(nodes[1], 1);
4014 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4016 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
4017 assert_eq!(events_3.len(), 1);
4018 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
4019 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
4020 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4021 assert!(updates.update_add_htlcs.is_empty());
4022 assert!(updates.update_fail_htlcs.is_empty());
4023 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4024 assert!(updates.update_fail_malformed_htlcs.is_empty());
4025 assert!(updates.update_fee.is_none());
4026 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
4028 _ => panic!("Unexpected event"),
4031 if messages_delivered >= 1 {
4032 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
4034 let events_4 = nodes[0].node.get_and_clear_pending_events();
4035 assert_eq!(events_4.len(), 1);
4037 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4038 assert_eq!(payment_preimage_1, *payment_preimage);
4039 assert_eq!(payment_hash_1, *payment_hash);
4041 _ => panic!("Unexpected event"),
4044 if messages_delivered >= 2 {
4045 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
4046 check_added_monitors!(nodes[0], 1);
4047 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4049 if messages_delivered >= 3 {
4050 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4051 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4052 check_added_monitors!(nodes[1], 1);
4054 if messages_delivered >= 4 {
4055 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
4056 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4057 // No commitment_signed so get_event_msg's assert(len == 1) passes
4058 check_added_monitors!(nodes[1], 1);
4060 if messages_delivered >= 5 {
4061 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4062 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4063 check_added_monitors!(nodes[0], 1);
4070 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4071 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4072 if messages_delivered < 2 {
4073 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4074 reconnect_args.pending_htlc_claims.0 = 1;
4075 reconnect_nodes(reconnect_args);
4076 if messages_delivered < 1 {
4077 expect_payment_sent!(nodes[0], payment_preimage_1);
4079 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4081 } else if messages_delivered == 2 {
4082 // nodes[0] still wants its RAA + commitment_signed
4083 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4084 reconnect_args.pending_responding_commitment_signed.1 = true;
4085 reconnect_args.pending_raa.1 = true;
4086 reconnect_nodes(reconnect_args);
4087 } else if messages_delivered == 3 {
4088 // nodes[0] still wants its commitment_signed
4089 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4090 reconnect_args.pending_responding_commitment_signed.1 = true;
4091 reconnect_nodes(reconnect_args);
4092 } else if messages_delivered == 4 {
4093 // nodes[1] still wants its final RAA
4094 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4095 reconnect_args.pending_raa.0 = true;
4096 reconnect_nodes(reconnect_args);
4097 } else if messages_delivered == 5 {
4098 // Everything was delivered...
4099 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
4102 if messages_delivered == 1 || messages_delivered == 2 {
4103 expect_payment_path_successful!(nodes[0]);
4105 if messages_delivered <= 5 {
4106 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4107 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4109 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
4111 if messages_delivered > 2 {
4112 expect_payment_path_successful!(nodes[0]);
4115 // Channel should still work fine...
4116 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4117 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
4118 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4122 fn test_drop_messages_peer_disconnect_a() {
4123 do_test_drop_messages_peer_disconnect(0, true);
4124 do_test_drop_messages_peer_disconnect(0, false);
4125 do_test_drop_messages_peer_disconnect(1, false);
4126 do_test_drop_messages_peer_disconnect(2, false);
4130 fn test_drop_messages_peer_disconnect_b() {
4131 do_test_drop_messages_peer_disconnect(3, false);
4132 do_test_drop_messages_peer_disconnect(4, false);
4133 do_test_drop_messages_peer_disconnect(5, false);
4134 do_test_drop_messages_peer_disconnect(6, false);
4138 fn test_channel_ready_without_best_block_updated() {
4139 // Previously, if we were offline when a funding transaction was locked in, and then we came
4140 // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
4141 // generate a channel_ready until a later best_block_updated. This tests that we generate the
4142 // channel_ready immediately instead.
4143 let chanmon_cfgs = create_chanmon_cfgs(2);
4144 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4145 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4146 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4147 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
4149 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
4151 let conf_height = nodes[0].best_block_info().1 + 1;
4152 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4153 let block_txn = [funding_tx];
4154 let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
4155 let conf_block_header = nodes[0].get_block_header(conf_height);
4156 nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
4158 // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4159 let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4160 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4164 fn test_channel_monitor_skipping_block_when_channel_manager_is_leading() {
4165 let chanmon_cfgs = create_chanmon_cfgs(2);
4166 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4167 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4168 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4170 // Let channel_manager get ahead of chain_monitor by 1 block.
4171 // This is to emulate race-condition where newly added channel_monitor skips processing 1 block,
4172 // in case where client calls block_connect on channel_manager first and then on chain_monitor.
4173 let height_1 = nodes[0].best_block_info().1 + 1;
4174 let mut block_1 = create_dummy_block(nodes[0].best_block_hash(), height_1, Vec::new());
4176 nodes[0].blocks.lock().unwrap().push((block_1.clone(), height_1));
4177 nodes[0].node.block_connected(&block_1, height_1);
4179 // Create channel, and it gets added to chain_monitor in funding_created.
4180 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
4182 // Now, newly added channel_monitor in chain_monitor hasn't processed block_1,
4183 // but it's best_block is block_1, since that was populated by channel_manager, and channel_manager
4184 // was running ahead of chain_monitor at the time of funding_created.
4185 // Later on, subsequent blocks are connected to both channel_manager and chain_monitor.
4186 // Hence, this channel's channel_monitor skipped block_1, directly tries to process subsequent blocks.
4187 confirm_transaction_at(&nodes[0], &funding_tx, nodes[0].best_block_info().1 + 1);
4188 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4190 // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4191 let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4192 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4196 fn test_channel_monitor_skipping_block_when_channel_manager_is_lagging() {
4197 let chanmon_cfgs = create_chanmon_cfgs(2);
4198 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4199 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4200 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4202 // Let chain_monitor get ahead of channel_manager by 1 block.
4203 // This is to emulate race-condition where newly added channel_monitor skips processing 1 block,
4204 // in case where client calls block_connect on chain_monitor first and then on channel_manager.
4205 let height_1 = nodes[0].best_block_info().1 + 1;
4206 let mut block_1 = create_dummy_block(nodes[0].best_block_hash(), height_1, Vec::new());
4208 nodes[0].blocks.lock().unwrap().push((block_1.clone(), height_1));
4209 nodes[0].chain_monitor.chain_monitor.block_connected(&block_1, height_1);
4211 // Create channel, and it gets added to chain_monitor in funding_created.
4212 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
4214 // channel_manager can't really skip block_1, it should get it eventually.
4215 nodes[0].node.block_connected(&block_1, height_1);
4217 // Now, newly added channel_monitor in chain_monitor hasn't processed block_1, it's best_block is
4218 // the block before block_1, since that was populated by channel_manager, and channel_manager was
4219 // running behind at the time of funding_created.
4220 // Later on, subsequent blocks are connected to both channel_manager and chain_monitor.
4221 // Hence, this channel's channel_monitor skipped block_1, directly tries to process subsequent blocks.
4222 confirm_transaction_at(&nodes[0], &funding_tx, nodes[0].best_block_info().1 + 1);
4223 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4225 // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4226 let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4227 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4231 fn test_drop_messages_peer_disconnect_dual_htlc() {
4232 // Test that we can handle reconnecting when both sides of a channel have pending
4233 // commitment_updates when we disconnect.
4234 let chanmon_cfgs = create_chanmon_cfgs(2);
4235 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4236 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4237 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4238 create_announced_chan_between_nodes(&nodes, 0, 1);
4240 let (payment_preimage_1, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
4242 // Now try to send a second payment which will fail to send
4243 let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4244 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
4245 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
4246 check_added_monitors!(nodes[0], 1);
4248 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4249 assert_eq!(events_1.len(), 1);
4251 MessageSendEvent::UpdateHTLCs { .. } => {},
4252 _ => panic!("Unexpected event"),
4255 nodes[1].node.claim_funds(payment_preimage_1);
4256 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4257 check_added_monitors!(nodes[1], 1);
4259 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4260 assert_eq!(events_2.len(), 1);
4262 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 } } => {
4263 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4264 assert!(update_add_htlcs.is_empty());
4265 assert_eq!(update_fulfill_htlcs.len(), 1);
4266 assert!(update_fail_htlcs.is_empty());
4267 assert!(update_fail_malformed_htlcs.is_empty());
4268 assert!(update_fee.is_none());
4270 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4271 let events_3 = nodes[0].node.get_and_clear_pending_events();
4272 assert_eq!(events_3.len(), 1);
4274 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4275 assert_eq!(*payment_preimage, payment_preimage_1);
4276 assert_eq!(*payment_hash, payment_hash_1);
4278 _ => panic!("Unexpected event"),
4281 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4282 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4283 // No commitment_signed so get_event_msg's assert(len == 1) passes
4284 check_added_monitors!(nodes[0], 1);
4286 _ => panic!("Unexpected event"),
4289 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4290 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4292 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
4293 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
4295 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4296 assert_eq!(reestablish_1.len(), 1);
4297 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
4298 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
4300 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4301 assert_eq!(reestablish_2.len(), 1);
4303 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4304 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4305 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4306 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4308 assert!(as_resp.0.is_none());
4309 assert!(bs_resp.0.is_none());
4311 assert!(bs_resp.1.is_none());
4312 assert!(bs_resp.2.is_none());
4314 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4316 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4317 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4318 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4319 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4320 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4321 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4322 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4323 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4324 // No commitment_signed so get_event_msg's assert(len == 1) passes
4325 check_added_monitors!(nodes[1], 1);
4327 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4328 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4329 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4330 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4331 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4332 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4333 assert!(bs_second_commitment_signed.update_fee.is_none());
4334 check_added_monitors!(nodes[1], 1);
4336 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4337 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4338 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4339 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4340 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4341 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4342 assert!(as_commitment_signed.update_fee.is_none());
4343 check_added_monitors!(nodes[0], 1);
4345 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4346 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4347 // No commitment_signed so get_event_msg's assert(len == 1) passes
4348 check_added_monitors!(nodes[0], 1);
4350 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4351 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4352 // No commitment_signed so get_event_msg's assert(len == 1) passes
4353 check_added_monitors!(nodes[1], 1);
4355 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4356 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4357 check_added_monitors!(nodes[1], 1);
4359 expect_pending_htlcs_forwardable!(nodes[1]);
4361 let events_5 = nodes[1].node.get_and_clear_pending_events();
4362 assert_eq!(events_5.len(), 1);
4364 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4365 assert_eq!(payment_hash_2, *payment_hash);
4367 PaymentPurpose::Bolt11InvoicePayment { payment_preimage, payment_secret, .. } => {
4368 assert!(payment_preimage.is_none());
4369 assert_eq!(payment_secret_2, *payment_secret);
4371 _ => panic!("expected PaymentPurpose::Bolt11InvoicePayment")
4374 _ => panic!("Unexpected event"),
4377 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4378 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4379 check_added_monitors!(nodes[0], 1);
4381 expect_payment_path_successful!(nodes[0]);
4382 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4385 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4386 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4387 // to avoid our counterparty failing the channel.
4388 let chanmon_cfgs = create_chanmon_cfgs(2);
4389 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4390 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4391 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4393 create_announced_chan_between_nodes(&nodes, 0, 1);
4395 let our_payment_hash = if send_partial_mpp {
4396 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4397 // Use the utility function send_payment_along_path to send the payment with MPP data which
4398 // indicates there are more HTLCs coming.
4399 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.
4400 let payment_id = PaymentId([42; 32]);
4401 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
4402 RecipientOnionFields::secret_only(payment_secret), payment_id, &route).unwrap();
4403 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
4404 RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id,
4405 &None, session_privs[0]).unwrap();
4406 check_added_monitors!(nodes[0], 1);
4407 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4408 assert_eq!(events.len(), 1);
4409 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4410 // hop should *not* yet generate any PaymentClaimable event(s).
4411 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4414 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4417 let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
4418 connect_block(&nodes[0], &block);
4419 connect_block(&nodes[1], &block);
4420 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4421 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4422 block.header.prev_blockhash = block.block_hash();
4423 connect_block(&nodes[0], &block);
4424 connect_block(&nodes[1], &block);
4427 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4429 check_added_monitors!(nodes[1], 1);
4430 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4431 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4432 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4433 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4434 assert!(htlc_timeout_updates.update_fee.is_none());
4436 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4437 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4438 // 100_000 msat as u64, followed by the height at which we failed back above
4439 let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4440 expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4441 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4445 fn test_htlc_timeout() {
4446 do_test_htlc_timeout(true);
4447 do_test_htlc_timeout(false);
4450 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4451 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4452 let chanmon_cfgs = create_chanmon_cfgs(3);
4453 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4454 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4455 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4456 create_announced_chan_between_nodes(&nodes, 0, 1);
4457 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4459 // Make sure all nodes are at the same starting height
4460 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4461 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4462 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4464 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4465 let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4466 nodes[1].node.send_payment_with_route(&route, first_payment_hash,
4467 RecipientOnionFields::secret_only(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4468 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4469 check_added_monitors!(nodes[1], 1);
4471 // Now attempt to route a second payment, which should be placed in the holding cell
4472 let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4473 let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4474 sending_node.node.send_payment_with_route(&route, second_payment_hash,
4475 RecipientOnionFields::secret_only(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4477 check_added_monitors!(nodes[0], 1);
4478 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4479 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4480 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4481 expect_pending_htlcs_forwardable!(nodes[1]);
4483 check_added_monitors!(nodes[1], 0);
4485 connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4486 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4487 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4488 connect_blocks(&nodes[1], 1);
4491 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 }]);
4492 check_added_monitors!(nodes[1], 1);
4493 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4494 assert_eq!(fail_commit.len(), 1);
4495 match fail_commit[0] {
4496 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4497 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4498 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4500 _ => unreachable!(),
4502 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4504 expect_payment_failed!(nodes[1], second_payment_hash, false);
4509 fn test_holding_cell_htlc_add_timeouts() {
4510 do_test_holding_cell_htlc_add_timeouts(false);
4511 do_test_holding_cell_htlc_add_timeouts(true);
4514 macro_rules! check_spendable_outputs {
4515 ($node: expr, $keysinterface: expr) => {
4517 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4518 let mut txn = Vec::new();
4519 let mut all_outputs = Vec::new();
4520 let secp_ctx = Secp256k1::new();
4521 for event in events.drain(..) {
4523 Event::SpendableOutputs { mut outputs, channel_id: _ } => {
4524 for outp in outputs.drain(..) {
4525 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());
4526 all_outputs.push(outp);
4529 _ => panic!("Unexpected event"),
4532 if all_outputs.len() > 1 {
4533 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) {
4543 fn test_claim_sizeable_push_msat() {
4544 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
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, 100_000, 98_000_000);
4551 let error_message = "Channel force-closed";
4552 nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id(), error_message.to_string()).unwrap();
4553 check_closed_broadcast!(nodes[1], true);
4554 check_added_monitors!(nodes[1], 1);
4555 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(true) }, [nodes[0].node.get_our_node_id()], 100000);
4556 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4557 assert_eq!(node_txn.len(), 1);
4558 check_spends!(node_txn[0], chan.3);
4559 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
4561 mine_transaction(&nodes[1], &node_txn[0]);
4562 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4564 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4565 assert_eq!(spend_txn.len(), 1);
4566 assert_eq!(spend_txn[0].input.len(), 1);
4567 check_spends!(spend_txn[0], node_txn[0]);
4568 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4572 fn test_claim_on_remote_sizeable_push_msat() {
4573 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4574 // to_remote output is encumbered by a P2WPKH
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);
4579 let error_message = "Channel force-closed";
4581 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4582 nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id(), error_message.to_string()).unwrap();
4583 check_closed_broadcast!(nodes[0], true);
4584 check_added_monitors!(nodes[0], 1);
4585 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(true) }, [nodes[1].node.get_our_node_id()], 100000);
4587 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4588 assert_eq!(node_txn.len(), 1);
4589 check_spends!(node_txn[0], chan.3);
4590 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
4592 mine_transaction(&nodes[1], &node_txn[0]);
4593 check_closed_broadcast!(nodes[1], true);
4594 check_added_monitors!(nodes[1], 1);
4595 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4596 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4598 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4599 assert_eq!(spend_txn.len(), 1);
4600 check_spends!(spend_txn[0], node_txn[0]);
4604 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4605 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4606 // to_remote output is encumbered by a P2WPKH
4608 let chanmon_cfgs = create_chanmon_cfgs(2);
4609 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4610 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4611 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4613 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4614 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4615 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4616 assert_eq!(revoked_local_txn[0].input.len(), 1);
4617 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4619 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4620 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4621 check_closed_broadcast!(nodes[1], true);
4622 check_added_monitors!(nodes[1], 1);
4623 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4625 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4626 mine_transaction(&nodes[1], &node_txn[0]);
4627 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4629 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4630 assert_eq!(spend_txn.len(), 3);
4631 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4632 check_spends!(spend_txn[1], node_txn[0]);
4633 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4637 fn test_static_spendable_outputs_preimage_tx() {
4638 let chanmon_cfgs = create_chanmon_cfgs(2);
4639 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4640 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4641 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4643 // Create some initial channels
4644 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4646 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4648 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4649 assert_eq!(commitment_tx[0].input.len(), 1);
4650 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4652 // Settle A's commitment tx on B's chain
4653 nodes[1].node.claim_funds(payment_preimage);
4654 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4655 check_added_monitors!(nodes[1], 1);
4656 mine_transaction(&nodes[1], &commitment_tx[0]);
4657 check_added_monitors!(nodes[1], 1);
4658 let events = nodes[1].node.get_and_clear_pending_msg_events();
4660 MessageSendEvent::UpdateHTLCs { .. } => {},
4661 _ => panic!("Unexpected event"),
4664 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4665 _ => panic!("Unexepected event"),
4668 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4669 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4670 assert_eq!(node_txn.len(), 1);
4671 check_spends!(node_txn[0], commitment_tx[0]);
4672 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4674 mine_transaction(&nodes[1], &node_txn[0]);
4675 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4676 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4678 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4679 assert_eq!(spend_txn.len(), 1);
4680 check_spends!(spend_txn[0], node_txn[0]);
4684 fn test_static_spendable_outputs_timeout_tx() {
4685 let chanmon_cfgs = create_chanmon_cfgs(2);
4686 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4687 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4688 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4690 // Create some initial channels
4691 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4693 // Rebalance the network a bit by relaying one payment through all the channels ...
4694 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4696 let (_, our_payment_hash, ..) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4698 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4699 assert_eq!(commitment_tx[0].input.len(), 1);
4700 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4702 // Settle A's commitment tx on B' chain
4703 mine_transaction(&nodes[1], &commitment_tx[0]);
4704 check_added_monitors!(nodes[1], 1);
4705 let events = nodes[1].node.get_and_clear_pending_msg_events();
4707 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4708 _ => panic!("Unexpected event"),
4710 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4712 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4713 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4714 assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4715 check_spends!(node_txn[0], commitment_tx[0].clone());
4716 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4718 mine_transaction(&nodes[1], &node_txn[0]);
4719 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4720 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4721 expect_payment_failed!(nodes[1], our_payment_hash, false);
4723 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4724 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4725 check_spends!(spend_txn[0], commitment_tx[0]);
4726 check_spends!(spend_txn[1], node_txn[0]);
4727 check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4731 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4732 let chanmon_cfgs = create_chanmon_cfgs(2);
4733 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4734 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4735 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4737 // Create some initial channels
4738 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4740 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4741 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4742 assert_eq!(revoked_local_txn[0].input.len(), 1);
4743 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4745 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4747 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4748 check_closed_broadcast!(nodes[1], true);
4749 check_added_monitors!(nodes[1], 1);
4750 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4752 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4753 assert_eq!(node_txn.len(), 1);
4754 assert_eq!(node_txn[0].input.len(), 2);
4755 check_spends!(node_txn[0], revoked_local_txn[0]);
4757 mine_transaction(&nodes[1], &node_txn[0]);
4758 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4760 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4761 assert_eq!(spend_txn.len(), 1);
4762 check_spends!(spend_txn[0], node_txn[0]);
4766 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4767 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4768 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4769 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4770 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4771 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4773 // Create some initial channels
4774 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4776 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4777 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4778 assert_eq!(revoked_local_txn[0].input.len(), 1);
4779 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4781 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4783 // A will generate HTLC-Timeout from revoked commitment tx
4784 mine_transaction(&nodes[0], &revoked_local_txn[0]);
4785 check_closed_broadcast!(nodes[0], true);
4786 check_added_monitors!(nodes[0], 1);
4787 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4788 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4790 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4791 assert_eq!(revoked_htlc_txn.len(), 1);
4792 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4793 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4794 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4795 assert_ne!(revoked_htlc_txn[0].lock_time, LockTime::ZERO); // HTLC-Timeout
4797 // B will generate justice tx from A's revoked commitment/HTLC tx
4798 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4799 check_closed_broadcast!(nodes[1], true);
4800 check_added_monitors!(nodes[1], 1);
4801 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4803 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4804 assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4805 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4806 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4807 // transactions next...
4808 assert_eq!(node_txn[0].input.len(), 3);
4809 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4811 assert_eq!(node_txn[1].input.len(), 2);
4812 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4813 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4814 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4816 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4817 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4820 mine_transaction(&nodes[1], &node_txn[1]);
4821 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4823 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4824 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4825 assert_eq!(spend_txn.len(), 1);
4826 assert_eq!(spend_txn[0].input.len(), 1);
4827 check_spends!(spend_txn[0], node_txn[1]);
4831 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4832 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4833 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4834 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4835 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4836 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4838 // Create some initial channels
4839 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4841 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4842 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4843 assert_eq!(revoked_local_txn[0].input.len(), 1);
4844 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4846 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4847 assert_eq!(revoked_local_txn[0].output.len(), 2);
4849 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4851 // B will generate HTLC-Success from revoked commitment tx
4852 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4853 check_closed_broadcast!(nodes[1], true);
4854 check_added_monitors!(nodes[1], 1);
4855 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4856 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4858 assert_eq!(revoked_htlc_txn.len(), 1);
4859 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4860 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4861 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4863 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4864 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4865 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4867 // A will generate justice tx from B's revoked commitment/HTLC tx
4868 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4869 check_closed_broadcast!(nodes[0], true);
4870 check_added_monitors!(nodes[0], 1);
4871 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4873 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4874 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4876 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4877 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4878 // transactions next...
4879 assert_eq!(node_txn[0].input.len(), 2);
4880 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4881 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4882 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4884 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4885 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4888 assert_eq!(node_txn[1].input.len(), 1);
4889 check_spends!(node_txn[1], revoked_htlc_txn[0]);
4891 mine_transaction(&nodes[0], &node_txn[1]);
4892 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4894 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4895 // didn't try to generate any new transactions.
4897 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4898 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4899 assert_eq!(spend_txn.len(), 3);
4900 assert_eq!(spend_txn[0].input.len(), 1);
4901 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4902 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4903 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4904 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4908 fn test_onchain_to_onchain_claim() {
4909 // Test that in case of channel closure, we detect the state of output and claim HTLC
4910 // on downstream peer's remote commitment tx.
4911 // First, have C claim an HTLC against its own latest commitment transaction.
4912 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4914 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4917 let chanmon_cfgs = create_chanmon_cfgs(3);
4918 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4919 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4920 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4922 // Create some initial channels
4923 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4924 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4926 // Ensure all nodes are at the same height
4927 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4928 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4929 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4930 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4932 // Rebalance the network a bit by relaying one payment through all the channels ...
4933 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4934 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4936 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4937 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4938 check_spends!(commitment_tx[0], chan_2.3);
4939 nodes[2].node.claim_funds(payment_preimage);
4940 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4941 check_added_monitors!(nodes[2], 1);
4942 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4943 assert!(updates.update_add_htlcs.is_empty());
4944 assert!(updates.update_fail_htlcs.is_empty());
4945 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4946 assert!(updates.update_fail_malformed_htlcs.is_empty());
4948 mine_transaction(&nodes[2], &commitment_tx[0]);
4949 check_closed_broadcast!(nodes[2], true);
4950 check_added_monitors!(nodes[2], 1);
4951 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4953 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4954 assert_eq!(c_txn.len(), 1);
4955 check_spends!(c_txn[0], commitment_tx[0]);
4956 assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4957 assert!(c_txn[0].output[0].script_pubkey.is_p2wsh()); // revokeable output
4958 assert_eq!(c_txn[0].lock_time, LockTime::ZERO); // Success tx
4960 // 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
4961 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![commitment_tx[0].clone(), c_txn[0].clone()]));
4962 check_added_monitors!(nodes[1], 1);
4963 let events = nodes[1].node.get_and_clear_pending_events();
4964 assert_eq!(events.len(), 2);
4966 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4967 _ => panic!("Unexpected event"),
4970 Event::PaymentForwarded { total_fee_earned_msat, prev_channel_id, claim_from_onchain_tx,
4971 next_channel_id, outbound_amount_forwarded_msat, ..
4973 assert_eq!(total_fee_earned_msat, Some(1000));
4974 assert_eq!(prev_channel_id, Some(chan_1.2));
4975 assert_eq!(claim_from_onchain_tx, true);
4976 assert_eq!(next_channel_id, Some(chan_2.2));
4977 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
4979 _ => panic!("Unexpected event"),
4981 check_added_monitors!(nodes[1], 1);
4982 let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4983 assert_eq!(msg_events.len(), 3);
4984 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut msg_events);
4985 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut msg_events);
4987 match nodes_2_event {
4988 MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { .. }, node_id: _ } => {},
4989 _ => panic!("Unexpected event"),
4992 match nodes_0_event {
4993 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, .. } } => {
4994 assert!(update_add_htlcs.is_empty());
4995 assert!(update_fail_htlcs.is_empty());
4996 assert_eq!(update_fulfill_htlcs.len(), 1);
4997 assert!(update_fail_malformed_htlcs.is_empty());
4998 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5000 _ => panic!("Unexpected event"),
5003 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
5004 match msg_events[0] {
5005 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5006 _ => panic!("Unexpected event"),
5009 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5010 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5011 mine_transaction(&nodes[1], &commitment_tx[0]);
5012 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
5013 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5014 // ChannelMonitor: HTLC-Success tx
5015 assert_eq!(b_txn.len(), 1);
5016 check_spends!(b_txn[0], commitment_tx[0]);
5017 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5018 assert!(b_txn[0].output[0].script_pubkey.is_p2wpkh()); // direct payment
5019 assert_eq!(b_txn[0].lock_time.to_consensus_u32(), nodes[1].best_block_info().1); // Success tx
5021 check_closed_broadcast!(nodes[1], true);
5022 check_added_monitors!(nodes[1], 1);
5026 fn test_duplicate_payment_hash_one_failure_one_success() {
5027 // Topology : A --> B --> C --> D
5028 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5029 // Note that because C will refuse to generate two payment secrets for the same payment hash,
5030 // we forward one of the payments onwards to D.
5031 let chanmon_cfgs = create_chanmon_cfgs(4);
5032 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5033 // When this test was written, the default base fee floated based on the HTLC count.
5034 // It is now fixed, so we simply set the fee to the expected value here.
5035 let mut config = test_default_channel_config();
5036 config.channel_config.forwarding_fee_base_msat = 196;
5037 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5038 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5039 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5041 create_announced_chan_between_nodes(&nodes, 0, 1);
5042 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5043 create_announced_chan_between_nodes(&nodes, 2, 3);
5045 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5046 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5047 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5048 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5049 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5051 let (our_payment_preimage, duplicate_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
5053 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
5054 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5055 // script push size limit so that the below script length checks match
5056 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5057 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV - 40)
5058 .with_bolt11_features(nodes[3].node.bolt11_invoice_features()).unwrap();
5059 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000);
5060 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
5062 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5063 assert_eq!(commitment_txn[0].input.len(), 1);
5064 check_spends!(commitment_txn[0], chan_2.3);
5066 mine_transaction(&nodes[1], &commitment_txn[0]);
5067 check_closed_broadcast!(nodes[1], true);
5068 check_added_monitors!(nodes[1], 1);
5069 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
5070 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
5072 let htlc_timeout_tx;
5073 { // Extract one of the two HTLC-Timeout transaction
5074 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5075 // ChannelMonitor: timeout tx * 2-or-3
5076 assert!(node_txn.len() == 2 || node_txn.len() == 3);
5078 check_spends!(node_txn[0], commitment_txn[0]);
5079 assert_eq!(node_txn[0].input.len(), 1);
5080 assert_eq!(node_txn[0].output.len(), 1);
5082 if node_txn.len() > 2 {
5083 check_spends!(node_txn[1], commitment_txn[0]);
5084 assert_eq!(node_txn[1].input.len(), 1);
5085 assert_eq!(node_txn[1].output.len(), 1);
5086 assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
5088 check_spends!(node_txn[2], commitment_txn[0]);
5089 assert_eq!(node_txn[2].input.len(), 1);
5090 assert_eq!(node_txn[2].output.len(), 1);
5091 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
5093 check_spends!(node_txn[1], commitment_txn[0]);
5094 assert_eq!(node_txn[1].input.len(), 1);
5095 assert_eq!(node_txn[1].output.len(), 1);
5096 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
5099 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5100 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5101 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
5102 // (with value 900 sats) will be claimed in the below `claim_funds` call.
5103 if node_txn.len() > 2 {
5104 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5105 htlc_timeout_tx = if node_txn[2].output[0].value.to_sat() < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
5107 htlc_timeout_tx = if node_txn[0].output[0].value.to_sat() < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
5111 nodes[2].node.claim_funds(our_payment_preimage);
5112 expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
5114 mine_transaction(&nodes[2], &commitment_txn[0]);
5115 check_added_monitors!(nodes[2], 2);
5116 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5117 let events = nodes[2].node.get_and_clear_pending_msg_events();
5119 MessageSendEvent::UpdateHTLCs { .. } => {},
5120 _ => panic!("Unexpected event"),
5123 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5124 _ => panic!("Unexepected event"),
5126 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5127 assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
5128 check_spends!(htlc_success_txn[0], commitment_txn[0]);
5129 check_spends!(htlc_success_txn[1], commitment_txn[0]);
5130 assert_eq!(htlc_success_txn[0].input.len(), 1);
5131 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5132 assert_eq!(htlc_success_txn[1].input.len(), 1);
5133 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5134 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5135 assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5137 mine_transaction(&nodes[1], &htlc_timeout_tx);
5138 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5139 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 }]);
5140 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5141 assert!(htlc_updates.update_add_htlcs.is_empty());
5142 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5143 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5144 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5145 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5146 check_added_monitors!(nodes[1], 1);
5148 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5149 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5151 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5153 expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5155 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5156 mine_transaction(&nodes[1], &htlc_success_txn[1]);
5157 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
5158 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5159 assert!(updates.update_add_htlcs.is_empty());
5160 assert!(updates.update_fail_htlcs.is_empty());
5161 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5162 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5163 assert!(updates.update_fail_malformed_htlcs.is_empty());
5164 check_added_monitors!(nodes[1], 1);
5166 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5167 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5168 expect_payment_sent(&nodes[0], our_payment_preimage, None, true, true);
5172 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5173 let chanmon_cfgs = create_chanmon_cfgs(2);
5174 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5175 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5176 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5178 // Create some initial channels
5179 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5181 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
5182 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5183 assert_eq!(local_txn.len(), 1);
5184 assert_eq!(local_txn[0].input.len(), 1);
5185 check_spends!(local_txn[0], chan_1.3);
5187 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5188 nodes[1].node.claim_funds(payment_preimage);
5189 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
5190 check_added_monitors!(nodes[1], 1);
5192 mine_transaction(&nodes[1], &local_txn[0]);
5193 check_added_monitors!(nodes[1], 1);
5194 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
5195 let events = nodes[1].node.get_and_clear_pending_msg_events();
5197 MessageSendEvent::UpdateHTLCs { .. } => {},
5198 _ => panic!("Unexpected event"),
5201 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5202 _ => panic!("Unexepected event"),
5205 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5206 assert_eq!(node_txn.len(), 1);
5207 assert_eq!(node_txn[0].input.len(), 1);
5208 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5209 check_spends!(node_txn[0], local_txn[0]);
5213 mine_transaction(&nodes[1], &node_tx);
5214 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5216 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5217 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5218 assert_eq!(spend_txn.len(), 1);
5219 assert_eq!(spend_txn[0].input.len(), 1);
5220 check_spends!(spend_txn[0], node_tx);
5221 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5224 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5225 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5226 // unrevoked commitment transaction.
5227 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5228 // a remote RAA before they could be failed backwards (and combinations thereof).
5229 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5230 // use the same payment hashes.
5231 // Thus, we use a six-node network:
5236 // And test where C fails back to A/B when D announces its latest commitment transaction
5237 let chanmon_cfgs = create_chanmon_cfgs(6);
5238 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5239 // When this test was written, the default base fee floated based on the HTLC count.
5240 // It is now fixed, so we simply set the fee to the expected value here.
5241 let mut config = test_default_channel_config();
5242 config.channel_config.forwarding_fee_base_msat = 196;
5243 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5244 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5245 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5247 let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2);
5248 let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5249 let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5250 let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
5251 let chan_3_5 = create_announced_chan_between_nodes(&nodes, 3, 5);
5253 // Rebalance and check output sanity...
5254 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5255 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5256 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
5258 let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
5259 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().context().holder_dust_limit_satoshis;
5261 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
5263 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
5264 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5266 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
5268 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
5270 let (_, payment_hash_3, ..) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5272 let (_, payment_hash_4, ..) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5273 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5275 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());
5277 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());
5280 let (_, payment_hash_5, ..) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5282 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5283 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
5286 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
5288 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5289 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());
5291 // Double-check that six of the new HTLC were added
5292 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5293 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5294 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5295 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5297 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5298 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5299 nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5300 nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5301 nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5302 nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5303 check_added_monitors!(nodes[4], 0);
5305 let failed_destinations = vec![
5306 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5307 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5308 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5309 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5311 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5312 check_added_monitors!(nodes[4], 1);
5314 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5315 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5316 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5317 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5318 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5319 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5321 // Fail 3rd below-dust and 7th above-dust HTLCs
5322 nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5323 nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5324 check_added_monitors!(nodes[5], 0);
5326 let failed_destinations_2 = vec![
5327 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5328 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5330 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5331 check_added_monitors!(nodes[5], 1);
5333 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5334 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5335 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5336 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5338 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5340 // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5341 let failed_destinations_3 = vec![
5342 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5343 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5344 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5345 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5346 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5347 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5349 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5350 check_added_monitors!(nodes[3], 1);
5351 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5352 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5353 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5354 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5355 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5356 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5357 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5358 if deliver_last_raa {
5359 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5361 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5364 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5365 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5366 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5367 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5369 // We now broadcast the latest commitment transaction, which *should* result in failures for
5370 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5371 // the non-broadcast above-dust HTLCs.
5373 // Alternatively, we may broadcast the previous commitment transaction, which should only
5374 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5375 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5377 if announce_latest {
5378 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5380 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5382 let events = nodes[2].node.get_and_clear_pending_events();
5383 let close_event = if deliver_last_raa {
5384 assert_eq!(events.len(), 2 + 6);
5385 events.last().clone().unwrap()
5387 assert_eq!(events.len(), 1);
5388 events.last().clone().unwrap()
5391 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5392 _ => panic!("Unexpected event"),
5395 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5396 check_closed_broadcast!(nodes[2], true);
5397 if deliver_last_raa {
5398 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[1..2], true);
5400 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();
5401 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5403 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5404 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5406 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5409 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5411 check_added_monitors!(nodes[2], 3);
5413 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5414 assert_eq!(cs_msgs.len(), 2);
5415 let mut a_done = false;
5416 for msg in cs_msgs {
5418 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5419 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5420 // should be failed-backwards here.
5421 let target = if *node_id == nodes[0].node.get_our_node_id() {
5422 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5423 for htlc in &updates.update_fail_htlcs {
5424 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 });
5426 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5431 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5432 for htlc in &updates.update_fail_htlcs {
5433 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5435 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5436 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5439 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5440 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5441 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5442 if announce_latest {
5443 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5444 if *node_id == nodes[0].node.get_our_node_id() {
5445 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5448 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5450 _ => panic!("Unexpected event"),
5454 let as_events = nodes[0].node.get_and_clear_pending_events();
5455 assert_eq!(as_events.len(), if announce_latest { 10 } else { 6 });
5456 let mut as_faileds = new_hash_set();
5457 let mut as_updates = 0;
5458 for event in as_events.iter() {
5459 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5460 assert!(as_faileds.insert(*payment_hash));
5461 if *payment_hash != payment_hash_2 {
5462 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5464 assert!(!payment_failed_permanently);
5466 if let PathFailure::OnPath { network_update: Some(_) } = failure {
5469 } else if let &Event::PaymentFailed { .. } = event {
5470 } else { panic!("Unexpected event"); }
5472 assert!(as_faileds.contains(&payment_hash_1));
5473 assert!(as_faileds.contains(&payment_hash_2));
5474 if announce_latest {
5475 assert!(as_faileds.contains(&payment_hash_3));
5476 assert!(as_faileds.contains(&payment_hash_5));
5478 assert!(as_faileds.contains(&payment_hash_6));
5480 let bs_events = nodes[1].node.get_and_clear_pending_events();
5481 assert_eq!(bs_events.len(), if announce_latest { 8 } else { 6 });
5482 let mut bs_faileds = new_hash_set();
5483 let mut bs_updates = 0;
5484 for event in bs_events.iter() {
5485 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5486 assert!(bs_faileds.insert(*payment_hash));
5487 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5488 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5490 assert!(!payment_failed_permanently);
5492 if let PathFailure::OnPath { network_update: Some(_) } = failure {
5495 } else if let &Event::PaymentFailed { .. } = event {
5496 } else { panic!("Unexpected event"); }
5498 assert!(bs_faileds.contains(&payment_hash_1));
5499 assert!(bs_faileds.contains(&payment_hash_2));
5500 if announce_latest {
5501 assert!(bs_faileds.contains(&payment_hash_4));
5503 assert!(bs_faileds.contains(&payment_hash_5));
5505 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5506 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5507 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5508 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5509 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5510 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5514 fn test_fail_backwards_latest_remote_announce_a() {
5515 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5519 fn test_fail_backwards_latest_remote_announce_b() {
5520 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5524 fn test_fail_backwards_previous_remote_announce() {
5525 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5526 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5527 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5531 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5532 let chanmon_cfgs = create_chanmon_cfgs(2);
5533 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5534 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5535 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5537 // Create some initial channels
5538 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5540 let (_, our_payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5541 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5542 assert_eq!(local_txn[0].input.len(), 1);
5543 check_spends!(local_txn[0], chan_1.3);
5545 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5546 mine_transaction(&nodes[0], &local_txn[0]);
5547 check_closed_broadcast!(nodes[0], true);
5548 check_added_monitors!(nodes[0], 1);
5549 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5550 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5552 let htlc_timeout = {
5553 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5554 assert_eq!(node_txn.len(), 1);
5555 assert_eq!(node_txn[0].input.len(), 1);
5556 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5557 check_spends!(node_txn[0], local_txn[0]);
5561 mine_transaction(&nodes[0], &htlc_timeout);
5562 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5563 expect_payment_failed!(nodes[0], our_payment_hash, false);
5565 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5566 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5567 assert_eq!(spend_txn.len(), 3);
5568 check_spends!(spend_txn[0], local_txn[0]);
5569 assert_eq!(spend_txn[1].input.len(), 1);
5570 check_spends!(spend_txn[1], htlc_timeout);
5571 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5572 assert_eq!(spend_txn[2].input.len(), 2);
5573 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5574 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5575 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5579 fn test_key_derivation_params() {
5580 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5581 // manager rotation to test that `channel_keys_id` returned in
5582 // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5583 // then derive a `delayed_payment_key`.
5585 let chanmon_cfgs = create_chanmon_cfgs(3);
5587 // We manually create the node configuration to backup the seed.
5588 let seed = [42; 32];
5589 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5590 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);
5591 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[0].logger));
5592 let scorer = RwLock::new(test_utils::TestScorer::new());
5593 let router = test_utils::TestRouter::new(network_graph.clone(), &chanmon_cfgs[0].logger, &scorer);
5594 let message_router = test_utils::TestMessageRouter::new(network_graph.clone(), &keys_manager);
5595 let node = NodeCfg { chain_source: &chanmon_cfgs[0].chain_source, logger: &chanmon_cfgs[0].logger, tx_broadcaster: &chanmon_cfgs[0].tx_broadcaster, fee_estimator: &chanmon_cfgs[0].fee_estimator, router, message_router, chain_monitor, keys_manager: &keys_manager, network_graph, node_seed: seed, override_init_features: alloc::rc::Rc::new(core::cell::RefCell::new(None)) };
5596 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5597 node_cfgs.remove(0);
5598 node_cfgs.insert(0, node);
5600 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5601 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5603 // Create some initial channels
5604 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5606 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2);
5607 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5608 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5610 // Ensure all nodes are at the same height
5611 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5612 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5613 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5614 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5616 let (_, our_payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5617 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5618 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5619 assert_eq!(local_txn_1[0].input.len(), 1);
5620 check_spends!(local_txn_1[0], chan_1.3);
5622 // We check funding pubkey are unique
5623 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]));
5624 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]));
5625 if from_0_funding_key_0 == from_1_funding_key_0
5626 || from_0_funding_key_0 == from_1_funding_key_1
5627 || from_0_funding_key_1 == from_1_funding_key_0
5628 || from_0_funding_key_1 == from_1_funding_key_1 {
5629 panic!("Funding pubkeys aren't unique");
5632 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5633 mine_transaction(&nodes[0], &local_txn_1[0]);
5634 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5635 check_closed_broadcast!(nodes[0], true);
5636 check_added_monitors!(nodes[0], 1);
5637 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5639 let htlc_timeout = {
5640 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5641 assert_eq!(node_txn.len(), 1);
5642 assert_eq!(node_txn[0].input.len(), 1);
5643 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5644 check_spends!(node_txn[0], local_txn_1[0]);
5648 mine_transaction(&nodes[0], &htlc_timeout);
5649 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5650 expect_payment_failed!(nodes[0], our_payment_hash, false);
5652 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5653 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5654 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5655 assert_eq!(spend_txn.len(), 3);
5656 check_spends!(spend_txn[0], local_txn_1[0]);
5657 assert_eq!(spend_txn[1].input.len(), 1);
5658 check_spends!(spend_txn[1], htlc_timeout);
5659 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5660 assert_eq!(spend_txn[2].input.len(), 2);
5661 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5662 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5663 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5667 fn test_static_output_closing_tx() {
5668 let chanmon_cfgs = create_chanmon_cfgs(2);
5669 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5670 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5671 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5673 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5675 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5676 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5678 mine_transaction(&nodes[0], &closing_tx);
5679 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyInitiatedCooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
5680 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5682 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5683 assert_eq!(spend_txn.len(), 1);
5684 check_spends!(spend_txn[0], closing_tx);
5686 mine_transaction(&nodes[1], &closing_tx);
5687 check_closed_event!(nodes[1], 1, ClosureReason::LocallyInitiatedCooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
5688 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5690 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5691 assert_eq!(spend_txn.len(), 1);
5692 check_spends!(spend_txn[0], closing_tx);
5695 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5696 let chanmon_cfgs = create_chanmon_cfgs(2);
5697 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5698 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5699 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5700 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5702 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5704 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5705 // present in B's local commitment transaction, but none of A's commitment transactions.
5706 nodes[1].node.claim_funds(payment_preimage);
5707 check_added_monitors!(nodes[1], 1);
5708 expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5710 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5711 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5712 expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
5714 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5715 check_added_monitors!(nodes[0], 1);
5716 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5717 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5718 check_added_monitors!(nodes[1], 1);
5720 let starting_block = nodes[1].best_block_info();
5721 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5722 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5723 connect_block(&nodes[1], &block);
5724 block.header.prev_blockhash = block.block_hash();
5726 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5727 check_closed_broadcast!(nodes[1], true);
5728 check_added_monitors!(nodes[1], 1);
5729 check_closed_event!(nodes[1], 1, ClosureReason::HTLCsTimedOut, [nodes[0].node.get_our_node_id()], 100000);
5732 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5733 let chanmon_cfgs = create_chanmon_cfgs(2);
5734 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5735 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5736 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5737 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5739 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5740 nodes[0].node.send_payment_with_route(&route, payment_hash,
5741 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
5742 check_added_monitors!(nodes[0], 1);
5744 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5746 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5747 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5748 // to "time out" the HTLC.
5750 let starting_block = nodes[1].best_block_info();
5751 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5753 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5754 connect_block(&nodes[0], &block);
5755 block.header.prev_blockhash = block.block_hash();
5757 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5758 check_closed_broadcast!(nodes[0], true);
5759 check_added_monitors!(nodes[0], 1);
5760 check_closed_event!(nodes[0], 1, ClosureReason::HTLCsTimedOut, [nodes[1].node.get_our_node_id()], 100000);
5763 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5764 let chanmon_cfgs = create_chanmon_cfgs(3);
5765 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5766 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5767 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5768 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5770 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5771 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5772 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5773 // actually revoked.
5774 let htlc_value = if use_dust { 50000 } else { 3000000 };
5775 let (_, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5776 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5777 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5778 check_added_monitors!(nodes[1], 1);
5780 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5781 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5782 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5783 check_added_monitors!(nodes[0], 1);
5784 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5785 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5786 check_added_monitors!(nodes[1], 1);
5787 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5788 check_added_monitors!(nodes[1], 1);
5789 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5791 if check_revoke_no_close {
5792 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5793 check_added_monitors!(nodes[0], 1);
5796 let starting_block = nodes[1].best_block_info();
5797 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5798 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5799 connect_block(&nodes[0], &block);
5800 block.header.prev_blockhash = block.block_hash();
5802 if !check_revoke_no_close {
5803 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5804 check_closed_broadcast!(nodes[0], true);
5805 check_added_monitors!(nodes[0], 1);
5806 check_closed_event!(nodes[0], 1, ClosureReason::HTLCsTimedOut, [nodes[1].node.get_our_node_id()], 100000);
5808 expect_payment_failed!(nodes[0], our_payment_hash, true);
5812 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5813 // There are only a few cases to test here:
5814 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5815 // broadcastable commitment transactions result in channel closure,
5816 // * its included in an unrevoked-but-previous remote commitment transaction,
5817 // * its included in the latest remote or local commitment transactions.
5818 // We test each of the three possible commitment transactions individually and use both dust and
5820 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5821 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5822 // tested for at least one of the cases in other tests.
5824 fn htlc_claim_single_commitment_only_a() {
5825 do_htlc_claim_local_commitment_only(true);
5826 do_htlc_claim_local_commitment_only(false);
5828 do_htlc_claim_current_remote_commitment_only(true);
5829 do_htlc_claim_current_remote_commitment_only(false);
5833 fn htlc_claim_single_commitment_only_b() {
5834 do_htlc_claim_previous_remote_commitment_only(true, false);
5835 do_htlc_claim_previous_remote_commitment_only(false, false);
5836 do_htlc_claim_previous_remote_commitment_only(true, true);
5837 do_htlc_claim_previous_remote_commitment_only(false, true);
5842 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5843 let chanmon_cfgs = create_chanmon_cfgs(2);
5844 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5845 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5846 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5847 // Force duplicate randomness for every get-random call
5848 for node in nodes.iter() {
5849 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5852 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5853 let channel_value_satoshis=10000;
5854 let push_msat=10001;
5855 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).unwrap();
5856 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5857 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5858 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5860 // Create a second channel with the same random values. This used to panic due to a colliding
5861 // channel_id, but now panics due to a colliding outbound SCID alias.
5862 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).is_err());
5866 fn bolt2_open_channel_sending_node_checks_part2() {
5867 let chanmon_cfgs = create_chanmon_cfgs(2);
5868 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5869 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5870 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5872 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5873 let channel_value_satoshis=2^24;
5874 let push_msat=10001;
5875 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).is_err());
5877 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5878 let channel_value_satoshis=10000;
5879 // Test when push_msat is equal to 1000 * funding_satoshis.
5880 let push_msat=1000*channel_value_satoshis+1;
5881 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).is_err());
5883 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5884 let channel_value_satoshis=10000;
5885 let push_msat=10001;
5886 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
5887 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5888 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.common_fields.dust_limit_satoshis);
5890 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5891 // 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
5892 assert!(node0_to_1_send_open_channel.common_fields.channel_flags<=1);
5894 // 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.
5895 assert!(BREAKDOWN_TIMEOUT>0);
5896 assert!(node0_to_1_send_open_channel.common_fields.to_self_delay==BREAKDOWN_TIMEOUT);
5898 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5899 let chain_hash = ChainHash::using_genesis_block(Network::Testnet);
5900 assert_eq!(node0_to_1_send_open_channel.common_fields.chain_hash, chain_hash);
5902 // 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.
5903 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.common_fields.funding_pubkey.serialize()).is_ok());
5904 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.common_fields.revocation_basepoint.serialize()).is_ok());
5905 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.common_fields.htlc_basepoint.serialize()).is_ok());
5906 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.common_fields.payment_basepoint.serialize()).is_ok());
5907 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.common_fields.delayed_payment_basepoint.serialize()).is_ok());
5911 fn bolt2_open_channel_sane_dust_limit() {
5912 let chanmon_cfgs = create_chanmon_cfgs(2);
5913 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5914 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5915 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5917 let channel_value_satoshis=1000000;
5918 let push_msat=10001;
5919 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).unwrap();
5920 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5921 node0_to_1_send_open_channel.common_fields.dust_limit_satoshis = 547;
5922 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5924 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5925 let events = nodes[1].node.get_and_clear_pending_msg_events();
5926 let err_msg = match events[0] {
5927 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5930 _ => panic!("Unexpected event"),
5932 assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5935 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5936 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5937 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5938 // is no longer affordable once it's freed.
5940 fn test_fail_holding_cell_htlc_upon_free() {
5941 let chanmon_cfgs = create_chanmon_cfgs(2);
5942 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5943 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5944 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5945 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5947 // First nodes[0] generates an update_fee, setting the channel's
5948 // pending_update_fee.
5950 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5951 *feerate_lock += 20;
5953 nodes[0].node.timer_tick_occurred();
5954 check_added_monitors!(nodes[0], 1);
5956 let events = nodes[0].node.get_and_clear_pending_msg_events();
5957 assert_eq!(events.len(), 1);
5958 let (update_msg, commitment_signed) = match events[0] {
5959 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5960 (update_fee.as_ref(), commitment_signed)
5962 _ => panic!("Unexpected event"),
5965 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5967 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5968 let channel_reserve = chan_stat.channel_reserve_msat;
5969 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5970 let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
5972 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5973 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
5974 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5976 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5977 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5978 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5979 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5980 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5982 // Flush the pending fee update.
5983 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5984 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5985 check_added_monitors!(nodes[1], 1);
5986 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5987 check_added_monitors!(nodes[0], 1);
5989 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5990 // HTLC, but now that the fee has been raised the payment will now fail, causing
5991 // us to surface its failure to the user.
5992 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5993 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5994 nodes[0].logger.assert_log("lightning::ln::channel", format!("Freeing holding cell with 1 HTLC updates in channel {}", chan.2), 1);
5996 // Check that the payment failed to be sent out.
5997 let events = nodes[0].node.get_and_clear_pending_events();
5998 assert_eq!(events.len(), 2);
6000 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
6001 assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
6002 assert_eq!(our_payment_hash.clone(), *payment_hash);
6003 assert_eq!(*payment_failed_permanently, false);
6004 assert_eq!(*short_channel_id, Some(route.paths[0].hops[0].short_channel_id));
6006 _ => panic!("Unexpected event"),
6009 &Event::PaymentFailed { ref payment_hash, .. } => {
6010 assert_eq!(our_payment_hash.clone(), *payment_hash);
6012 _ => panic!("Unexpected event"),
6016 // Test that if multiple HTLCs are released from the holding cell and one is
6017 // valid but the other is no longer valid upon release, the valid HTLC can be
6018 // successfully completed while the other one fails as expected.
6020 fn test_free_and_fail_holding_cell_htlcs() {
6021 let chanmon_cfgs = create_chanmon_cfgs(2);
6022 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6023 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6024 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6025 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6027 // First nodes[0] generates an update_fee, setting the channel's
6028 // pending_update_fee.
6030 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6031 *feerate_lock += 200;
6033 nodes[0].node.timer_tick_occurred();
6034 check_added_monitors!(nodes[0], 1);
6036 let events = nodes[0].node.get_and_clear_pending_msg_events();
6037 assert_eq!(events.len(), 1);
6038 let (update_msg, commitment_signed) = match events[0] {
6039 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6040 (update_fee.as_ref(), commitment_signed)
6042 _ => panic!("Unexpected event"),
6045 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6047 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6048 let channel_reserve = chan_stat.channel_reserve_msat;
6049 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6050 let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
6052 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6054 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features) - amt_1;
6055 let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
6056 let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
6058 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6059 nodes[0].node.send_payment_with_route(&route_1, payment_hash_1,
6060 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
6061 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6062 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6063 let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
6064 nodes[0].node.send_payment_with_route(&route_2, payment_hash_2,
6065 RecipientOnionFields::secret_only(payment_secret_2), payment_id_2).unwrap();
6066 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6067 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6069 // Flush the pending fee update.
6070 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6071 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6072 check_added_monitors!(nodes[1], 1);
6073 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6074 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6075 check_added_monitors!(nodes[0], 2);
6077 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6078 // but now that the fee has been raised the second payment will now fail, causing us
6079 // to surface its failure to the user. The first payment should succeed.
6080 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6081 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6082 nodes[0].logger.assert_log("lightning::ln::channel", format!("Freeing holding cell with 2 HTLC updates in channel {}", chan.2), 1);
6084 // Check that the second payment failed to be sent out.
6085 let events = nodes[0].node.get_and_clear_pending_events();
6086 assert_eq!(events.len(), 2);
6088 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
6089 assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6090 assert_eq!(payment_hash_2.clone(), *payment_hash);
6091 assert_eq!(*payment_failed_permanently, false);
6092 assert_eq!(*short_channel_id, Some(route_2.paths[0].hops[0].short_channel_id));
6094 _ => panic!("Unexpected event"),
6097 &Event::PaymentFailed { ref payment_hash, .. } => {
6098 assert_eq!(payment_hash_2.clone(), *payment_hash);
6100 _ => panic!("Unexpected event"),
6103 // Complete the first payment and the RAA from the fee update.
6104 let (payment_event, send_raa_event) = {
6105 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6106 assert_eq!(msgs.len(), 2);
6107 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6109 let raa = match send_raa_event {
6110 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6111 _ => panic!("Unexpected event"),
6113 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6114 check_added_monitors!(nodes[1], 1);
6115 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6116 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6117 let events = nodes[1].node.get_and_clear_pending_events();
6118 assert_eq!(events.len(), 1);
6120 Event::PendingHTLCsForwardable { .. } => {},
6121 _ => panic!("Unexpected event"),
6123 nodes[1].node.process_pending_htlc_forwards();
6124 let events = nodes[1].node.get_and_clear_pending_events();
6125 assert_eq!(events.len(), 1);
6127 Event::PaymentClaimable { .. } => {},
6128 _ => panic!("Unexpected event"),
6130 nodes[1].node.claim_funds(payment_preimage_1);
6131 check_added_monitors!(nodes[1], 1);
6132 expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
6134 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6135 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6136 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6137 expect_payment_sent!(nodes[0], payment_preimage_1);
6140 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6141 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6142 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6145 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6146 let chanmon_cfgs = create_chanmon_cfgs(3);
6147 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6148 // Avoid having to include routing fees in calculations
6149 let mut config = test_default_channel_config();
6150 config.channel_config.forwarding_fee_base_msat = 0;
6151 config.channel_config.forwarding_fee_proportional_millionths = 0;
6152 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6153 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6154 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6155 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
6157 // First nodes[1] generates an update_fee, setting the channel's
6158 // pending_update_fee.
6160 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6161 *feerate_lock += 20;
6163 nodes[1].node.timer_tick_occurred();
6164 check_added_monitors!(nodes[1], 1);
6166 let events = nodes[1].node.get_and_clear_pending_msg_events();
6167 assert_eq!(events.len(), 1);
6168 let (update_msg, commitment_signed) = match events[0] {
6169 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6170 (update_fee.as_ref(), commitment_signed)
6172 _ => panic!("Unexpected event"),
6175 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6177 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan_0_1.2);
6178 let channel_reserve = chan_stat.channel_reserve_msat;
6179 let feerate = get_feerate!(nodes[0], nodes[1], chan_0_1.2);
6180 let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_0_1.2);
6182 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6183 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
6184 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6185 let payment_event = {
6186 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6187 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6188 check_added_monitors!(nodes[0], 1);
6190 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6191 assert_eq!(events.len(), 1);
6193 SendEvent::from_event(events.remove(0))
6195 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6196 check_added_monitors!(nodes[1], 0);
6197 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6198 expect_pending_htlcs_forwardable!(nodes[1]);
6200 chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
6201 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6203 // Flush the pending fee update.
6204 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6205 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6206 check_added_monitors!(nodes[2], 1);
6207 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6208 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6209 check_added_monitors!(nodes[1], 2);
6211 // A final RAA message is generated to finalize the fee update.
6212 let events = nodes[1].node.get_and_clear_pending_msg_events();
6213 assert_eq!(events.len(), 1);
6215 let raa_msg = match &events[0] {
6216 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6219 _ => panic!("Unexpected event"),
6222 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6223 check_added_monitors!(nodes[2], 1);
6224 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6226 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6227 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6228 assert_eq!(process_htlc_forwards_event.len(), 2);
6229 match &process_htlc_forwards_event[1] {
6230 &Event::PendingHTLCsForwardable { .. } => {},
6231 _ => panic!("Unexpected event"),
6234 // In response, we call ChannelManager's process_pending_htlc_forwards
6235 nodes[1].node.process_pending_htlc_forwards();
6236 check_added_monitors!(nodes[1], 1);
6238 // This causes the HTLC to be failed backwards.
6239 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6240 assert_eq!(fail_event.len(), 1);
6241 let (fail_msg, commitment_signed) = match &fail_event[0] {
6242 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6243 assert_eq!(updates.update_add_htlcs.len(), 0);
6244 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6245 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6246 assert_eq!(updates.update_fail_htlcs.len(), 1);
6247 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6249 _ => panic!("Unexpected event"),
6252 // Pass the failure messages back to nodes[0].
6253 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6254 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6256 // Complete the HTLC failure+removal process.
6257 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6258 check_added_monitors!(nodes[0], 1);
6259 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6260 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6261 check_added_monitors!(nodes[1], 2);
6262 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6263 assert_eq!(final_raa_event.len(), 1);
6264 let raa = match &final_raa_event[0] {
6265 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6266 _ => panic!("Unexpected event"),
6268 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6269 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6270 check_added_monitors!(nodes[0], 1);
6274 fn test_payment_route_reaching_same_channel_twice() {
6275 //A route should not go through the same channel twice
6276 //It is enforced when constructing a route.
6277 let chanmon_cfgs = create_chanmon_cfgs(2);
6278 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6279 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6280 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6281 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6283 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6284 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
6285 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);
6287 // Extend the path by itself, essentially simulating route going through same channel twice
6288 let cloned_hops = route.paths[0].hops.clone();
6289 route.paths[0].hops.extend_from_slice(&cloned_hops);
6291 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6292 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6293 ), false, APIError::InvalidRoute { ref err },
6294 assert_eq!(err, &"Path went through the same channel twice"));
6297 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6298 // 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.
6299 //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.
6302 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6303 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6304 let chanmon_cfgs = create_chanmon_cfgs(2);
6305 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6306 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6307 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6308 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6310 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6311 route.paths[0].hops[0].fee_msat = 100;
6313 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6314 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6315 ), true, APIError::ChannelUnavailable { .. }, {});
6316 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6320 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6321 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
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, 100000, 95000000);
6328 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6329 route.paths[0].hops[0].fee_msat = 0;
6330 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6331 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)),
6332 true, APIError::ChannelUnavailable { ref err },
6333 assert_eq!(err, "Cannot send 0-msat HTLC"));
6335 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6336 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send 0-msat HTLC", 1);
6340 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6341 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6342 let chanmon_cfgs = create_chanmon_cfgs(2);
6343 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6344 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6345 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6346 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6348 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6349 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6350 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6351 check_added_monitors!(nodes[0], 1);
6352 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6353 updates.update_add_htlcs[0].amount_msat = 0;
6355 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6356 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Remote side tried to send a 0-msat HTLC", 3);
6357 check_closed_broadcast!(nodes[1], true).unwrap();
6358 check_added_monitors!(nodes[1], 1);
6359 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() },
6360 [nodes[0].node.get_our_node_id()], 100000);
6364 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6365 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6366 //It is enforced when constructing a route.
6367 let chanmon_cfgs = create_chanmon_cfgs(2);
6368 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6369 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6370 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6371 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6373 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6374 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
6375 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);
6376 route.paths[0].hops.last_mut().unwrap().cltv_expiry_delta = 500000001;
6377 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6378 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6379 ), true, APIError::InvalidRoute { ref err },
6380 assert_eq!(err, &"Channel CLTV overflowed?"));
6384 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6385 //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.
6386 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6387 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6388 let chanmon_cfgs = create_chanmon_cfgs(2);
6389 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6390 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6391 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6392 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6393 let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6394 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context().counterparty_max_accepted_htlcs as u64;
6396 // Fetch a route in advance as we will be unable to once we're unable to send.
6397 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6398 for i in 0..max_accepted_htlcs {
6399 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6400 let payment_event = {
6401 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6402 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6403 check_added_monitors!(nodes[0], 1);
6405 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6406 assert_eq!(events.len(), 1);
6407 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6408 assert_eq!(htlcs[0].htlc_id, i);
6412 SendEvent::from_event(events.remove(0))
6414 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6415 check_added_monitors!(nodes[1], 0);
6416 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6418 expect_pending_htlcs_forwardable!(nodes[1]);
6419 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6421 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6422 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6423 ), true, APIError::ChannelUnavailable { .. }, {});
6425 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6429 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6430 //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.
6431 let chanmon_cfgs = create_chanmon_cfgs(2);
6432 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6433 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6434 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6435 let channel_value = 100000;
6436 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6437 let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6439 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6441 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6442 // Manually create a route over our max in flight (which our router normally automatically
6444 route.paths[0].hops[0].fee_msat = max_in_flight + 1;
6445 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6446 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6447 ), true, APIError::ChannelUnavailable { .. }, {});
6448 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6450 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6453 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6455 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6456 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6457 let chanmon_cfgs = create_chanmon_cfgs(2);
6458 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6459 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6460 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6461 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6462 let htlc_minimum_msat: u64;
6464 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6465 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6466 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6467 htlc_minimum_msat = channel.context().get_holder_htlc_minimum_msat();
6470 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6471 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6472 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6473 check_added_monitors!(nodes[0], 1);
6474 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6475 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6476 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6477 assert!(nodes[1].node.list_channels().is_empty());
6478 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6479 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()));
6480 check_added_monitors!(nodes[1], 1);
6481 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6485 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6486 //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
6487 let chanmon_cfgs = create_chanmon_cfgs(2);
6488 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6489 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6490 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6491 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6493 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6494 let channel_reserve = chan_stat.channel_reserve_msat;
6495 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6496 let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
6497 // The 2* and +1 are for the fee spike reserve.
6498 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
6500 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6501 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6502 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6503 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6504 check_added_monitors!(nodes[0], 1);
6505 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6507 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6508 // at this time channel-initiatee receivers are not required to enforce that senders
6509 // respect the fee_spike_reserve.
6510 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6511 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6513 assert!(nodes[1].node.list_channels().is_empty());
6514 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6515 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6516 check_added_monitors!(nodes[1], 1);
6517 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6521 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6522 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6523 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6524 let chanmon_cfgs = create_chanmon_cfgs(2);
6525 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6526 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6527 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6528 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6530 let send_amt = 3999999;
6531 let (mut route, our_payment_hash, _, our_payment_secret) =
6532 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
6533 route.paths[0].hops[0].fee_msat = send_amt;
6534 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6535 let cur_height = nodes[0].node.best_block.read().unwrap().height + 1;
6536 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6537 let recipient_onion_fields = RecipientOnionFields::secret_only(our_payment_secret);
6538 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
6539 &route.paths[0], send_amt, &recipient_onion_fields, cur_height, &None).unwrap();
6540 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
6542 let mut msg = msgs::UpdateAddHTLC {
6546 payment_hash: our_payment_hash,
6547 cltv_expiry: htlc_cltv,
6548 onion_routing_packet: onion_packet.clone(),
6549 skimmed_fee_msat: None,
6550 blinding_point: None,
6554 msg.htlc_id = i as u64;
6555 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6557 msg.htlc_id = (50) as u64;
6558 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6560 assert!(nodes[1].node.list_channels().is_empty());
6561 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6562 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6563 check_added_monitors!(nodes[1], 1);
6564 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6568 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6569 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6570 let chanmon_cfgs = create_chanmon_cfgs(2);
6571 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6572 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6573 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6574 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6576 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6577 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6578 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6579 check_added_monitors!(nodes[0], 1);
6580 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6581 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;
6582 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6584 assert!(nodes[1].node.list_channels().is_empty());
6585 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6586 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6587 check_added_monitors!(nodes[1], 1);
6588 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 1000000);
6592 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6593 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6594 let chanmon_cfgs = create_chanmon_cfgs(2);
6595 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6596 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6597 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6599 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6600 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6601 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6602 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6603 check_added_monitors!(nodes[0], 1);
6604 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6605 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6606 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6608 assert!(nodes[1].node.list_channels().is_empty());
6609 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6610 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6611 check_added_monitors!(nodes[1], 1);
6612 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6616 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6617 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6618 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6619 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6620 let chanmon_cfgs = create_chanmon_cfgs(2);
6621 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6622 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6623 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6625 create_announced_chan_between_nodes(&nodes, 0, 1);
6626 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6627 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6628 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6629 check_added_monitors!(nodes[0], 1);
6630 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6631 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6633 //Disconnect and Reconnect
6634 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
6635 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
6636 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
6637 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
6639 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6640 assert_eq!(reestablish_1.len(), 1);
6641 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
6642 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
6644 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6645 assert_eq!(reestablish_2.len(), 1);
6646 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6647 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6648 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6649 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6652 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6653 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6654 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6655 check_added_monitors!(nodes[1], 1);
6656 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6658 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6660 assert!(nodes[1].node.list_channels().is_empty());
6661 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6662 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6663 check_added_monitors!(nodes[1], 1);
6664 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6668 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6669 //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.
6671 let chanmon_cfgs = create_chanmon_cfgs(2);
6672 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6673 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6674 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6675 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6676 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6677 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6678 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6680 check_added_monitors!(nodes[0], 1);
6681 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6682 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6684 let update_msg = msgs::UpdateFulfillHTLC{
6687 payment_preimage: our_payment_preimage,
6690 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6692 assert!(nodes[0].node.list_channels().is_empty());
6693 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6694 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()));
6695 check_added_monitors!(nodes[0], 1);
6696 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6700 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6701 //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.
6703 let chanmon_cfgs = create_chanmon_cfgs(2);
6704 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6705 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6706 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6707 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6709 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6710 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6711 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6712 check_added_monitors!(nodes[0], 1);
6713 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6714 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6716 let update_msg = msgs::UpdateFailHTLC{
6719 reason: msgs::OnionErrorPacket { data: Vec::new()},
6722 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6724 assert!(nodes[0].node.list_channels().is_empty());
6725 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6726 assert!(regex::Regex::new(r"Remote tried to fulfill/fail HTLC \(\d+\) before it had been committed").unwrap().is_match(err_msg.data.as_str()));
6727 check_added_monitors!(nodes[0], 1);
6728 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6732 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6733 //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.
6735 let chanmon_cfgs = create_chanmon_cfgs(2);
6736 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6737 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6738 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6739 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6741 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6742 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6743 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6744 check_added_monitors!(nodes[0], 1);
6745 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6746 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6747 let update_msg = msgs::UpdateFailMalformedHTLC{
6750 sha256_of_onion: [1; 32],
6751 failure_code: 0x8000,
6754 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6756 assert!(nodes[0].node.list_channels().is_empty());
6757 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6758 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()));
6759 check_added_monitors!(nodes[0], 1);
6760 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6764 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6765 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6767 let chanmon_cfgs = create_chanmon_cfgs(2);
6768 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6769 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6770 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6771 create_announced_chan_between_nodes(&nodes, 0, 1);
6773 let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6775 nodes[1].node.claim_funds(our_payment_preimage);
6776 check_added_monitors!(nodes[1], 1);
6777 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6779 let events = nodes[1].node.get_and_clear_pending_msg_events();
6780 assert_eq!(events.len(), 1);
6781 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6783 MessageSendEvent::UpdateHTLCs { node_id: _ , updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, .. } } => {
6784 assert!(update_add_htlcs.is_empty());
6785 assert_eq!(update_fulfill_htlcs.len(), 1);
6786 assert!(update_fail_htlcs.is_empty());
6787 assert!(update_fail_malformed_htlcs.is_empty());
6788 assert!(update_fee.is_none());
6789 update_fulfill_htlcs[0].clone()
6791 _ => panic!("Unexpected event"),
6795 update_fulfill_msg.htlc_id = 1;
6797 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6799 assert!(nodes[0].node.list_channels().is_empty());
6800 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6801 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6802 check_added_monitors!(nodes[0], 1);
6803 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6807 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6808 //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.
6810 let chanmon_cfgs = create_chanmon_cfgs(2);
6811 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6812 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6813 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6814 create_announced_chan_between_nodes(&nodes, 0, 1);
6816 let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6818 nodes[1].node.claim_funds(our_payment_preimage);
6819 check_added_monitors!(nodes[1], 1);
6820 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6822 let events = nodes[1].node.get_and_clear_pending_msg_events();
6823 assert_eq!(events.len(), 1);
6824 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6826 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, .. } } => {
6827 assert!(update_add_htlcs.is_empty());
6828 assert_eq!(update_fulfill_htlcs.len(), 1);
6829 assert!(update_fail_htlcs.is_empty());
6830 assert!(update_fail_malformed_htlcs.is_empty());
6831 assert!(update_fee.is_none());
6832 update_fulfill_htlcs[0].clone()
6834 _ => panic!("Unexpected event"),
6838 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6840 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6842 assert!(nodes[0].node.list_channels().is_empty());
6843 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6844 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6845 check_added_monitors!(nodes[0], 1);
6846 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6850 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6851 //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.
6853 let chanmon_cfgs = create_chanmon_cfgs(2);
6854 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6855 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6856 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6857 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6859 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6860 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6861 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6862 check_added_monitors!(nodes[0], 1);
6864 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6865 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6867 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6868 check_added_monitors!(nodes[1], 0);
6869 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6871 let events = nodes[1].node.get_and_clear_pending_msg_events();
6873 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6875 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, .. } } => {
6876 assert!(update_add_htlcs.is_empty());
6877 assert!(update_fulfill_htlcs.is_empty());
6878 assert!(update_fail_htlcs.is_empty());
6879 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6880 assert!(update_fee.is_none());
6881 update_fail_malformed_htlcs[0].clone()
6883 _ => panic!("Unexpected event"),
6886 update_msg.failure_code &= !0x8000;
6887 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6889 assert!(nodes[0].node.list_channels().is_empty());
6890 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6891 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6892 check_added_monitors!(nodes[0], 1);
6893 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 1000000);
6897 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6898 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6899 // * 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.
6901 let chanmon_cfgs = create_chanmon_cfgs(3);
6902 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6903 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6904 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6905 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6906 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000);
6908 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6911 let mut payment_event = {
6912 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6913 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6914 check_added_monitors!(nodes[0], 1);
6915 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6916 assert_eq!(events.len(), 1);
6917 SendEvent::from_event(events.remove(0))
6919 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6920 check_added_monitors!(nodes[1], 0);
6921 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6922 expect_pending_htlcs_forwardable!(nodes[1]);
6923 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6924 assert_eq!(events_2.len(), 1);
6925 check_added_monitors!(nodes[1], 1);
6926 payment_event = SendEvent::from_event(events_2.remove(0));
6927 assert_eq!(payment_event.msgs.len(), 1);
6930 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6931 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6932 check_added_monitors!(nodes[2], 0);
6933 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6935 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6936 assert_eq!(events_3.len(), 1);
6937 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6939 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 } } => {
6940 assert!(update_add_htlcs.is_empty());
6941 assert!(update_fulfill_htlcs.is_empty());
6942 assert!(update_fail_htlcs.is_empty());
6943 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6944 assert!(update_fee.is_none());
6945 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6947 _ => panic!("Unexpected event"),
6951 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6953 check_added_monitors!(nodes[1], 0);
6954 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6955 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 }]);
6956 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6957 assert_eq!(events_4.len(), 1);
6959 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6961 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, .. } } => {
6962 assert!(update_add_htlcs.is_empty());
6963 assert!(update_fulfill_htlcs.is_empty());
6964 assert_eq!(update_fail_htlcs.len(), 1);
6965 assert!(update_fail_malformed_htlcs.is_empty());
6966 assert!(update_fee.is_none());
6968 _ => panic!("Unexpected event"),
6971 check_added_monitors!(nodes[1], 1);
6975 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6976 let chanmon_cfgs = create_chanmon_cfgs(3);
6977 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6978 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6979 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6980 create_announced_chan_between_nodes(&nodes, 0, 1);
6981 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6983 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6986 let mut payment_event = {
6987 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6988 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6989 check_added_monitors!(nodes[0], 1);
6990 SendEvent::from_node(&nodes[0])
6993 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6994 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6995 expect_pending_htlcs_forwardable!(nodes[1]);
6996 check_added_monitors!(nodes[1], 1);
6997 payment_event = SendEvent::from_node(&nodes[1]);
6998 assert_eq!(payment_event.msgs.len(), 1);
7001 payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
7002 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7003 check_added_monitors!(nodes[2], 0);
7004 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7006 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7007 assert_eq!(events_3.len(), 1);
7009 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
7010 let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
7011 // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
7012 update_msg.failure_code |= 0x2000;
7014 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
7015 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
7017 _ => panic!("Unexpected event"),
7020 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
7021 vec![HTLCDestination::NextHopChannel {
7022 node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
7023 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7024 assert_eq!(events_4.len(), 1);
7025 check_added_monitors!(nodes[1], 1);
7028 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
7029 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
7030 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
7032 _ => panic!("Unexpected event"),
7035 let events_5 = nodes[0].node.get_and_clear_pending_events();
7036 assert_eq!(events_5.len(), 2);
7038 // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
7039 // the node originating the error to its next hop.
7041 Event::PaymentPathFailed { error_code, failure: PathFailure::OnPath { network_update: Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }) }, ..
7043 assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
7044 assert!(is_permanent);
7045 assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
7047 _ => panic!("Unexpected event"),
7050 Event::PaymentFailed { payment_hash, .. } => {
7051 assert_eq!(payment_hash, our_payment_hash);
7053 _ => panic!("Unexpected event"),
7056 // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
7059 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7060 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7061 // 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
7062 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7064 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7065 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7066 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7067 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7068 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7069 let chan =create_announced_chan_between_nodes(&nodes, 0, 1);
7071 let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
7072 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context().holder_dust_limit_satoshis;
7074 // We route 2 dust-HTLCs between A and B
7075 let (_, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7076 let (_, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7077 route_payment(&nodes[0], &[&nodes[1]], 1000000);
7079 // Cache one local commitment tx as previous
7080 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7082 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7083 nodes[1].node.fail_htlc_backwards(&payment_hash_2);
7084 check_added_monitors!(nodes[1], 0);
7085 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7086 check_added_monitors!(nodes[1], 1);
7088 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7089 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7090 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7091 check_added_monitors!(nodes[0], 1);
7093 // Cache one local commitment tx as lastest
7094 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7096 let events = nodes[0].node.get_and_clear_pending_msg_events();
7098 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7099 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7101 _ => panic!("Unexpected event"),
7104 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7105 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7107 _ => panic!("Unexpected event"),
7110 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7111 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7112 if announce_latest {
7113 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7115 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7118 check_closed_broadcast!(nodes[0], true);
7119 check_added_monitors!(nodes[0], 1);
7120 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7122 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7123 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7124 let events = nodes[0].node.get_and_clear_pending_events();
7125 // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7126 assert_eq!(events.len(), 4);
7127 let mut first_failed = false;
7128 for event in events {
7130 Event::PaymentPathFailed { payment_hash, .. } => {
7131 if payment_hash == payment_hash_1 {
7132 assert!(!first_failed);
7133 first_failed = true;
7135 assert_eq!(payment_hash, payment_hash_2);
7138 Event::PaymentFailed { .. } => {}
7139 _ => panic!("Unexpected event"),
7145 fn test_failure_delay_dust_htlc_local_commitment() {
7146 do_test_failure_delay_dust_htlc_local_commitment(true);
7147 do_test_failure_delay_dust_htlc_local_commitment(false);
7150 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7151 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7152 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7153 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7154 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7155 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7156 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7158 let chanmon_cfgs = create_chanmon_cfgs(3);
7159 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7160 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7161 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7162 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
7164 let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
7165 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context().holder_dust_limit_satoshis;
7167 let (_payment_preimage_1, dust_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7168 let (_payment_preimage_2, non_dust_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7170 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7171 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7173 // We revoked bs_commitment_tx
7175 let (payment_preimage_3, ..) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7176 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7179 let mut timeout_tx = Vec::new();
7181 // We fail dust-HTLC 1 by broadcast of local commitment tx
7182 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7183 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7184 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7185 expect_payment_failed!(nodes[0], dust_hash, false);
7187 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7188 check_closed_broadcast!(nodes[0], true);
7189 check_added_monitors!(nodes[0], 1);
7190 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7191 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7192 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7193 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7194 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7195 mine_transaction(&nodes[0], &timeout_tx[0]);
7196 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7197 expect_payment_failed!(nodes[0], non_dust_hash, false);
7199 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7200 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7201 check_closed_broadcast!(nodes[0], true);
7202 check_added_monitors!(nodes[0], 1);
7203 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7204 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7206 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7207 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
7208 .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
7209 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
7210 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
7211 // dust HTLC should have been failed.
7212 expect_payment_failed!(nodes[0], dust_hash, false);
7215 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7217 assert_eq!(timeout_tx[0].lock_time.to_consensus_u32(), 11);
7219 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
7220 mine_transaction(&nodes[0], &timeout_tx[0]);
7221 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7222 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7223 expect_payment_failed!(nodes[0], non_dust_hash, false);
7228 fn test_sweep_outbound_htlc_failure_update() {
7229 do_test_sweep_outbound_htlc_failure_update(false, true);
7230 do_test_sweep_outbound_htlc_failure_update(false, false);
7231 do_test_sweep_outbound_htlc_failure_update(true, false);
7235 fn test_user_configurable_csv_delay() {
7236 // We test our channel constructors yield errors when we pass them absurd csv delay
7238 let mut low_our_to_self_config = UserConfig::default();
7239 low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
7240 let mut high_their_to_self_config = UserConfig::default();
7241 high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
7242 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7243 let chanmon_cfgs = create_chanmon_cfgs(2);
7244 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7245 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7246 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7248 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in OutboundV1Channel::new()
7249 if let Err(error) = OutboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7250 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[1].node.init_features(), 1000000, 1000000, 0,
7251 &low_our_to_self_config, 0, 42, None)
7254 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())); },
7255 _ => panic!("Unexpected event"),
7257 } else { assert!(false) }
7259 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in InboundV1Channel::new()
7260 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None, None).unwrap();
7261 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7262 open_channel.common_fields.to_self_delay = 200;
7263 if let Err(error) = InboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7264 &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,
7265 &low_our_to_self_config, 0, &nodes[0].logger, /*is_0conf=*/false)
7268 ChannelError::Close((err, _)) => {
7269 let regex = regex::Regex::new(r"Configured with an unreasonable our_to_self_delay \(\d+\) putting user funds at risks").unwrap();
7270 assert!(regex.is_match(err.as_str()));
7272 _ => panic!("Unexpected event"),
7274 } else { assert!(false); }
7276 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7277 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None, None).unwrap();
7278 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()));
7279 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7280 accept_channel.common_fields.to_self_delay = 200;
7281 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
7283 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7285 &ErrorAction::SendErrorMessage { ref msg } => {
7286 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()));
7287 reason_msg = msg.data.clone();
7291 } else { panic!(); }
7292 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg }, [nodes[1].node.get_our_node_id()], 1000000);
7294 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in InboundV1Channel::new()
7295 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None, None).unwrap();
7296 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7297 open_channel.common_fields.to_self_delay = 200;
7298 if let Err(error) = InboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7299 &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,
7300 &high_their_to_self_config, 0, &nodes[0].logger, /*is_0conf=*/false)
7303 ChannelError::Close((err, _)) => {
7304 let regex = regex::Regex::new(r"They wanted our payments to be delayed by a needlessly long period\. Upper limit: \d+\. Actual: \d+").unwrap();
7305 assert!(regex.is_match(err.as_str()));
7307 _ => panic!("Unexpected event"),
7309 } else { assert!(false); }
7313 fn test_check_htlc_underpaying() {
7314 // Send payment through A -> B but A is maliciously
7315 // sending a probe payment (i.e less than expected value0
7316 // to B, B should refuse payment.
7318 let chanmon_cfgs = create_chanmon_cfgs(2);
7319 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7320 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7321 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7323 // Create some initial channels
7324 create_announced_chan_between_nodes(&nodes, 0, 1);
7326 let scorer = test_utils::TestScorer::new();
7327 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7328 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
7329 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
7330 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 10_000);
7331 let route = get_route(&nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph.read_only(),
7332 None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes).unwrap();
7333 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7334 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, None).unwrap();
7335 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
7336 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
7337 check_added_monitors!(nodes[0], 1);
7339 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7340 assert_eq!(events.len(), 1);
7341 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7342 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7343 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7345 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7346 // and then will wait a second random delay before failing the HTLC back:
7347 expect_pending_htlcs_forwardable!(nodes[1]);
7348 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7350 // Node 3 is expecting payment of 100_000 but received 10_000,
7351 // it should fail htlc like we didn't know the preimage.
7352 nodes[1].node.process_pending_htlc_forwards();
7354 let events = nodes[1].node.get_and_clear_pending_msg_events();
7355 assert_eq!(events.len(), 1);
7356 let (update_fail_htlc, commitment_signed) = match events[0] {
7357 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 } } => {
7358 assert!(update_add_htlcs.is_empty());
7359 assert!(update_fulfill_htlcs.is_empty());
7360 assert_eq!(update_fail_htlcs.len(), 1);
7361 assert!(update_fail_malformed_htlcs.is_empty());
7362 assert!(update_fee.is_none());
7363 (update_fail_htlcs[0].clone(), commitment_signed)
7365 _ => panic!("Unexpected event"),
7367 check_added_monitors!(nodes[1], 1);
7369 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7370 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7372 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7373 let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
7374 expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
7375 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7379 fn test_announce_disable_channels() {
7380 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7381 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7383 let chanmon_cfgs = create_chanmon_cfgs(2);
7384 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7385 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7386 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7388 // Connect a dummy node for proper future events broadcasting
7389 connect_dummy_node(&nodes[0]);
7391 create_announced_chan_between_nodes(&nodes, 0, 1);
7392 create_announced_chan_between_nodes(&nodes, 1, 0);
7393 create_announced_chan_between_nodes(&nodes, 0, 1);
7396 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
7397 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
7399 for _ in 0..DISABLE_GOSSIP_TICKS + 1 {
7400 nodes[0].node.timer_tick_occurred();
7402 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7403 assert_eq!(msg_events.len(), 3);
7404 let mut chans_disabled = new_hash_map();
7405 for e in msg_events {
7407 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7408 assert_eq!(msg.contents.channel_flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7409 // Check that each channel gets updated exactly once
7410 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7411 panic!("Generated ChannelUpdate for wrong chan!");
7414 _ => panic!("Unexpected event"),
7418 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
7419 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
7421 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7422 assert_eq!(reestablish_1.len(), 3);
7423 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
7424 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
7426 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7427 assert_eq!(reestablish_2.len(), 3);
7429 // Reestablish chan_1
7430 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7431 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7432 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7433 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7434 // Reestablish chan_2
7435 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7436 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7437 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7438 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7439 // Reestablish chan_3
7440 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7441 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7442 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7443 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7445 for _ in 0..ENABLE_GOSSIP_TICKS {
7446 nodes[0].node.timer_tick_occurred();
7448 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7449 nodes[0].node.timer_tick_occurred();
7450 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7451 assert_eq!(msg_events.len(), 3);
7452 for e in msg_events {
7454 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7455 assert_eq!(msg.contents.channel_flags & (1<<1), 0); // The "channel disabled" bit should be off
7456 match chans_disabled.remove(&msg.contents.short_channel_id) {
7457 // Each update should have a higher timestamp than the previous one, replacing
7459 Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7460 None => panic!("Generated ChannelUpdate for wrong chan!"),
7463 _ => panic!("Unexpected event"),
7466 // Check that each channel gets updated exactly once
7467 assert!(chans_disabled.is_empty());
7471 fn test_bump_penalty_txn_on_revoked_commitment() {
7472 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7473 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7475 let chanmon_cfgs = create_chanmon_cfgs(2);
7476 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7477 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7478 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7480 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7482 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7483 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7484 .with_bolt11_features(nodes[0].node.bolt11_invoice_features()).unwrap();
7485 let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000);
7486 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7488 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7489 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7490 assert_eq!(revoked_txn[0].output.len(), 4);
7491 assert_eq!(revoked_txn[0].input.len(), 1);
7492 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7493 let revoked_txid = revoked_txn[0].txid();
7495 let mut penalty_sum = 0;
7496 for outp in revoked_txn[0].output.iter() {
7497 if outp.script_pubkey.is_p2wsh() {
7498 penalty_sum += outp.value.to_sat();
7502 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7503 let header_114 = connect_blocks(&nodes[1], 14);
7505 // Actually revoke tx by claiming a HTLC
7506 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7507 connect_block(&nodes[1], &create_dummy_block(header_114, 42, vec![revoked_txn[0].clone()]));
7508 check_added_monitors!(nodes[1], 1);
7510 // One or more justice tx should have been broadcast, check it
7514 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7515 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7516 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7517 assert_eq!(node_txn[0].output.len(), 1);
7518 check_spends!(node_txn[0], revoked_txn[0]);
7519 let fee_1 = penalty_sum - node_txn[0].output[0].value.to_sat();
7520 feerate_1 = fee_1 * 1000 / node_txn[0].weight().to_wu();
7521 penalty_1 = node_txn[0].txid();
7525 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7526 connect_blocks(&nodes[1], 15);
7527 let mut penalty_2 = penalty_1;
7528 let mut feerate_2 = 0;
7530 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7531 assert_eq!(node_txn.len(), 1);
7532 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7533 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7534 assert_eq!(node_txn[0].output.len(), 1);
7535 check_spends!(node_txn[0], revoked_txn[0]);
7536 penalty_2 = node_txn[0].txid();
7537 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7538 assert_ne!(penalty_2, penalty_1);
7539 let fee_2 = penalty_sum - node_txn[0].output[0].value.to_sat();
7540 feerate_2 = fee_2 * 1000 / node_txn[0].weight().to_wu();
7541 // Verify 25% bump heuristic
7542 assert!(feerate_2 * 100 >= feerate_1 * 125);
7546 assert_ne!(feerate_2, 0);
7548 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7549 connect_blocks(&nodes[1], 1);
7551 let mut feerate_3 = 0;
7553 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7554 assert_eq!(node_txn.len(), 1);
7555 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7556 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7557 assert_eq!(node_txn[0].output.len(), 1);
7558 check_spends!(node_txn[0], revoked_txn[0]);
7559 penalty_3 = node_txn[0].txid();
7560 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7561 assert_ne!(penalty_3, penalty_2);
7562 let fee_3 = penalty_sum - node_txn[0].output[0].value.to_sat();
7563 feerate_3 = fee_3 * 1000 / node_txn[0].weight().to_wu();
7564 // Verify 25% bump heuristic
7565 assert!(feerate_3 * 100 >= feerate_2 * 125);
7569 assert_ne!(feerate_3, 0);
7571 nodes[1].node.get_and_clear_pending_events();
7572 nodes[1].node.get_and_clear_pending_msg_events();
7576 fn test_bump_penalty_txn_on_revoked_htlcs() {
7577 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7578 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7580 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7581 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7582 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7583 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7584 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7586 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7587 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7588 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();
7589 let scorer = test_utils::TestScorer::new();
7590 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7591 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 3_000_000);
7592 let route = get_route(&nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph.read_only(), None,
7593 nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes).unwrap();
7594 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7595 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50)
7596 .with_bolt11_features(nodes[0].node.bolt11_invoice_features()).unwrap();
7597 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 3_000_000);
7598 let route = get_route(&nodes[1].node.get_our_node_id(), &route_params, &nodes[1].network_graph.read_only(), None,
7599 nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes).unwrap();
7600 let failed_payment_hash = send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000).1;
7602 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7603 assert_eq!(revoked_local_txn[0].input.len(), 1);
7604 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7606 // Revoke local commitment tx
7607 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7609 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7610 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone()]));
7611 check_closed_broadcast!(nodes[1], true);
7612 check_added_monitors!(nodes[1], 1);
7613 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 1000000);
7614 connect_blocks(&nodes[1], 50); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7616 let revoked_htlc_txn = {
7617 let txn = nodes[1].tx_broadcaster.unique_txn_broadcast();
7618 assert_eq!(txn.len(), 2);
7620 assert_eq!(txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7621 assert_eq!(txn[0].input.len(), 1);
7622 check_spends!(txn[0], revoked_local_txn[0]);
7624 assert_eq!(txn[1].input.len(), 1);
7625 assert_eq!(txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7626 assert_eq!(txn[1].output.len(), 1);
7627 check_spends!(txn[1], revoked_local_txn[0]);
7632 // Broadcast set of revoked txn on A
7633 let hash_128 = connect_blocks(&nodes[0], 40);
7634 let block_11 = create_dummy_block(hash_128, 42, vec![revoked_local_txn[0].clone()]);
7635 connect_block(&nodes[0], &block_11);
7636 let block_129 = create_dummy_block(block_11.block_hash(), 42, vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()]);
7637 connect_block(&nodes[0], &block_129);
7638 let events = nodes[0].node.get_and_clear_pending_events();
7639 expect_pending_htlcs_forwardable_conditions(events[0..2].to_vec(), &[HTLCDestination::FailedPayment { payment_hash: failed_payment_hash }]);
7640 match events.last().unwrap() {
7641 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7642 _ => panic!("Unexpected event"),
7648 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7649 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7650 // Verify claim tx are spending revoked HTLC txn
7652 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7653 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7654 // which are included in the same block (they are broadcasted because we scan the
7655 // transactions linearly and generate claims as we go, they likely should be removed in the
7657 assert_eq!(node_txn[0].input.len(), 1);
7658 check_spends!(node_txn[0], revoked_local_txn[0]);
7659 assert_eq!(node_txn[1].input.len(), 1);
7660 check_spends!(node_txn[1], revoked_local_txn[0]);
7661 assert_eq!(node_txn[2].input.len(), 1);
7662 check_spends!(node_txn[2], revoked_local_txn[0]);
7664 // Each of the three justice transactions claim a separate (single) output of the three
7665 // available, which we check here:
7666 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7667 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7668 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7670 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7671 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7673 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7674 // output, checked above).
7675 assert_eq!(node_txn[3].input.len(), 2);
7676 assert_eq!(node_txn[3].output.len(), 1);
7677 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7679 first = node_txn[3].txid();
7680 // Store both feerates for later comparison
7681 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7682 feerate_1 = fee_1 * 1000 / node_txn[3].weight().to_wu();
7683 penalty_txn = vec![node_txn[2].clone()];
7687 // Connect one more block to see if bumped penalty are issued for HTLC txn
7688 let block_130 = create_dummy_block(block_129.block_hash(), 42, penalty_txn);
7689 connect_block(&nodes[0], &block_130);
7690 let block_131 = create_dummy_block(block_130.block_hash(), 42, Vec::new());
7691 connect_block(&nodes[0], &block_131);
7693 // Few more blocks to confirm penalty txn
7694 connect_blocks(&nodes[0], 4);
7695 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7696 let header_144 = connect_blocks(&nodes[0], 9);
7698 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7699 assert_eq!(node_txn.len(), 1);
7701 assert_eq!(node_txn[0].input.len(), 2);
7702 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7703 // Verify bumped tx is different and 25% bump heuristic
7704 assert_ne!(first, node_txn[0].txid());
7705 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7706 let feerate_2 = fee_2 * 1000 / node_txn[0].weight().to_wu();
7707 assert!(feerate_2 * 100 > feerate_1 * 125);
7708 let txn = vec![node_txn[0].clone()];
7712 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7713 connect_block(&nodes[0], &create_dummy_block(header_144, 42, node_txn));
7714 connect_blocks(&nodes[0], 20);
7716 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7717 // We verify than no new transaction has been broadcast because previously
7718 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7719 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7720 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7721 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7722 // up bumped justice generation.
7723 assert_eq!(node_txn.len(), 0);
7726 check_closed_broadcast!(nodes[0], true);
7727 check_added_monitors!(nodes[0], 1);
7731 fn test_bump_penalty_txn_on_remote_commitment() {
7732 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7733 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7736 // Provide preimage for one
7737 // Check aggregation
7739 let chanmon_cfgs = create_chanmon_cfgs(2);
7740 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7741 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7742 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7744 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7745 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7746 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7748 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7749 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7750 assert_eq!(remote_txn[0].output.len(), 4);
7751 assert_eq!(remote_txn[0].input.len(), 1);
7752 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7754 // Claim a HTLC without revocation (provide B monitor with preimage)
7755 nodes[1].node.claim_funds(payment_preimage);
7756 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7757 mine_transaction(&nodes[1], &remote_txn[0]);
7758 check_added_monitors!(nodes[1], 2);
7759 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7761 // One or more claim tx should have been broadcast, check it
7765 let feerate_timeout;
7766 let feerate_preimage;
7768 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7769 // 3 transactions including:
7770 // preimage and timeout sweeps from remote commitment + preimage sweep bump
7771 assert_eq!(node_txn.len(), 3);
7772 assert_eq!(node_txn[0].input.len(), 1);
7773 assert_eq!(node_txn[1].input.len(), 1);
7774 assert_eq!(node_txn[2].input.len(), 1);
7775 check_spends!(node_txn[0], remote_txn[0]);
7776 check_spends!(node_txn[1], remote_txn[0]);
7777 check_spends!(node_txn[2], remote_txn[0]);
7779 preimage = node_txn[0].txid();
7780 let index = node_txn[0].input[0].previous_output.vout;
7781 let fee = remote_txn[0].output[index as usize].value.to_sat() - node_txn[0].output[0].value.to_sat();
7782 feerate_preimage = fee * 1000 / node_txn[0].weight().to_wu();
7784 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7785 (node_txn[2].clone(), node_txn[1].clone())
7787 (node_txn[1].clone(), node_txn[2].clone())
7790 preimage_bump = preimage_bump_tx;
7791 check_spends!(preimage_bump, remote_txn[0]);
7792 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7794 timeout = timeout_tx.txid();
7795 let index = timeout_tx.input[0].previous_output.vout;
7796 let fee = remote_txn[0].output[index as usize].value.to_sat() - timeout_tx.output[0].value.to_sat();
7797 feerate_timeout = fee * 1000 / timeout_tx.weight().to_wu();
7801 assert_ne!(feerate_timeout, 0);
7802 assert_ne!(feerate_preimage, 0);
7804 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7805 connect_blocks(&nodes[1], 1);
7807 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7808 assert_eq!(node_txn.len(), 1);
7809 assert_eq!(node_txn[0].input.len(), 1);
7810 assert_eq!(preimage_bump.input.len(), 1);
7811 check_spends!(node_txn[0], remote_txn[0]);
7812 check_spends!(preimage_bump, remote_txn[0]);
7814 let index = preimage_bump.input[0].previous_output.vout;
7815 let fee = remote_txn[0].output[index as usize].value.to_sat() - preimage_bump.output[0].value.to_sat();
7816 let new_feerate = fee * 1000 / preimage_bump.weight().to_wu();
7817 assert!(new_feerate * 100 > feerate_timeout * 125);
7818 assert_ne!(timeout, preimage_bump.txid());
7820 let index = node_txn[0].input[0].previous_output.vout;
7821 let fee = remote_txn[0].output[index as usize].value.to_sat() - node_txn[0].output[0].value.to_sat();
7822 let new_feerate = fee * 1000 / node_txn[0].weight().to_wu();
7823 assert!(new_feerate * 100 > feerate_preimage * 125);
7824 assert_ne!(preimage, node_txn[0].txid());
7829 nodes[1].node.get_and_clear_pending_events();
7830 nodes[1].node.get_and_clear_pending_msg_events();
7834 fn test_counterparty_raa_skip_no_crash() {
7835 // Previously, if our counterparty sent two RAAs in a row without us having provided a
7836 // commitment transaction, we would have happily carried on and provided them the next
7837 // commitment transaction based on one RAA forward. This would probably eventually have led to
7838 // channel closure, but it would not have resulted in funds loss. Still, our
7839 // TestChannelSigner would have panicked as it doesn't like jumps into the future. Here, we
7840 // check simply that the channel is closed in response to such an RAA, but don't check whether
7841 // we decide to punish our counterparty for revoking their funds (as we don't currently
7843 let chanmon_cfgs = create_chanmon_cfgs(2);
7844 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7845 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7846 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7847 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7849 let per_commitment_secret;
7850 let next_per_commitment_point;
7852 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7853 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7854 let keys = guard.channel_by_id.get_mut(&channel_id).map(
7855 |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
7856 ).flatten().unwrap().get_signer();
7858 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7860 // Make signer believe we got a counterparty signature, so that it allows the revocation
7861 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7862 per_commitment_secret = keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7864 // Must revoke without gaps
7865 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7866 keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7868 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7869 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7870 &SecretKey::from_slice(&keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7873 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7874 &msgs::RevokeAndACK {
7876 per_commitment_secret,
7877 next_per_commitment_point,
7879 next_local_nonce: None,
7881 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7882 check_added_monitors!(nodes[1], 1);
7883 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() }
7884 , [nodes[0].node.get_our_node_id()], 100000);
7888 fn test_bump_txn_sanitize_tracking_maps() {
7889 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7890 // verify we clean then right after expiration of ANTI_REORG_DELAY.
7892 let chanmon_cfgs = create_chanmon_cfgs(2);
7893 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7894 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7895 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7897 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7898 // Lock HTLC in both directions
7899 let (payment_preimage_1, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7900 let (_, payment_hash_2, ..) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7902 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7903 assert_eq!(revoked_local_txn[0].input.len(), 1);
7904 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7906 // Revoke local commitment tx
7907 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7909 // Broadcast set of revoked txn on A
7910 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7911 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7912 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7914 mine_transaction(&nodes[0], &revoked_local_txn[0]);
7915 check_closed_broadcast!(nodes[0], true);
7916 check_added_monitors!(nodes[0], 1);
7917 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 1000000);
7919 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7920 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7921 check_spends!(node_txn[0], revoked_local_txn[0]);
7922 check_spends!(node_txn[1], revoked_local_txn[0]);
7923 check_spends!(node_txn[2], revoked_local_txn[0]);
7924 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7928 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, penalty_txn));
7929 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7931 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7932 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7933 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7938 fn test_channel_conf_timeout() {
7939 // Tests that, for inbound channels, we give up on them if the funding transaction does not
7940 // confirm within 2016 blocks, as recommended by BOLT 2.
7941 let chanmon_cfgs = create_chanmon_cfgs(2);
7942 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7943 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7944 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7946 let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7948 // The outbound node should wait forever for confirmation:
7949 // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7950 // copied here instead of directly referencing the constant.
7951 connect_blocks(&nodes[0], 2016);
7952 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7954 // The inbound node should fail the channel after exactly 2016 blocks
7955 connect_blocks(&nodes[1], 2015);
7956 check_added_monitors!(nodes[1], 0);
7957 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7959 connect_blocks(&nodes[1], 1);
7960 check_added_monitors!(nodes[1], 1);
7961 check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut, [nodes[0].node.get_our_node_id()], 1000000);
7962 let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7963 assert_eq!(close_ev.len(), 1);
7965 MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { ref msg }, ref node_id } => {
7966 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7967 assert_eq!(msg.as_ref().unwrap().data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7969 _ => panic!("Unexpected event"),
7974 fn test_override_channel_config() {
7975 let chanmon_cfgs = create_chanmon_cfgs(2);
7976 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7977 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7978 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7980 // Node0 initiates a channel to node1 using the override config.
7981 let mut override_config = UserConfig::default();
7982 override_config.channel_handshake_config.our_to_self_delay = 200;
7984 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, None, Some(override_config)).unwrap();
7986 // Assert the channel created by node0 is using the override config.
7987 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7988 assert_eq!(res.common_fields.channel_flags, 0);
7989 assert_eq!(res.common_fields.to_self_delay, 200);
7993 fn test_override_0msat_htlc_minimum() {
7994 let mut zero_config = UserConfig::default();
7995 zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7996 let chanmon_cfgs = create_chanmon_cfgs(2);
7997 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7998 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7999 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8001 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, None, Some(zero_config)).unwrap();
8002 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8003 assert_eq!(res.common_fields.htlc_minimum_msat, 1);
8005 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
8006 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8007 assert_eq!(res.common_fields.htlc_minimum_msat, 1);
8011 fn test_channel_update_has_correct_htlc_maximum_msat() {
8012 // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
8013 // Bolt 7 specifies that if present `htlc_maximum_msat`:
8014 // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
8015 // 90% of the `channel_value`.
8016 // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
8018 let mut config_30_percent = UserConfig::default();
8019 config_30_percent.channel_handshake_config.announced_channel = true;
8020 config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
8021 let mut config_50_percent = UserConfig::default();
8022 config_50_percent.channel_handshake_config.announced_channel = true;
8023 config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
8024 let mut config_95_percent = UserConfig::default();
8025 config_95_percent.channel_handshake_config.announced_channel = true;
8026 config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
8027 let mut config_100_percent = UserConfig::default();
8028 config_100_percent.channel_handshake_config.announced_channel = true;
8029 config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
8031 let chanmon_cfgs = create_chanmon_cfgs(4);
8032 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8033 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)]);
8034 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8036 let channel_value_satoshis = 100000;
8037 let channel_value_msat = channel_value_satoshis * 1000;
8038 let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
8039 let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
8040 let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
8042 let (node_0_chan_update, node_1_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
8043 let (node_2_chan_update, node_3_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
8045 // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
8046 // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
8047 assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
8048 // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
8049 // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
8050 assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
8052 // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8053 // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
8055 assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
8056 // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8057 // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
8059 assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
8063 fn test_manually_accept_inbound_channel_request() {
8064 let mut manually_accept_conf = UserConfig::default();
8065 manually_accept_conf.manually_accept_inbound_channels = true;
8066 let chanmon_cfgs = create_chanmon_cfgs(2);
8067 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8068 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8069 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8071 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();
8072 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8074 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
8076 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8077 // accepting the inbound channel request.
8078 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8080 let events = nodes[1].node.get_and_clear_pending_events();
8082 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8083 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
8085 _ => panic!("Unexpected event"),
8088 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8089 assert_eq!(accept_msg_ev.len(), 1);
8091 match accept_msg_ev[0] {
8092 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8093 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8095 _ => panic!("Unexpected event"),
8097 let error_message = "Channel force-closed";
8098 nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id(), error_message.to_string()).unwrap();
8100 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8101 assert_eq!(close_msg_ev.len(), 1);
8103 let events = nodes[1].node.get_and_clear_pending_events();
8105 Event::ChannelClosed { user_channel_id, .. } => {
8106 assert_eq!(user_channel_id, 23);
8108 _ => panic!("Unexpected event"),
8113 fn test_manually_reject_inbound_channel_request() {
8114 let mut manually_accept_conf = UserConfig::default();
8115 manually_accept_conf.manually_accept_inbound_channels = true;
8116 let chanmon_cfgs = create_chanmon_cfgs(2);
8117 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8118 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8119 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8121 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, Some(manually_accept_conf)).unwrap();
8122 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8124 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
8126 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8127 // rejecting the inbound channel request.
8128 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8129 let error_message = "Channel force-closed";
8130 let events = nodes[1].node.get_and_clear_pending_events();
8132 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8133 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id(), error_message.to_string()).unwrap();
8135 _ => panic!("Unexpected event"),
8138 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8139 assert_eq!(close_msg_ev.len(), 1);
8141 match close_msg_ev[0] {
8142 MessageSendEvent::HandleError { ref node_id, .. } => {
8143 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8145 _ => panic!("Unexpected event"),
8148 // There should be no more events to process, as the channel was never opened.
8149 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
8153 fn test_can_not_accept_inbound_channel_twice() {
8154 let mut manually_accept_conf = UserConfig::default();
8155 manually_accept_conf.manually_accept_inbound_channels = true;
8156 let chanmon_cfgs = create_chanmon_cfgs(2);
8157 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8158 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8159 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8161 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, Some(manually_accept_conf)).unwrap();
8162 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8164 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
8166 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8167 // accepting the inbound channel request.
8168 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8170 let events = nodes[1].node.get_and_clear_pending_events();
8172 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8173 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
8174 let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
8176 Err(APIError::APIMisuseError { err }) => {
8177 assert_eq!(err, "No such channel awaiting to be accepted.");
8179 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8180 Err(e) => panic!("Unexpected Error {:?}", e),
8183 _ => panic!("Unexpected event"),
8186 // Ensure that the channel wasn't closed after attempting to accept it twice.
8187 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8188 assert_eq!(accept_msg_ev.len(), 1);
8190 match accept_msg_ev[0] {
8191 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8192 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8194 _ => panic!("Unexpected event"),
8199 fn test_can_not_accept_unknown_inbound_channel() {
8200 let chanmon_cfg = create_chanmon_cfgs(2);
8201 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8202 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8203 let nodes = create_network(2, &node_cfg, &node_chanmgr);
8205 let unknown_channel_id = ChannelId::new_zero();
8206 let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
8208 Err(APIError::APIMisuseError { err }) => {
8209 assert_eq!(err, "No such channel awaiting to be accepted.");
8211 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8212 Err(e) => panic!("Unexpected Error: {:?}", e),
8217 fn test_onion_value_mpp_set_calculation() {
8218 // Test that we use the onion value `amt_to_forward` when
8219 // calculating whether we've reached the `total_msat` of an MPP
8220 // by having a routing node forward more than `amt_to_forward`
8221 // and checking that the receiving node doesn't generate
8222 // a PaymentClaimable event too early
8224 let chanmon_cfgs = create_chanmon_cfgs(node_count);
8225 let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8226 let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8227 let mut nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8229 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8230 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8231 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8232 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8234 let total_msat = 100_000;
8235 let expected_paths: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
8236 let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], total_msat);
8237 let sample_path = route.paths.pop().unwrap();
8239 let mut path_1 = sample_path.clone();
8240 path_1.hops[0].pubkey = nodes[1].node.get_our_node_id();
8241 path_1.hops[0].short_channel_id = chan_1_id;
8242 path_1.hops[1].pubkey = nodes[3].node.get_our_node_id();
8243 path_1.hops[1].short_channel_id = chan_3_id;
8244 path_1.hops[1].fee_msat = 100_000;
8245 route.paths.push(path_1);
8247 let mut path_2 = sample_path.clone();
8248 path_2.hops[0].pubkey = nodes[2].node.get_our_node_id();
8249 path_2.hops[0].short_channel_id = chan_2_id;
8250 path_2.hops[1].pubkey = nodes[3].node.get_our_node_id();
8251 path_2.hops[1].short_channel_id = chan_4_id;
8252 path_2.hops[1].fee_msat = 1_000;
8253 route.paths.push(path_2);
8256 let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
8257 let onion_session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
8258 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8259 nodes[0].node.test_send_payment_internal(&route, our_payment_hash,
8260 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8261 check_added_monitors!(nodes[0], expected_paths.len());
8263 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8264 assert_eq!(events.len(), expected_paths.len());
8267 let ev = remove_first_msg_event_to_node(&expected_paths[0][0].node.get_our_node_id(), &mut events);
8268 let mut payment_event = SendEvent::from_event(ev);
8269 let mut prev_node = &nodes[0];
8271 for (idx, &node) in expected_paths[0].iter().enumerate() {
8272 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
8274 if idx == 0 { // routing node
8275 let session_priv = [3; 32];
8276 let height = nodes[0].best_block_info().1;
8277 let session_priv = SecretKey::from_slice(&session_priv).unwrap();
8278 let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
8279 let recipient_onion_fields = RecipientOnionFields::secret_only(our_payment_secret);
8280 let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], 100_000,
8281 &recipient_onion_fields, height + 1, &None).unwrap();
8282 // Edit amt_to_forward to simulate the sender having set
8283 // the final amount and the routing node taking less fee
8284 if let msgs::OutboundOnionPayload::Receive {
8285 ref mut sender_intended_htlc_amt_msat, ..
8286 } = onion_payloads[1] {
8287 *sender_intended_htlc_amt_msat = 99_000;
8289 let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
8290 payment_event.msgs[0].onion_routing_packet = new_onion_packet;
8293 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
8294 check_added_monitors!(node, 0);
8295 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
8296 expect_pending_htlcs_forwardable!(node);
8299 let mut events_2 = node.node.get_and_clear_pending_msg_events();
8300 assert_eq!(events_2.len(), 1);
8301 check_added_monitors!(node, 1);
8302 payment_event = SendEvent::from_event(events_2.remove(0));
8303 assert_eq!(payment_event.msgs.len(), 1);
8305 let events_2 = node.node.get_and_clear_pending_events();
8306 assert!(events_2.is_empty());
8313 let ev = remove_first_msg_event_to_node(&expected_paths[1][0].node.get_our_node_id(), &mut events);
8314 pass_along_path(&nodes[0], expected_paths[1], 101_000, our_payment_hash.clone(), Some(our_payment_secret), ev, true, None);
8316 claim_payment_along_route(
8317 ClaimAlongRouteArgs::new(&nodes[0], expected_paths, our_payment_preimage)
8321 fn do_test_overshoot_mpp(msat_amounts: &[u64], total_msat: u64) {
8323 let routing_node_count = msat_amounts.len();
8324 let node_count = routing_node_count + 2;
8326 let chanmon_cfgs = create_chanmon_cfgs(node_count);
8327 let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8328 let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8329 let nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8334 // Create channels for each amount
8335 let mut expected_paths = Vec::with_capacity(routing_node_count);
8336 let mut src_chan_ids = Vec::with_capacity(routing_node_count);
8337 let mut dst_chan_ids = Vec::with_capacity(routing_node_count);
8338 for i in 0..routing_node_count {
8339 let routing_node = 2 + i;
8340 let src_chan_id = create_announced_chan_between_nodes(&nodes, src_idx, routing_node).0.contents.short_channel_id;
8341 src_chan_ids.push(src_chan_id);
8342 let dst_chan_id = create_announced_chan_between_nodes(&nodes, routing_node, dst_idx).0.contents.short_channel_id;
8343 dst_chan_ids.push(dst_chan_id);
8344 let path = vec![&nodes[routing_node], &nodes[dst_idx]];
8345 expected_paths.push(path);
8347 let expected_paths: Vec<&[&Node]> = expected_paths.iter().map(|route| route.as_slice()).collect();
8349 // Create a route for each amount
8350 let example_amount = 100000;
8351 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);
8352 let sample_path = route.paths.pop().unwrap();
8353 for i in 0..routing_node_count {
8354 let routing_node = 2 + i;
8355 let mut path = sample_path.clone();
8356 path.hops[0].pubkey = nodes[routing_node].node.get_our_node_id();
8357 path.hops[0].short_channel_id = src_chan_ids[i];
8358 path.hops[1].pubkey = nodes[dst_idx].node.get_our_node_id();
8359 path.hops[1].short_channel_id = dst_chan_ids[i];
8360 path.hops[1].fee_msat = msat_amounts[i];
8361 route.paths.push(path);
8364 // Send payment with manually set total_msat
8365 let payment_id = PaymentId(nodes[src_idx].keys_manager.backing.get_secure_random_bytes());
8366 let onion_session_privs = nodes[src_idx].node.test_add_new_pending_payment(our_payment_hash,
8367 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8368 nodes[src_idx].node.test_send_payment_internal(&route, our_payment_hash,
8369 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8370 check_added_monitors!(nodes[src_idx], expected_paths.len());
8372 let mut events = nodes[src_idx].node.get_and_clear_pending_msg_events();
8373 assert_eq!(events.len(), expected_paths.len());
8374 let mut amount_received = 0;
8375 for (path_idx, expected_path) in expected_paths.iter().enumerate() {
8376 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
8378 let current_path_amount = msat_amounts[path_idx];
8379 amount_received += current_path_amount;
8380 let became_claimable_now = amount_received >= total_msat && amount_received - current_path_amount < total_msat;
8381 pass_along_path(&nodes[src_idx], expected_path, amount_received, our_payment_hash.clone(), Some(our_payment_secret), ev, became_claimable_now, None);
8384 claim_payment_along_route(
8385 ClaimAlongRouteArgs::new(&nodes[src_idx], &expected_paths, our_payment_preimage)
8390 fn test_overshoot_mpp() {
8391 do_test_overshoot_mpp(&[100_000, 101_000], 200_000);
8392 do_test_overshoot_mpp(&[100_000, 10_000, 100_000], 200_000);
8396 fn test_simple_mpp() {
8397 // Simple test of sending a multi-path payment.
8398 let chanmon_cfgs = create_chanmon_cfgs(4);
8399 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8400 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8401 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8403 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8404 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8405 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8406 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8408 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8409 let path = route.paths[0].clone();
8410 route.paths.push(path);
8411 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
8412 route.paths[0].hops[0].short_channel_id = chan_1_id;
8413 route.paths[0].hops[1].short_channel_id = chan_3_id;
8414 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
8415 route.paths[1].hops[0].short_channel_id = chan_2_id;
8416 route.paths[1].hops[1].short_channel_id = chan_4_id;
8417 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8418 claim_payment_along_route(
8419 ClaimAlongRouteArgs::new(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], payment_preimage)
8424 fn test_preimage_storage() {
8425 // Simple test of payment preimage storage allowing no client-side storage to claim payments
8426 let chanmon_cfgs = create_chanmon_cfgs(2);
8427 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8428 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8429 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8431 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8434 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
8435 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8436 nodes[0].node.send_payment_with_route(&route, payment_hash,
8437 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8438 check_added_monitors!(nodes[0], 1);
8439 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8440 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8441 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8442 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8444 // Note that after leaving the above scope we have no knowledge of any arguments or return
8445 // values from previous calls.
8446 expect_pending_htlcs_forwardable!(nodes[1]);
8447 let events = nodes[1].node.get_and_clear_pending_events();
8448 assert_eq!(events.len(), 1);
8450 Event::PaymentClaimable { ref purpose, .. } => {
8452 PaymentPurpose::Bolt11InvoicePayment { payment_preimage, .. } => {
8453 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8455 _ => panic!("expected PaymentPurpose::Bolt11InvoicePayment")
8458 _ => panic!("Unexpected event"),
8463 fn test_bad_secret_hash() {
8464 // Simple test of unregistered payment hash/invalid payment secret handling
8465 let chanmon_cfgs = create_chanmon_cfgs(2);
8466 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8467 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8468 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8470 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8472 let random_payment_hash = PaymentHash([42; 32]);
8473 let random_payment_secret = PaymentSecret([43; 32]);
8474 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8475 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8477 // All the below cases should end up being handled exactly identically, so we macro the
8478 // resulting events.
8479 macro_rules! handle_unknown_invalid_payment_data {
8480 ($payment_hash: expr) => {
8481 check_added_monitors!(nodes[0], 1);
8482 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8483 let payment_event = SendEvent::from_event(events.pop().unwrap());
8484 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8485 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8487 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8488 // again to process the pending backwards-failure of the HTLC
8489 expect_pending_htlcs_forwardable!(nodes[1]);
8490 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8491 check_added_monitors!(nodes[1], 1);
8493 // We should fail the payment back
8494 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8495 match events.pop().unwrap() {
8496 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8497 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8498 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8500 _ => panic!("Unexpected event"),
8505 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8506 // Error data is the HTLC value (100,000) and current block height
8507 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8509 // Send a payment with the right payment hash but the wrong payment secret
8510 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
8511 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8512 handle_unknown_invalid_payment_data!(our_payment_hash);
8513 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8515 // Send a payment with a random payment hash, but the right payment secret
8516 nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8517 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8518 handle_unknown_invalid_payment_data!(random_payment_hash);
8519 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8521 // Send a payment with a random payment hash and random payment secret
8522 nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8523 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8524 handle_unknown_invalid_payment_data!(random_payment_hash);
8525 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8529 fn test_update_err_monitor_lockdown() {
8530 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8531 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8532 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8535 // This scenario may happen in a watchtower setup, where watchtower process a block height
8536 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8537 // commitment at same time.
8539 let chanmon_cfgs = create_chanmon_cfgs(2);
8540 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8541 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8542 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8544 // Create some initial channel
8545 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8546 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8548 // Rebalance the network to generate htlc in the two directions
8549 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8551 // Route a HTLC from node 0 to node 1 (but don't settle)
8552 let (preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8554 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8555 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8556 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8557 let persister = test_utils::TestPersister::new();
8560 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8561 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8562 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8563 assert!(new_monitor == *monitor);
8566 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);
8567 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), Ok(ChannelMonitorUpdateStatus::Completed));
8570 let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8571 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8572 // transaction lock time requirements here.
8573 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 200));
8574 watchtower.chain_monitor.block_connected(&block, 200);
8576 // Try to update ChannelMonitor
8577 nodes[1].node.claim_funds(preimage);
8578 check_added_monitors!(nodes[1], 1);
8579 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8581 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8582 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8583 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8585 let mut node_0_per_peer_lock;
8586 let mut node_0_peer_state_lock;
8587 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) {
8588 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8589 assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::InProgress);
8590 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8591 } else { assert!(false); }
8596 // Our local monitor is in-sync and hasn't processed yet timeout
8597 check_added_monitors!(nodes[0], 1);
8598 let events = nodes[0].node.get_and_clear_pending_events();
8599 assert_eq!(events.len(), 1);
8603 fn test_concurrent_monitor_claim() {
8604 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8605 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8606 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8607 // state N+1 confirms. Alice claims output from state N+1.
8609 let chanmon_cfgs = create_chanmon_cfgs(2);
8610 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8611 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8612 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8614 // Create some initial channel
8615 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8616 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8618 // Rebalance the network to generate htlc in the two directions
8619 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8621 // Route a HTLC from node 0 to node 1 (but don't settle)
8622 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8624 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8625 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8626 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8627 let persister = test_utils::TestPersister::new();
8628 let alice_broadcaster = test_utils::TestBroadcaster::with_blocks(
8629 Arc::new(Mutex::new(nodes[0].blocks.lock().unwrap().clone())),
8631 let watchtower_alice = {
8633 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8634 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8635 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8636 assert!(new_monitor == *monitor);
8639 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &alice_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8640 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), Ok(ChannelMonitorUpdateStatus::Completed));
8643 let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8644 // Make Alice aware of enough blocks that it doesn't think we're violating transaction lock time
8645 // requirements here.
8646 const HTLC_TIMEOUT_BROADCAST: u32 = CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS;
8647 alice_broadcaster.blocks.lock().unwrap().resize((HTLC_TIMEOUT_BROADCAST) as usize, (block.clone(), HTLC_TIMEOUT_BROADCAST));
8648 watchtower_alice.chain_monitor.block_connected(&block, HTLC_TIMEOUT_BROADCAST);
8650 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8652 let mut txn = alice_broadcaster.txn_broadcast();
8653 assert_eq!(txn.len(), 2);
8654 check_spends!(txn[0], chan_1.3);
8655 check_spends!(txn[1], txn[0]);
8658 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8659 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8660 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8661 let persister = test_utils::TestPersister::new();
8662 let bob_broadcaster = test_utils::TestBroadcaster::with_blocks(Arc::clone(&alice_broadcaster.blocks));
8663 let watchtower_bob = {
8665 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8666 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8667 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8668 assert!(new_monitor == *monitor);
8671 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &bob_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8672 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), Ok(ChannelMonitorUpdateStatus::Completed));
8675 watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST - 1);
8677 // Route another payment to generate another update with still previous HTLC pending
8678 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8679 nodes[1].node.send_payment_with_route(&route, payment_hash,
8680 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8681 check_added_monitors!(nodes[1], 1);
8683 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8684 assert_eq!(updates.update_add_htlcs.len(), 1);
8685 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8687 let mut node_0_per_peer_lock;
8688 let mut node_0_peer_state_lock;
8689 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) {
8690 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8691 // Watchtower Alice should already have seen the block and reject the update
8692 assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::InProgress);
8693 assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8694 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8695 } else { assert!(false); }
8700 // Our local monitor is in-sync and hasn't processed yet timeout
8701 check_added_monitors!(nodes[0], 1);
8703 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8704 watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST);
8706 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8709 let mut txn = bob_broadcaster.txn_broadcast();
8710 assert_eq!(txn.len(), 2);
8711 bob_state_y = txn.remove(0);
8714 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8715 let height = HTLC_TIMEOUT_BROADCAST + 1;
8716 connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
8717 check_closed_broadcast(&nodes[0], 1, true);
8718 check_closed_event!(&nodes[0], 1, ClosureReason::HTLCsTimedOut, false,
8719 [nodes[1].node.get_our_node_id()], 100000);
8720 watchtower_alice.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, vec![bob_state_y.clone()]), height);
8721 check_added_monitors(&nodes[0], 1);
8723 let htlc_txn = alice_broadcaster.txn_broadcast();
8724 assert_eq!(htlc_txn.len(), 1);
8725 check_spends!(htlc_txn[0], bob_state_y);
8730 fn test_pre_lockin_no_chan_closed_update() {
8731 // Test that if a peer closes a channel in response to a funding_created message we don't
8732 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8735 // Doing so would imply a channel monitor update before the initial channel monitor
8736 // registration, violating our API guarantees.
8738 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8739 // then opening a second channel with the same funding output as the first (which is not
8740 // rejected because the first channel does not exist in the ChannelManager) and closing it
8741 // before receiving funding_signed.
8742 let chanmon_cfgs = create_chanmon_cfgs(2);
8743 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8744 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8745 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8747 // Create an initial channel
8748 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
8749 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8750 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8751 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8752 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8754 // Move the first channel through the funding flow...
8755 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8757 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8758 check_added_monitors!(nodes[0], 0);
8760 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8761 let channel_id = ChannelId::v1_from_funding_outpoint(crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index });
8762 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8763 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8764 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("Hi".to_string()) }, true,
8765 [nodes[1].node.get_our_node_id()], 100000);
8769 fn test_htlc_no_detection() {
8770 // This test is a mutation to underscore the detection logic bug we had
8771 // before #653. HTLC value routed is above the remaining balance, thus
8772 // inverting HTLC and `to_remote` output. HTLC will come second and
8773 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8774 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8775 // outputs order detection for correct spending children filtring.
8777 let chanmon_cfgs = create_chanmon_cfgs(2);
8778 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8779 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8780 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8782 // Create some initial channels
8783 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8785 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8786 let (_, our_payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8787 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8788 assert_eq!(local_txn[0].input.len(), 1);
8789 assert_eq!(local_txn[0].output.len(), 3);
8790 check_spends!(local_txn[0], chan_1.3);
8792 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8793 let block = create_dummy_block(nodes[0].best_block_hash(), 42, vec![local_txn[0].clone()]);
8794 connect_block(&nodes[0], &block);
8795 // We deliberately connect the local tx twice as this should provoke a failure calling
8796 // this test before #653 fix.
8797 chain::Listen::block_connected(&nodes[0].chain_monitor.chain_monitor, &block, nodes[0].best_block_info().1 + 1);
8798 check_closed_broadcast!(nodes[0], true);
8799 check_added_monitors!(nodes[0], 1);
8800 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
8801 connect_blocks(&nodes[0], TEST_FINAL_CLTV);
8803 let htlc_timeout = {
8804 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8805 assert_eq!(node_txn.len(), 1);
8806 assert_eq!(node_txn[0].input.len(), 1);
8807 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8808 check_spends!(node_txn[0], local_txn[0]);
8812 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![htlc_timeout.clone()]));
8813 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8814 expect_payment_failed!(nodes[0], our_payment_hash, false);
8817 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8818 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8819 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8820 // Carol, Alice would be the upstream node, and Carol the downstream.)
8822 // Steps of the test:
8823 // 1) Alice sends a HTLC to Carol through Bob.
8824 // 2) Carol doesn't settle the HTLC.
8825 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8826 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8827 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8828 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8829 // 5) Carol release the preimage to Bob off-chain.
8830 // 6) Bob claims the offered output on the broadcasted commitment.
8831 let chanmon_cfgs = create_chanmon_cfgs(3);
8832 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8833 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8834 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8836 // Create some initial channels
8837 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8838 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8840 // Steps (1) and (2):
8841 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8842 let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8844 // Check that Alice's commitment transaction now contains an output for this HTLC.
8845 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8846 check_spends!(alice_txn[0], chan_ab.3);
8847 assert_eq!(alice_txn[0].output.len(), 2);
8848 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8849 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8850 assert_eq!(alice_txn.len(), 2);
8852 // Steps (3) and (4):
8853 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8854 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8855 let mut force_closing_node = 0; // Alice force-closes
8856 let mut counterparty_node = 1; // Bob if Alice force-closes
8859 if !broadcast_alice {
8860 force_closing_node = 1;
8861 counterparty_node = 0;
8863 let error_message = "Channel force-closed";
8864 nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id(), error_message.to_string()).unwrap();
8865 check_closed_broadcast!(nodes[force_closing_node], true);
8866 check_added_monitors!(nodes[force_closing_node], 1);
8867 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(true) }, [nodes[counterparty_node].node.get_our_node_id()], 100000);
8868 if go_onchain_before_fulfill {
8869 let txn_to_broadcast = match broadcast_alice {
8870 true => alice_txn.clone(),
8871 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8873 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8874 if broadcast_alice {
8875 check_closed_broadcast!(nodes[1], true);
8876 check_added_monitors!(nodes[1], 1);
8877 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
8882 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8883 // process of removing the HTLC from their commitment transactions.
8884 nodes[2].node.claim_funds(payment_preimage);
8885 check_added_monitors!(nodes[2], 1);
8886 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8888 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8889 assert!(carol_updates.update_add_htlcs.is_empty());
8890 assert!(carol_updates.update_fail_htlcs.is_empty());
8891 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8892 assert!(carol_updates.update_fee.is_none());
8893 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8895 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8896 let went_onchain = go_onchain_before_fulfill || force_closing_node == 1;
8897 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if went_onchain { None } else { Some(1000) }, went_onchain, false);
8898 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8899 if !go_onchain_before_fulfill && broadcast_alice {
8900 let events = nodes[1].node.get_and_clear_pending_msg_events();
8901 assert_eq!(events.len(), 1);
8903 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8904 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8906 _ => panic!("Unexpected event"),
8909 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8910 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8911 // Carol<->Bob's updated commitment transaction info.
8912 check_added_monitors!(nodes[1], 2);
8914 let events = nodes[1].node.get_and_clear_pending_msg_events();
8915 assert_eq!(events.len(), 2);
8916 let bob_revocation = match events[0] {
8917 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8918 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8921 _ => panic!("Unexpected event"),
8923 let bob_updates = match events[1] {
8924 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8925 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8928 _ => panic!("Unexpected event"),
8931 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8932 check_added_monitors!(nodes[2], 1);
8933 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8934 check_added_monitors!(nodes[2], 1);
8936 let events = nodes[2].node.get_and_clear_pending_msg_events();
8937 assert_eq!(events.len(), 1);
8938 let carol_revocation = match events[0] {
8939 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8940 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8943 _ => panic!("Unexpected event"),
8945 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8946 check_added_monitors!(nodes[1], 1);
8948 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8949 // here's where we put said channel's commitment tx on-chain.
8950 let mut txn_to_broadcast = alice_txn.clone();
8951 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8952 if !go_onchain_before_fulfill {
8953 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8954 // If Bob was the one to force-close, he will have already passed these checks earlier.
8955 if broadcast_alice {
8956 check_closed_broadcast!(nodes[1], true);
8957 check_added_monitors!(nodes[1], 1);
8958 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
8960 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8961 if broadcast_alice {
8962 assert_eq!(bob_txn.len(), 1);
8963 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8965 if nodes[1].connect_style.borrow().updates_best_block_first() {
8966 assert_eq!(bob_txn.len(), 3);
8967 assert_eq!(bob_txn[0].txid(), bob_txn[1].txid());
8969 assert_eq!(bob_txn.len(), 2);
8971 check_spends!(bob_txn[0], chan_ab.3);
8976 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8977 // broadcasted commitment transaction.
8979 let script_weight = match broadcast_alice {
8980 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8981 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8983 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8984 // Bob force-closed and broadcasts the commitment transaction along with a
8985 // HTLC-output-claiming transaction.
8986 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8987 if broadcast_alice {
8988 assert_eq!(bob_txn.len(), 1);
8989 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8990 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8992 assert_eq!(bob_txn.len(), if nodes[1].connect_style.borrow().updates_best_block_first() { 3 } else { 2 });
8993 let htlc_tx = bob_txn.pop().unwrap();
8994 check_spends!(htlc_tx, txn_to_broadcast[0]);
8995 assert_eq!(htlc_tx.input[0].witness.last().unwrap().len(), script_weight);
9001 fn test_onchain_htlc_settlement_after_close() {
9002 do_test_onchain_htlc_settlement_after_close(true, true);
9003 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
9004 do_test_onchain_htlc_settlement_after_close(true, false);
9005 do_test_onchain_htlc_settlement_after_close(false, false);
9009 fn test_duplicate_temporary_channel_id_from_different_peers() {
9010 // Tests that we can accept two different `OpenChannel` requests with the same
9011 // `temporary_channel_id`, as long as they are from different peers.
9012 let chanmon_cfgs = create_chanmon_cfgs(3);
9013 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9014 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9015 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9017 // Create an first channel channel
9018 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
9019 let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
9021 // Create an second channel
9022 nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None, None).unwrap();
9023 let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
9025 // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
9026 // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
9027 open_chan_msg_chan_2_0.common_fields.temporary_channel_id = open_chan_msg_chan_1_0.common_fields.temporary_channel_id;
9029 // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
9030 // `temporary_channel_id` as they are from different peers.
9031 nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
9033 let events = nodes[0].node.get_and_clear_pending_msg_events();
9034 assert_eq!(events.len(), 1);
9036 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
9037 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
9038 assert_eq!(msg.common_fields.temporary_channel_id, open_chan_msg_chan_1_0.common_fields.temporary_channel_id);
9040 _ => panic!("Unexpected event"),
9044 nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
9046 let events = nodes[0].node.get_and_clear_pending_msg_events();
9047 assert_eq!(events.len(), 1);
9049 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
9050 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
9051 assert_eq!(msg.common_fields.temporary_channel_id, open_chan_msg_chan_1_0.common_fields.temporary_channel_id);
9053 _ => panic!("Unexpected event"),
9059 fn test_peer_funding_sidechannel() {
9060 // Test that if a peer somehow learns which txid we'll use for our channel funding before we
9061 // receive `funding_transaction_generated` the peer cannot cause us to crash. We'd previously
9062 // assumed that LDK would receive `funding_transaction_generated` prior to our peer learning
9063 // the txid and panicked if the peer tried to open a redundant channel to us with the same
9064 // funding outpoint.
9066 // While this assumption is generally safe, some users may have out-of-band protocols where
9067 // they notify their LSP about a funding outpoint first, or this may be violated in the future
9068 // with collaborative transaction construction protocols, i.e. dual-funding.
9069 let chanmon_cfgs = create_chanmon_cfgs(3);
9070 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9071 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9072 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9074 let temp_chan_id_ab = exchange_open_accept_chan(&nodes[0], &nodes[1], 1_000_000, 0);
9075 let temp_chan_id_ca = exchange_open_accept_chan(&nodes[2], &nodes[0], 1_000_000, 0);
9077 let (_, tx, funding_output) =
9078 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9080 let cs_funding_events = nodes[2].node.get_and_clear_pending_events();
9081 assert_eq!(cs_funding_events.len(), 1);
9082 match cs_funding_events[0] {
9083 Event::FundingGenerationReady { .. } => {}
9084 _ => panic!("Unexpected event {:?}", cs_funding_events),
9087 nodes[2].node.funding_transaction_generated_unchecked(&temp_chan_id_ca, &nodes[0].node.get_our_node_id(), tx.clone(), funding_output.index).unwrap();
9088 let funding_created_msg = get_event_msg!(nodes[2], MessageSendEvent::SendFundingCreated, nodes[0].node.get_our_node_id());
9089 nodes[0].node.handle_funding_created(&nodes[2].node.get_our_node_id(), &funding_created_msg);
9090 get_event_msg!(nodes[0], MessageSendEvent::SendFundingSigned, nodes[2].node.get_our_node_id());
9091 expect_channel_pending_event(&nodes[0], &nodes[2].node.get_our_node_id());
9092 check_added_monitors!(nodes[0], 1);
9094 let res = nodes[0].node.funding_transaction_generated(&temp_chan_id_ab, &nodes[1].node.get_our_node_id(), tx.clone());
9095 let err_msg = format!("{:?}", res.unwrap_err());
9096 assert!(err_msg.contains("An existing channel using outpoint "));
9097 assert!(err_msg.contains(" is open with peer"));
9098 // Even though the last funding_transaction_generated errored, it still generated a
9099 // SendFundingCreated. However, when the peer responds with a funding_signed it will send the
9100 // appropriate error message.
9101 let as_funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9102 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &as_funding_created);
9103 check_added_monitors!(nodes[1], 1);
9104 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9105 let reason = ClosureReason::ProcessingError { err: format!("An existing channel using outpoint {} is open with peer {}", funding_output, nodes[2].node.get_our_node_id()), };
9106 check_closed_events(&nodes[0], &[ExpectedCloseEvent::from_id_reason(ChannelId::v1_from_funding_outpoint(funding_output), true, reason)]);
9108 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9109 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
9110 get_err_msg(&nodes[0], &nodes[1].node.get_our_node_id());
9114 fn test_duplicate_conflicting_funding_from_second_peer() {
9115 // Test that if a user tries to fund a channel with a funding outpoint they'd previously used
9116 // we don't try to remove the previous ChannelMonitor. This is largely a test to ensure we
9117 // don't regress in the fuzzer, as such funding getting passed our outpoint-matches checks
9118 // implies the user (and our counterparty) has reused cryptographic keys across channels, which
9119 // we require the user not do.
9120 let chanmon_cfgs = create_chanmon_cfgs(4);
9121 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9122 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9123 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9125 let temp_chan_id = exchange_open_accept_chan(&nodes[0], &nodes[1], 1_000_000, 0);
9127 let (_, tx, funding_output) =
9128 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9130 // Now that we have a funding outpoint, create a dummy `ChannelMonitor` and insert it into
9131 // nodes[0]'s ChainMonitor so that the initial `ChannelMonitor` write fails.
9132 let dummy_chan_id = create_chan_between_nodes(&nodes[2], &nodes[3]).3;
9133 let dummy_monitor = get_monitor!(nodes[2], dummy_chan_id).clone();
9134 nodes[0].chain_monitor.chain_monitor.watch_channel(funding_output, dummy_monitor).unwrap();
9136 nodes[0].node.funding_transaction_generated(&temp_chan_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9138 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9139 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9140 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9141 check_added_monitors!(nodes[1], 1);
9142 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9144 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9145 // At this point, the channel should be closed, after having generated one monitor write (the
9146 // watch_channel call which failed), but zero monitor updates.
9147 check_added_monitors!(nodes[0], 1);
9148 get_err_msg(&nodes[0], &nodes[1].node.get_our_node_id());
9149 let err_reason = ClosureReason::ProcessingError { err: "Channel funding outpoint was a duplicate".to_owned() };
9150 check_closed_events(&nodes[0], &[ExpectedCloseEvent::from_id_reason(funding_signed_msg.channel_id, true, err_reason)]);
9154 fn test_duplicate_funding_err_in_funding() {
9155 // Test that if we have a live channel with one peer, then another peer comes along and tries
9156 // to create a second channel with the same txid we'll fail and not overwrite the
9157 // outpoint_to_peer map in `ChannelManager`.
9159 // This was previously broken.
9160 let chanmon_cfgs = create_chanmon_cfgs(3);
9161 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9162 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9163 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9165 let (_, _, _, real_channel_id, funding_tx) = create_chan_between_nodes(&nodes[0], &nodes[1]);
9166 let real_chan_funding_txo = chain::transaction::OutPoint { txid: funding_tx.txid(), index: 0 };
9167 assert_eq!(ChannelId::v1_from_funding_outpoint(real_chan_funding_txo), real_channel_id);
9169 nodes[2].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
9170 let mut open_chan_msg = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9171 let node_c_temp_chan_id = open_chan_msg.common_fields.temporary_channel_id;
9172 open_chan_msg.common_fields.temporary_channel_id = real_channel_id;
9173 nodes[1].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg);
9174 let mut accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[2].node.get_our_node_id());
9175 accept_chan_msg.common_fields.temporary_channel_id = node_c_temp_chan_id;
9176 nodes[2].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
9178 // Now that we have a second channel with the same funding txo, send a bogus funding message
9179 // and let nodes[1] remove the inbound channel.
9180 let (_, funding_tx, _) = create_funding_transaction(&nodes[2], &nodes[1].node.get_our_node_id(), 100_000, 42);
9182 nodes[2].node.funding_transaction_generated(&node_c_temp_chan_id, &nodes[1].node.get_our_node_id(), funding_tx).unwrap();
9184 let mut funding_created_msg = get_event_msg!(nodes[2], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9185 funding_created_msg.temporary_channel_id = real_channel_id;
9186 // Make the signature invalid by changing the funding output
9187 funding_created_msg.funding_output_index += 10;
9188 nodes[1].node.handle_funding_created(&nodes[2].node.get_our_node_id(), &funding_created_msg);
9189 get_err_msg(&nodes[1], &nodes[2].node.get_our_node_id());
9190 let err = "Invalid funding_created signature from peer".to_owned();
9191 let reason = ClosureReason::ProcessingError { err };
9192 let expected_closing = ExpectedCloseEvent::from_id_reason(real_channel_id, false, reason);
9193 check_closed_events(&nodes[1], &[expected_closing]);
9196 *nodes[1].node.outpoint_to_peer.lock().unwrap().get(&real_chan_funding_txo).unwrap(),
9197 nodes[0].node.get_our_node_id()
9202 fn test_duplicate_chan_id() {
9203 // Test that if a given peer tries to open a channel with the same channel_id as one that is
9204 // already open we reject it and keep the old channel.
9206 // Previously, full_stack_target managed to figure out that if you tried to open two channels
9207 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
9208 // the existing channel when we detect the duplicate new channel, screwing up our monitor
9209 // updating logic for the existing channel.
9210 let chanmon_cfgs = create_chanmon_cfgs(2);
9211 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9212 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9213 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9215 // Create an initial channel
9216 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
9217 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9218 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
9219 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()));
9221 // Try to create a second channel with the same temporary_channel_id as the first and check
9222 // that it is rejected.
9223 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
9225 let events = nodes[1].node.get_and_clear_pending_msg_events();
9226 assert_eq!(events.len(), 1);
9228 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9229 // Technically, at this point, nodes[1] would be justified in thinking both the
9230 // first (valid) and second (invalid) channels are closed, given they both have
9231 // the same non-temporary channel_id. However, currently we do not, so we just
9232 // move forward with it.
9233 assert_eq!(msg.channel_id, open_chan_msg.common_fields.temporary_channel_id);
9234 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9236 _ => panic!("Unexpected event"),
9240 // Move the first channel through the funding flow...
9241 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9243 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9244 check_added_monitors!(nodes[0], 0);
9246 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9247 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9249 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9250 assert_eq!(added_monitors.len(), 1);
9251 assert_eq!(added_monitors[0].0, funding_output);
9252 added_monitors.clear();
9254 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9256 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9258 let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
9259 let channel_id = ChannelId::v1_from_funding_outpoint(funding_outpoint);
9261 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
9264 // First try to open a second channel with a temporary channel id equal to the txid-based one.
9265 // Technically this is allowed by the spec, but we don't support it and there's little reason
9266 // to. Still, it shouldn't cause any other issues.
9267 open_chan_msg.common_fields.temporary_channel_id = channel_id;
9268 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
9270 let events = nodes[1].node.get_and_clear_pending_msg_events();
9271 assert_eq!(events.len(), 1);
9273 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9274 // Technically, at this point, nodes[1] would be justified in thinking both
9275 // channels are closed, but currently we do not, so we just move forward with it.
9276 assert_eq!(msg.channel_id, open_chan_msg.common_fields.temporary_channel_id);
9277 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9279 _ => panic!("Unexpected event"),
9283 // Now try to create a second channel which has a duplicate funding output.
9284 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
9285 let open_chan_2_msg = 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_chan_2_msg);
9287 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()));
9288 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
9290 let funding_created = {
9291 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9292 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9293 // Once we call `get_funding_created` the channel has a duplicate channel_id as
9294 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
9295 // try to create another channel. Instead, we drop the channel entirely here (leaving the
9296 // channelmanager in a possibly nonsense state instead).
9297 match a_peer_state.channel_by_id.remove(&open_chan_2_msg.common_fields.temporary_channel_id).unwrap() {
9298 ChannelPhase::UnfundedOutboundV1(mut chan) => {
9299 let logger = test_utils::TestLogger::new();
9300 chan.get_funding_created(tx.clone(), funding_outpoint, false, &&logger).map_err(|_| ()).unwrap()
9302 _ => panic!("Unexpected ChannelPhase variant"),
9305 check_added_monitors!(nodes[0], 0);
9306 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9307 // At this point we'll look up if the channel_id is present and immediately fail the channel
9308 // without trying to persist the `ChannelMonitor`.
9309 check_added_monitors!(nodes[1], 0);
9311 check_closed_events(&nodes[1], &[
9312 ExpectedCloseEvent::from_id_reason(funding_created.temporary_channel_id, false, ClosureReason::ProcessingError {
9313 err: "Already had channel with the new channel_id".to_owned()
9317 // ...still, nodes[1] will reject the duplicate channel.
9319 let events = nodes[1].node.get_and_clear_pending_msg_events();
9320 assert_eq!(events.len(), 1);
9322 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9323 // Technically, at this point, nodes[1] would be justified in thinking both
9324 // channels are closed, but currently we do not, so we just move forward with it.
9325 assert_eq!(msg.channel_id, channel_id);
9326 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9328 _ => panic!("Unexpected event"),
9332 // finally, finish creating the original channel and send a payment over it to make sure
9333 // everything is functional.
9334 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9336 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9337 assert_eq!(added_monitors.len(), 1);
9338 assert_eq!(added_monitors[0].0, funding_output);
9339 added_monitors.clear();
9341 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9343 let events_4 = nodes[0].node.get_and_clear_pending_events();
9344 assert_eq!(events_4.len(), 0);
9345 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9346 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9348 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9349 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9350 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9352 send_payment(&nodes[0], &[&nodes[1]], 8000000);
9356 fn test_error_chans_closed() {
9357 // Test that we properly handle error messages, closing appropriate channels.
9359 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9360 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9361 // we can test various edge cases around it to ensure we don't regress.
9362 let chanmon_cfgs = create_chanmon_cfgs(3);
9363 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9364 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9365 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9367 // Create some initial channels
9368 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9369 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9370 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
9372 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9373 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9374 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9376 // Closing a channel from a different peer has no effect
9377 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9378 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9380 // Closing one channel doesn't impact others
9381 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9382 check_added_monitors!(nodes[0], 1);
9383 check_closed_broadcast!(nodes[0], false);
9384 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) },
9385 [nodes[1].node.get_our_node_id()], 100000);
9386 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9387 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9388 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);
9389 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);
9391 // A null channel ID should close all channels
9392 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9393 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: ChannelId::new_zero(), data: "ERR".to_owned() });
9394 check_added_monitors!(nodes[0], 2);
9395 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) },
9396 [nodes[1].node.get_our_node_id(); 2], 100000);
9397 let events = nodes[0].node.get_and_clear_pending_msg_events();
9398 assert_eq!(events.len(), 2);
9400 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9401 assert_eq!(msg.contents.channel_flags & 2, 2);
9403 _ => panic!("Unexpected event"),
9406 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9407 assert_eq!(msg.contents.channel_flags & 2, 2);
9409 _ => panic!("Unexpected event"),
9411 // Note that at this point users of a standard PeerHandler will end up calling
9412 // peer_disconnected.
9413 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9414 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9416 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9417 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9418 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9422 fn test_invalid_funding_tx() {
9423 // Test that we properly handle invalid funding transactions sent to us from a peer.
9425 // Previously, all other major lightning implementations had failed to properly sanitize
9426 // funding transactions from their counterparties, leading to a multi-implementation critical
9427 // security vulnerability (though we always sanitized properly, we've previously had
9428 // un-released crashes in the sanitization process).
9430 // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9431 // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9432 // gave up on it. We test this here by generating such a transaction.
9433 let chanmon_cfgs = create_chanmon_cfgs(2);
9434 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9435 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9436 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9438 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None, None).unwrap();
9439 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()));
9440 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()));
9442 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9444 // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9445 // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9446 // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9448 let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9449 let wit_program_script: ScriptBuf = wit_program.into();
9450 for output in tx.output.iter_mut() {
9451 // Make the confirmed funding transaction have a bogus script_pubkey
9452 output.script_pubkey = ScriptBuf::new_p2wsh(&wit_program_script.wscript_hash());
9455 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9456 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()));
9457 check_added_monitors!(nodes[1], 1);
9458 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9460 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()));
9461 check_added_monitors!(nodes[0], 1);
9462 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9464 let events_1 = nodes[0].node.get_and_clear_pending_events();
9465 assert_eq!(events_1.len(), 0);
9467 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9468 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9469 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9471 let expected_err = "funding tx had wrong script/value or output index";
9472 confirm_transaction_at(&nodes[1], &tx, 1);
9473 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() },
9474 [nodes[0].node.get_our_node_id()], 100000);
9475 check_added_monitors!(nodes[1], 1);
9476 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9477 assert_eq!(events_2.len(), 1);
9478 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9479 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9480 if let msgs::ErrorAction::DisconnectPeer { msg } = action {
9481 assert_eq!(msg.as_ref().unwrap().data, "Channel closed because of an exception: ".to_owned() + expected_err);
9482 } else { panic!(); }
9483 } else { panic!(); }
9484 assert_eq!(nodes[1].node.list_channels().len(), 0);
9486 // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9487 // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9488 // as its not 32 bytes long.
9489 let mut spend_tx = Transaction {
9490 version: Version::TWO, lock_time: LockTime::ZERO,
9491 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9492 previous_output: BitcoinOutPoint {
9496 script_sig: ScriptBuf::new(),
9497 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9498 witness: Witness::from_slice(&channelmonitor::deliberately_bogus_accepted_htlc_witness())
9500 output: vec![TxOut {
9501 value: Amount::from_sat(1000),
9502 script_pubkey: ScriptBuf::new(),
9505 check_spends!(spend_tx, tx);
9506 mine_transaction(&nodes[1], &spend_tx);
9510 fn test_coinbase_funding_tx() {
9511 // Miners are able to fund channels directly from coinbase transactions, however
9512 // by consensus rules, outputs of a coinbase transaction are encumbered by a 100
9513 // block maturity timelock. To ensure that a (non-0conf) channel like this is enforceable
9514 // on-chain, the minimum depth is updated to 100 blocks for coinbase funding transactions.
9516 // Note that 0conf channels with coinbase funding transactions are unaffected and are
9517 // immediately operational after opening.
9518 let chanmon_cfgs = create_chanmon_cfgs(2);
9519 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9520 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9521 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9523 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
9524 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9526 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9527 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9529 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9531 // Create the coinbase funding transaction.
9532 let (temporary_channel_id, tx, _) = create_coinbase_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9534 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9535 check_added_monitors!(nodes[0], 0);
9536 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9538 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9539 check_added_monitors!(nodes[1], 1);
9540 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9542 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9544 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
9545 check_added_monitors!(nodes[0], 1);
9547 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9548 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
9550 // Starting at height 0, we "confirm" the coinbase at height 1.
9551 confirm_transaction_at(&nodes[0], &tx, 1);
9552 // We connect 98 more blocks to have 99 confirmations for the coinbase transaction.
9553 connect_blocks(&nodes[0], COINBASE_MATURITY - 2);
9554 // Check that we have no pending message events (we have not queued a `channel_ready` yet).
9555 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
9556 // Now connect one more block which results in 100 confirmations of the coinbase transaction.
9557 connect_blocks(&nodes[0], 1);
9558 // There should now be a `channel_ready` which can be handled.
9559 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()));
9561 confirm_transaction_at(&nodes[1], &tx, 1);
9562 connect_blocks(&nodes[1], COINBASE_MATURITY - 2);
9563 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9564 connect_blocks(&nodes[1], 1);
9565 expect_channel_ready_event(&nodes[1], &nodes[0].node.get_our_node_id());
9566 create_chan_between_nodes_with_value_confirm_second(&nodes[0], &nodes[1]);
9569 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9570 // In the first version of the chain::Confirm interface, after a refactor was made to not
9571 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9572 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9573 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9574 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9575 // spending transaction until height N+1 (or greater). This was due to the way
9576 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9577 // spending transaction at the height the input transaction was confirmed at, not whether we
9578 // should broadcast a spending transaction at the current height.
9579 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9580 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9581 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9582 // until we learned about an additional block.
9584 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9585 // aren't broadcasting transactions too early (ie not broadcasting them at all).
9586 let chanmon_cfgs = create_chanmon_cfgs(3);
9587 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9588 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9589 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9590 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9592 create_announced_chan_between_nodes(&nodes, 0, 1);
9593 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
9594 let (_, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9595 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
9596 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9597 let error_message = "Channel force-closed";
9598 nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id(), error_message.to_string()).unwrap();
9599 check_closed_broadcast!(nodes[1], true);
9600 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(true) }, [nodes[2].node.get_our_node_id()], 100000);
9601 check_added_monitors!(nodes[1], 1);
9602 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9603 assert_eq!(node_txn.len(), 1);
9605 let conf_height = nodes[1].best_block_info().1;
9606 if !test_height_before_timelock {
9607 connect_blocks(&nodes[1], 24 * 6);
9609 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9610 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9611 if test_height_before_timelock {
9612 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9613 // generate any events or broadcast any transactions
9614 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9615 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9617 // We should broadcast an HTLC transaction spending our funding transaction first
9618 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9619 assert_eq!(spending_txn.len(), 2);
9620 let htlc_tx = if spending_txn[0].txid() == node_txn[0].txid() {
9625 check_spends!(htlc_tx, node_txn[0]);
9626 // We should also generate a SpendableOutputs event with the to_self output (as its
9628 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9629 assert_eq!(descriptor_spend_txn.len(), 1);
9631 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9632 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9633 // additional block built on top of the current chain.
9634 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9635 &nodes[1].get_block_header(conf_height + 1), &[(0, htlc_tx)], conf_height + 1);
9636 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 }]);
9637 check_added_monitors!(nodes[1], 1);
9639 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9640 assert!(updates.update_add_htlcs.is_empty());
9641 assert!(updates.update_fulfill_htlcs.is_empty());
9642 assert_eq!(updates.update_fail_htlcs.len(), 1);
9643 assert!(updates.update_fail_malformed_htlcs.is_empty());
9644 assert!(updates.update_fee.is_none());
9645 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9646 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9647 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9652 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9653 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9654 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9657 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9658 let chanmon_cfgs = create_chanmon_cfgs(2);
9659 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9660 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9661 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9663 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9665 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9666 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
9667 let route = get_route!(nodes[0], payment_params, 10_000).unwrap();
9669 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9672 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9673 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9674 check_added_monitors!(nodes[0], 1);
9675 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9676 assert_eq!(events.len(), 1);
9677 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9678 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9679 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9681 expect_pending_htlcs_forwardable!(nodes[1]);
9682 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9685 // Note that we use a different PaymentId here to allow us to duplicativly pay
9686 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9687 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9688 check_added_monitors!(nodes[0], 1);
9689 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9690 assert_eq!(events.len(), 1);
9691 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9692 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9693 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9694 // At this point, nodes[1] would notice it has too much value for the payment. It will
9695 // assume the second is a privacy attack (no longer particularly relevant
9696 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9697 // the first HTLC delivered above.
9700 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9701 nodes[1].node.process_pending_htlc_forwards();
9703 if test_for_second_fail_panic {
9704 // Now we go fail back the first HTLC from the user end.
9705 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9707 let expected_destinations = vec![
9708 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9709 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9711 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], expected_destinations);
9712 nodes[1].node.process_pending_htlc_forwards();
9714 check_added_monitors!(nodes[1], 1);
9715 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9716 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9718 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9719 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9720 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9722 let failure_events = nodes[0].node.get_and_clear_pending_events();
9723 assert_eq!(failure_events.len(), 4);
9724 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9725 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9726 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9727 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9729 // Let the second HTLC fail and claim the first
9730 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9731 nodes[1].node.process_pending_htlc_forwards();
9733 check_added_monitors!(nodes[1], 1);
9734 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9735 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9736 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9738 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9740 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9745 fn test_dup_htlc_second_fail_panic() {
9746 // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9747 // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9748 // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9749 // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9750 do_test_dup_htlc_second_rejected(true);
9754 fn test_dup_htlc_second_rejected() {
9755 // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9756 // simply reject the second HTLC but are still able to claim the first HTLC.
9757 do_test_dup_htlc_second_rejected(false);
9761 fn test_inconsistent_mpp_params() {
9762 // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9763 // such HTLC and allow the second to stay.
9764 let chanmon_cfgs = create_chanmon_cfgs(4);
9765 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9766 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9767 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9769 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9770 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9771 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9772 let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9774 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9775 .with_bolt11_features(nodes[3].node.bolt11_invoice_features()).unwrap();
9776 let mut route = get_route!(nodes[0], payment_params, 15_000_000).unwrap();
9777 assert_eq!(route.paths.len(), 2);
9778 route.paths.sort_by(|path_a, _| {
9779 // Sort the path so that the path through nodes[1] comes first
9780 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9781 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9784 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9786 let cur_height = nodes[0].best_block_info().1;
9787 let payment_id = PaymentId([42; 32]);
9789 let session_privs = {
9790 // We create a fake route here so that we start with three pending HTLCs, which we'll
9791 // ultimately have, just not right away.
9792 let mut dup_route = route.clone();
9793 dup_route.paths.push(route.paths[1].clone());
9794 nodes[0].node.test_add_new_pending_payment(our_payment_hash,
9795 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &dup_route).unwrap()
9797 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
9798 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9799 &None, session_privs[0]).unwrap();
9800 check_added_monitors!(nodes[0], 1);
9803 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9804 assert_eq!(events.len(), 1);
9805 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9807 assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9809 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9810 RecipientOnionFields::secret_only(our_payment_secret), 14_000_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9811 check_added_monitors!(nodes[0], 1);
9814 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9815 assert_eq!(events.len(), 1);
9816 let payment_event = SendEvent::from_event(events.pop().unwrap());
9818 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9819 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9821 expect_pending_htlcs_forwardable!(nodes[2]);
9822 check_added_monitors!(nodes[2], 1);
9824 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9825 assert_eq!(events.len(), 1);
9826 let payment_event = SendEvent::from_event(events.pop().unwrap());
9828 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9829 check_added_monitors!(nodes[3], 0);
9830 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9832 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9833 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9834 // post-payment_secrets) and fail back the new HTLC.
9836 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9837 nodes[3].node.process_pending_htlc_forwards();
9838 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9839 nodes[3].node.process_pending_htlc_forwards();
9841 check_added_monitors!(nodes[3], 1);
9843 let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9844 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9845 commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9847 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 }]);
9848 check_added_monitors!(nodes[2], 1);
9850 let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9851 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9852 commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9854 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9856 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9857 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9858 &None, session_privs[2]).unwrap();
9859 check_added_monitors!(nodes[0], 1);
9861 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9862 assert_eq!(events.len(), 1);
9863 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9865 do_claim_payment_along_route(
9866 ClaimAlongRouteArgs::new(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], our_payment_preimage)
9868 expect_payment_sent(&nodes[0], our_payment_preimage, Some(None), true, true);
9872 fn test_double_partial_claim() {
9873 // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9874 // time out, the sender resends only some of the MPP parts, then the user processes the
9875 // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9877 let chanmon_cfgs = create_chanmon_cfgs(4);
9878 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9879 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9880 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9882 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9883 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9884 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9885 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9887 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9888 assert_eq!(route.paths.len(), 2);
9889 route.paths.sort_by(|path_a, _| {
9890 // Sort the path so that the path through nodes[1] comes first
9891 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9892 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9895 send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9896 // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9897 // amount of time to respond to.
9899 // Connect some blocks to time out the payment
9900 connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9901 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9903 let failed_destinations = vec![
9904 HTLCDestination::FailedPayment { payment_hash },
9905 HTLCDestination::FailedPayment { payment_hash },
9907 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9909 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
9911 // nodes[1] now retries one of the two paths...
9912 nodes[0].node.send_payment_with_route(&route, payment_hash,
9913 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9914 check_added_monitors!(nodes[0], 2);
9916 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9917 assert_eq!(events.len(), 2);
9918 let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
9919 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9921 // At this point nodes[3] has received one half of the payment, and the user goes to handle
9922 // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9923 nodes[3].node.claim_funds(payment_preimage);
9924 check_added_monitors!(nodes[3], 0);
9925 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9928 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9929 #[derive(Clone, Copy, PartialEq)]
9930 enum ExposureEvent {
9931 /// Breach occurs at HTLC forwarding (see `send_htlc`)
9933 /// Breach occurs at HTLC reception (see `update_add_htlc`)
9935 /// Breach occurs at outbound update_fee (see `send_update_fee`)
9936 AtUpdateFeeOutbound,
9939 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool, multiplier_dust_limit: bool, apply_excess_fee: bool) {
9940 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9943 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9944 // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9945 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9946 // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9947 // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9948 // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9949 // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9950 // might be available again for HTLC processing once the dust bandwidth has cleared up.
9952 let chanmon_cfgs = create_chanmon_cfgs(2);
9953 let mut config = test_default_channel_config();
9955 // We hard-code the feerate values here but they're re-calculated furter down and asserted.
9956 // If the values ever change below these constants should simply be updated.
9957 const AT_FEE_OUTBOUND_HTLCS: u64 = 20;
9958 let nondust_htlc_count_in_limit =
9959 if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9960 AT_FEE_OUTBOUND_HTLCS
9962 let initial_feerate = if apply_excess_fee { 253 * 2 } else { 253 };
9963 let expected_dust_buffer_feerate = initial_feerate + 2530;
9964 let mut commitment_tx_cost = commit_tx_fee_msat(initial_feerate - 253, nondust_htlc_count_in_limit, &ChannelTypeFeatures::empty());
9965 commitment_tx_cost +=
9967 htlc_success_tx_weight(&ChannelTypeFeatures::empty())
9969 htlc_timeout_tx_weight(&ChannelTypeFeatures::empty())
9970 } * (initial_feerate as u64 - 253) / 1000 * nondust_htlc_count_in_limit;
9972 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9973 *feerate_lock = initial_feerate;
9975 config.channel_config.max_dust_htlc_exposure = if multiplier_dust_limit {
9976 // Default test fee estimator rate is 253 sat/kw, so we set the multiplier to 5_000_000 / 253
9977 // to get roughly the same initial value as the default setting when this test was
9978 // originally written.
9979 MaxDustHTLCExposure::FeeRateMultiplier((5_000_000 + commitment_tx_cost) / 253)
9980 } else { MaxDustHTLCExposure::FixedLimitMsat(5_000_000 + commitment_tx_cost) };
9981 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9982 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9983 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9985 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None, None).unwrap();
9986 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9987 open_channel.common_fields.max_htlc_value_in_flight_msat = 50_000_000;
9988 open_channel.common_fields.max_accepted_htlcs = 60;
9990 open_channel.common_fields.dust_limit_satoshis = 546;
9992 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9993 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9994 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9996 let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
9998 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
10001 let mut node_0_per_peer_lock;
10002 let mut node_0_peer_state_lock;
10003 match get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, temporary_channel_id) {
10004 ChannelPhase::UnfundedOutboundV1(chan) => {
10005 chan.context.holder_dust_limit_satoshis = 546;
10007 _ => panic!("Unexpected ChannelPhase variant"),
10011 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
10012 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()));
10013 check_added_monitors!(nodes[1], 1);
10014 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
10016 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()));
10017 check_added_monitors!(nodes[0], 1);
10018 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
10020 let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
10021 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
10022 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
10025 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10026 *feerate_lock = 253;
10029 // Fetch a route in advance as we will be unable to once we're unable to send.
10030 let (mut route, payment_hash, _, payment_secret) =
10031 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
10033 let (dust_buffer_feerate, max_dust_htlc_exposure_msat) = {
10034 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
10035 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
10036 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
10037 (chan.context().get_dust_buffer_feerate(None) as u64,
10038 chan.context().get_max_dust_htlc_exposure_msat(253))
10040 assert_eq!(dust_buffer_feerate, expected_dust_buffer_feerate as u64);
10041 let dust_outbound_htlc_on_holder_tx_msat: u64 = (dust_buffer_feerate * htlc_timeout_tx_weight(&channel_type_features) / 1000 + open_channel.common_fields.dust_limit_satoshis - 1) * 1000;
10042 let dust_outbound_htlc_on_holder_tx: u64 = max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
10044 // Substract 3 sats for multiplier and 2 sats for fixed limit to make sure we are 50% below the dust limit.
10045 // This is to make sure we fully use the dust limit. If we don't, we could end up with `dust_ibd_htlc_on_holder_tx` being 1
10046 // while `max_dust_htlc_exposure_msat` is not equal to `dust_outbound_htlc_on_holder_tx_msat`.
10047 let dust_inbound_htlc_on_holder_tx_msat: u64 = (dust_buffer_feerate * htlc_success_tx_weight(&channel_type_features) / 1000 + open_channel.common_fields.dust_limit_satoshis - if multiplier_dust_limit { 3 } else { 2 }) * 1000;
10048 let dust_inbound_htlc_on_holder_tx: u64 = max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
10050 // This test was written with a fixed dust value here, which we retain, but assert that it is,
10051 // indeed, dust on both transactions.
10052 let dust_htlc_on_counterparty_tx: u64 = 4;
10053 let dust_htlc_on_counterparty_tx_msat: u64 = 1_250_000;
10054 let calcd_dust_htlc_on_counterparty_tx_msat: u64 = (dust_buffer_feerate * htlc_timeout_tx_weight(&channel_type_features) / 1000 + open_channel.common_fields.dust_limit_satoshis - if multiplier_dust_limit { 3 } else { 2 }) * 1000;
10055 assert!(dust_htlc_on_counterparty_tx_msat < dust_inbound_htlc_on_holder_tx_msat);
10056 assert!(dust_htlc_on_counterparty_tx_msat < calcd_dust_htlc_on_counterparty_tx_msat);
10059 if dust_outbound_balance {
10060 // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10061 // Outbound dust balance: 4372 sats
10062 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
10063 for _ in 0..dust_outbound_htlc_on_holder_tx {
10064 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
10065 nodes[0].node.send_payment_with_route(&route, payment_hash,
10066 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
10069 // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10070 // Inbound dust balance: 4372 sats
10071 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
10072 for _ in 0..dust_inbound_htlc_on_holder_tx {
10073 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
10077 if dust_outbound_balance {
10078 // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10079 // Outbound dust balance: 5000 sats
10080 for _ in 0..dust_htlc_on_counterparty_tx - 1 {
10081 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
10082 nodes[0].node.send_payment_with_route(&route, payment_hash,
10083 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
10086 // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10087 // Inbound dust balance: 5000 sats
10088 for _ in 0..dust_htlc_on_counterparty_tx - 1 {
10089 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
10094 if exposure_breach_event == ExposureEvent::AtHTLCForward {
10095 route.paths[0].hops.last_mut().unwrap().fee_msat =
10096 if on_holder_tx { dust_outbound_htlc_on_holder_tx_msat } else { dust_htlc_on_counterparty_tx_msat + 1 };
10097 // With default dust exposure: 5000 sats
10099 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
10100 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
10101 ), true, APIError::ChannelUnavailable { .. }, {});
10103 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
10104 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
10105 ), true, APIError::ChannelUnavailable { .. }, {});
10107 } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
10108 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 });
10109 nodes[1].node.send_payment_with_route(&route, payment_hash,
10110 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
10111 check_added_monitors!(nodes[1], 1);
10112 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
10113 assert_eq!(events.len(), 1);
10114 let payment_event = SendEvent::from_event(events.remove(0));
10115 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
10116 // With default dust exposure: 5000 sats
10118 // Outbound dust balance: 6399 sats
10119 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
10120 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
10121 nodes[0].logger.assert_log("lightning::ln::channel", format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on holder commitment tx", if dust_outbound_balance { dust_outbound_overflow } else { dust_inbound_overflow }, max_dust_htlc_exposure_msat), 1);
10123 // Outbound dust balance: 5200 sats
10124 nodes[0].logger.assert_log("lightning::ln::channel",
10125 format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx",
10126 dust_htlc_on_counterparty_tx_msat * dust_htlc_on_counterparty_tx + commitment_tx_cost + 4,
10127 max_dust_htlc_exposure_msat), 1);
10129 } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
10130 route.paths[0].hops.last_mut().unwrap().fee_msat = 2_500_000;
10131 // For the multiplier dust exposure limit, since it scales with feerate,
10132 // we need to add a lot of HTLCs that will become dust at the new feerate
10133 // to cross the threshold.
10134 for _ in 0..AT_FEE_OUTBOUND_HTLCS {
10135 let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[1], Some(1_000), None);
10136 nodes[0].node.send_payment_with_route(&route, payment_hash,
10137 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
10140 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10141 *feerate_lock = *feerate_lock * 10;
10143 nodes[0].node.timer_tick_occurred();
10144 check_added_monitors!(nodes[0], 1);
10145 nodes[0].logger.assert_log_contains("lightning::ln::channel", "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure", 1);
10148 let _ = nodes[0].node.get_and_clear_pending_msg_events();
10149 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
10150 added_monitors.clear();
10153 fn do_test_max_dust_htlc_exposure_by_threshold_type(multiplier_dust_limit: bool, apply_excess_fee: bool) {
10154 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true, multiplier_dust_limit, apply_excess_fee);
10155 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true, multiplier_dust_limit, apply_excess_fee);
10156 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true, multiplier_dust_limit, apply_excess_fee);
10157 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false, multiplier_dust_limit, apply_excess_fee);
10158 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false, multiplier_dust_limit, apply_excess_fee);
10159 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false, multiplier_dust_limit, apply_excess_fee);
10160 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true, multiplier_dust_limit, apply_excess_fee);
10161 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false, multiplier_dust_limit, apply_excess_fee);
10162 if !multiplier_dust_limit && !apply_excess_fee {
10163 // Because non-dust HTLC transaction fees are included in the dust exposure, trying to
10164 // increase the fee to hit a higher dust exposure with a
10165 // `MaxDustHTLCExposure::FeeRateMultiplier` is no longer super practical, so we skip these
10166 // in the `multiplier_dust_limit` case.
10167 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true, multiplier_dust_limit, apply_excess_fee);
10168 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false, multiplier_dust_limit, apply_excess_fee);
10169 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false, multiplier_dust_limit, apply_excess_fee);
10170 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true, multiplier_dust_limit, apply_excess_fee);
10175 fn test_max_dust_htlc_exposure() {
10176 do_test_max_dust_htlc_exposure_by_threshold_type(false, false);
10177 do_test_max_dust_htlc_exposure_by_threshold_type(false, true);
10178 do_test_max_dust_htlc_exposure_by_threshold_type(true, false);
10179 do_test_max_dust_htlc_exposure_by_threshold_type(true, true);
10183 fn test_nondust_htlc_fees_are_dust() {
10184 // Test that the transaction fees paid in nondust HTLCs count towards our dust limit
10185 let chanmon_cfgs = create_chanmon_cfgs(3);
10186 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10188 let mut config = test_default_channel_config();
10189 // Set the dust limit to the default value
10190 config.channel_config.max_dust_htlc_exposure =
10191 MaxDustHTLCExposure::FeeRateMultiplier(10_000);
10192 // Make sure the HTLC limits don't get in the way
10193 config.channel_handshake_limits.min_max_accepted_htlcs = 400;
10194 config.channel_handshake_config.our_max_accepted_htlcs = 400;
10195 config.channel_handshake_config.our_htlc_minimum_msat = 1;
10197 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config), Some(config), Some(config)]);
10198 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10200 // Create a channel from 1 -> 0 but immediately push all of the funds towards 0
10201 let chan_id_1 = create_announced_chan_between_nodes(&nodes, 1, 0).2;
10202 while nodes[1].node.list_channels()[0].next_outbound_htlc_limit_msat > 0 {
10203 send_payment(&nodes[1], &[&nodes[0]], nodes[1].node.list_channels()[0].next_outbound_htlc_limit_msat);
10206 // First get the channel one HTLC_VALUE HTLC away from the dust limit by sending dust HTLCs
10207 // repeatedly until we run out of space.
10208 const HTLC_VALUE: u64 = 1_000_000; // Doesn't matter, tune until the test passes
10209 let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], HTLC_VALUE).0;
10211 while nodes[0].node.list_channels()[0].next_outbound_htlc_minimum_msat == 0 {
10212 route_payment(&nodes[0], &[&nodes[1]], HTLC_VALUE);
10214 assert_ne!(nodes[0].node.list_channels()[0].next_outbound_htlc_limit_msat, 0,
10215 "We don't want to run out of ability to send because of some non-dust limit");
10216 assert!(nodes[0].node.list_channels()[0].pending_outbound_htlcs.len() < 10,
10217 "We should be able to fill our dust limit without too many HTLCs");
10219 let dust_limit = nodes[0].node.list_channels()[0].next_outbound_htlc_minimum_msat;
10220 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
10221 assert_ne!(nodes[0].node.list_channels()[0].next_outbound_htlc_minimum_msat, 0,
10222 "Make sure we are able to send once we clear one HTLC");
10224 // At this point we have somewhere between dust_limit and dust_limit * 2 left in our dust
10225 // exposure limit, and we want to max that out using non-dust HTLCs.
10226 let commitment_tx_per_htlc_cost =
10227 htlc_success_tx_weight(&ChannelTypeFeatures::empty()) * 253;
10228 let max_htlcs_remaining = dust_limit * 2 / commitment_tx_per_htlc_cost;
10229 assert!(max_htlcs_remaining < 30,
10230 "We should be able to fill our dust limit without too many HTLCs");
10231 for i in 0..max_htlcs_remaining + 1 {
10232 assert_ne!(i, max_htlcs_remaining);
10233 if nodes[0].node.list_channels()[0].next_outbound_htlc_limit_msat < dust_limit {
10234 // We found our limit, and it was less than max_htlcs_remaining!
10235 // At this point we can only send dust HTLCs as any non-dust HTLCs will overuse our
10236 // remaining dust exposure.
10239 route_payment(&nodes[0], &[&nodes[1]], dust_limit * 2);
10242 // At this point non-dust HTLCs are no longer accepted from node 0 -> 1, we also check that
10243 // such HTLCs can't be routed over the same channel either.
10244 create_announced_chan_between_nodes(&nodes, 2, 0);
10245 let (route, payment_hash, _, payment_secret) =
10246 get_route_and_payment_hash!(nodes[2], nodes[1], dust_limit * 2);
10247 let onion = RecipientOnionFields::secret_only(payment_secret);
10248 nodes[2].node.send_payment_with_route(&route, payment_hash, onion, PaymentId([0; 32])).unwrap();
10249 check_added_monitors(&nodes[2], 1);
10250 let send = SendEvent::from_node(&nodes[2]);
10252 nodes[0].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &send.msgs[0]);
10253 commitment_signed_dance!(nodes[0], nodes[2], send.commitment_msg, false, true);
10255 expect_pending_htlcs_forwardable!(nodes[0]);
10256 check_added_monitors(&nodes[0], 1);
10257 let node_id_1 = nodes[1].node.get_our_node_id();
10258 expect_htlc_handling_failed_destinations!(
10259 nodes[0].node.get_and_clear_pending_events(),
10260 &[HTLCDestination::NextHopChannel { node_id: Some(node_id_1), channel_id: chan_id_1 }]
10263 let fail = get_htlc_update_msgs(&nodes[0], &nodes[2].node.get_our_node_id());
10264 nodes[2].node.handle_update_fail_htlc(&nodes[0].node.get_our_node_id(), &fail.update_fail_htlcs[0]);
10265 commitment_signed_dance!(nodes[2], nodes[0], fail.commitment_signed, false);
10266 expect_payment_failed_conditions(&nodes[2], payment_hash, false, PaymentFailedConditions::new());
10271 fn test_non_final_funding_tx() {
10272 let chanmon_cfgs = create_chanmon_cfgs(2);
10273 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10274 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10275 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10277 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
10278 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10279 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10280 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10281 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10283 let best_height = nodes[0].node.best_block.read().unwrap().height;
10285 let chan_id = *nodes[0].network_chan_count.borrow();
10286 let events = nodes[0].node.get_and_clear_pending_events();
10287 let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::ScriptBuf::new(), sequence: Sequence(1), witness: Witness::from_slice(&[&[1]]) };
10288 assert_eq!(events.len(), 1);
10289 let mut tx = match events[0] {
10290 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
10291 // Timelock the transaction _beyond_ the best client height + 1.
10292 Transaction { version: Version(chan_id as i32), lock_time: LockTime::from_height(best_height + 2).unwrap(), input: vec![input], output: vec![TxOut {
10293 value: Amount::from_sat(*channel_value_satoshis), script_pubkey: output_script.clone(),
10296 _ => panic!("Unexpected event"),
10298 // Transaction should fail as it's evaluated as non-final for propagation.
10299 match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
10300 Err(APIError::APIMisuseError { err }) => {
10301 assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
10305 let err = "Error in transaction funding: Misuse error: Funding transaction absolute timelock is non-final".to_owned();
10306 check_closed_events(&nodes[0], &[ExpectedCloseEvent::from_id_reason(temp_channel_id, false, ClosureReason::ProcessingError { err })]);
10307 assert_eq!(get_err_msg(&nodes[0], &nodes[1].node.get_our_node_id()).data, "Failed to fund channel");
10311 fn test_non_final_funding_tx_within_headroom() {
10312 let chanmon_cfgs = create_chanmon_cfgs(2);
10313 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10314 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10315 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10317 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
10318 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10319 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10320 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10321 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10323 let best_height = nodes[0].node.best_block.read().unwrap().height;
10325 let chan_id = *nodes[0].network_chan_count.borrow();
10326 let events = nodes[0].node.get_and_clear_pending_events();
10327 let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::ScriptBuf::new(), sequence: Sequence(1), witness: Witness::from_slice(&[[1]]) };
10328 assert_eq!(events.len(), 1);
10329 let mut tx = match events[0] {
10330 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
10331 // Timelock the transaction within a +1 headroom from the best block.
10332 Transaction { version: Version(chan_id as i32), lock_time: LockTime::from_consensus(best_height + 1), input: vec![input], output: vec![TxOut {
10333 value: Amount::from_sat(*channel_value_satoshis), script_pubkey: output_script.clone(),
10336 _ => panic!("Unexpected event"),
10339 // Transaction should be accepted if it's in a +1 headroom from best block.
10340 assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
10341 get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
10345 fn accept_busted_but_better_fee() {
10346 // If a peer sends us a fee update that is too low, but higher than our previous channel
10347 // feerate, we should accept it. In the future we may want to consider closing the channel
10348 // later, but for now we only accept the update.
10349 let mut chanmon_cfgs = create_chanmon_cfgs(2);
10350 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10351 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10352 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10354 create_chan_between_nodes(&nodes[0], &nodes[1]);
10356 // Set nodes[1] to expect 5,000 sat/kW.
10358 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
10359 *feerate_lock = 5000;
10362 // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
10364 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10365 *feerate_lock = 1000;
10367 nodes[0].node.timer_tick_occurred();
10368 check_added_monitors!(nodes[0], 1);
10370 let events = nodes[0].node.get_and_clear_pending_msg_events();
10371 assert_eq!(events.len(), 1);
10373 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
10374 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
10375 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
10377 _ => panic!("Unexpected event"),
10380 // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
10383 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10384 *feerate_lock = 2000;
10386 nodes[0].node.timer_tick_occurred();
10387 check_added_monitors!(nodes[0], 1);
10389 let events = nodes[0].node.get_and_clear_pending_msg_events();
10390 assert_eq!(events.len(), 1);
10392 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
10393 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
10394 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
10396 _ => panic!("Unexpected event"),
10399 // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
10402 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10403 *feerate_lock = 1000;
10405 nodes[0].node.timer_tick_occurred();
10406 check_added_monitors!(nodes[0], 1);
10408 let events = nodes[0].node.get_and_clear_pending_msg_events();
10409 assert_eq!(events.len(), 1);
10411 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
10412 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
10413 check_closed_event!(nodes[1], 1, ClosureReason::PeerFeerateTooLow {
10414 peer_feerate_sat_per_kw: 1000, required_feerate_sat_per_kw: 5000,
10415 }, [nodes[0].node.get_our_node_id()], 100000);
10416 check_closed_broadcast!(nodes[1], true);
10417 check_added_monitors!(nodes[1], 1);
10419 _ => panic!("Unexpected event"),
10423 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
10424 let mut chanmon_cfgs = create_chanmon_cfgs(2);
10425 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10426 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10427 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10428 let min_final_cltv_expiry_delta = 120;
10429 let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
10430 min_final_cltv_expiry_delta - 2 };
10431 let recv_value = 100_000;
10433 create_chan_between_nodes(&nodes[0], &nodes[1]);
10435 let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), final_cltv_expiry_delta as u32);
10436 let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
10437 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
10438 Some(recv_value), Some(min_final_cltv_expiry_delta));
10439 (payment_hash, payment_preimage, payment_secret)
10441 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
10442 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
10444 let route = get_route!(nodes[0], payment_parameters, recv_value).unwrap();
10445 nodes[0].node.send_payment_with_route(&route, payment_hash,
10446 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
10447 check_added_monitors!(nodes[0], 1);
10448 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10449 assert_eq!(events.len(), 1);
10450 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
10451 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
10452 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
10453 expect_pending_htlcs_forwardable!(nodes[1]);
10456 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
10457 None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
10459 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
10461 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
10463 check_added_monitors!(nodes[1], 1);
10465 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
10466 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
10467 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
10469 expect_payment_failed!(nodes[0], payment_hash, true);
10474 fn test_payment_with_custom_min_cltv_expiry_delta() {
10475 do_payment_with_custom_min_final_cltv_expiry(false, false);
10476 do_payment_with_custom_min_final_cltv_expiry(false, true);
10477 do_payment_with_custom_min_final_cltv_expiry(true, false);
10478 do_payment_with_custom_min_final_cltv_expiry(true, true);
10482 fn test_disconnects_peer_awaiting_response_ticks() {
10483 // Tests that nodes which are awaiting on a response critical for channel responsiveness
10484 // disconnect their counterparty after `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10485 let mut chanmon_cfgs = create_chanmon_cfgs(2);
10486 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10487 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10488 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10490 // Asserts a disconnect event is queued to the user.
10491 let check_disconnect_event = |node: &Node, should_disconnect: bool| {
10492 let disconnect_event = node.node.get_and_clear_pending_msg_events().iter().find_map(|event|
10493 if let MessageSendEvent::HandleError { action, .. } = event {
10494 if let msgs::ErrorAction::DisconnectPeerWithWarning { .. } = action {
10503 assert_eq!(disconnect_event.is_some(), should_disconnect);
10506 // Fires timer ticks ensuring we only attempt to disconnect peers after reaching
10507 // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10508 let check_disconnect = |node: &Node| {
10509 // No disconnect without any timer ticks.
10510 check_disconnect_event(node, false);
10512 // No disconnect with 1 timer tick less than required.
10513 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS - 1 {
10514 node.node.timer_tick_occurred();
10515 check_disconnect_event(node, false);
10518 // Disconnect after reaching the required ticks.
10519 node.node.timer_tick_occurred();
10520 check_disconnect_event(node, true);
10522 // Disconnect again on the next tick if the peer hasn't been disconnected yet.
10523 node.node.timer_tick_occurred();
10524 check_disconnect_event(node, true);
10527 create_chan_between_nodes(&nodes[0], &nodes[1]);
10529 // We'll start by performing a fee update with Alice (nodes[0]) on the channel.
10530 *nodes[0].fee_estimator.sat_per_kw.lock().unwrap() *= 2;
10531 nodes[0].node.timer_tick_occurred();
10532 check_added_monitors!(&nodes[0], 1);
10533 let alice_fee_update = get_htlc_update_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
10534 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), alice_fee_update.update_fee.as_ref().unwrap());
10535 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &alice_fee_update.commitment_signed);
10536 check_added_monitors!(&nodes[1], 1);
10538 // This will prompt Bob (nodes[1]) to respond with his `CommitmentSigned` and `RevokeAndACK`.
10539 let (bob_revoke_and_ack, bob_commitment_signed) = get_revoke_commit_msgs!(&nodes[1], nodes[0].node.get_our_node_id());
10540 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revoke_and_ack);
10541 check_added_monitors!(&nodes[0], 1);
10542 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_commitment_signed);
10543 check_added_monitors(&nodes[0], 1);
10545 // Alice then needs to send her final `RevokeAndACK` to complete the commitment dance. We
10546 // pretend Bob hasn't received the message and check whether he'll disconnect Alice after
10547 // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10548 let alice_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
10549 check_disconnect(&nodes[1]);
10551 // Now, we'll reconnect them to test awaiting a `ChannelReestablish` message.
10553 // Note that since the commitment dance didn't complete above, Alice is expected to resend her
10554 // final `RevokeAndACK` to Bob to complete it.
10555 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
10556 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10557 let bob_init = msgs::Init {
10558 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
10560 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &bob_init, true).unwrap();
10561 let alice_init = msgs::Init {
10562 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
10564 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &alice_init, true).unwrap();
10566 // Upon reconnection, Alice sends her `ChannelReestablish` to Bob. Alice, however, hasn't
10567 // received Bob's yet, so she should disconnect him after reaching
10568 // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10569 let alice_channel_reestablish = get_event_msg!(
10570 nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id()
10572 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &alice_channel_reestablish);
10573 check_disconnect(&nodes[0]);
10575 // Bob now sends his `ChannelReestablish` to Alice to resume the channel and consider it "live".
10576 let bob_channel_reestablish = nodes[1].node.get_and_clear_pending_msg_events().iter().find_map(|event|
10577 if let MessageSendEvent::SendChannelReestablish { node_id, msg } = event {
10578 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
10584 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bob_channel_reestablish);
10586 // Sanity check that Alice won't disconnect Bob since she's no longer waiting for any messages.
10587 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
10588 nodes[0].node.timer_tick_occurred();
10589 check_disconnect_event(&nodes[0], false);
10592 // However, Bob is still waiting on Alice's `RevokeAndACK`, so he should disconnect her after
10593 // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10594 check_disconnect(&nodes[1]);
10596 // Finally, have Bob process the last message.
10597 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &alice_revoke_and_ack);
10598 check_added_monitors(&nodes[1], 1);
10600 // At this point, neither node should attempt to disconnect each other, since they aren't
10601 // waiting on any messages.
10602 for node in &nodes {
10603 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
10604 node.node.timer_tick_occurred();
10605 check_disconnect_event(node, false);
10611 fn test_remove_expired_outbound_unfunded_channels() {
10612 let chanmon_cfgs = create_chanmon_cfgs(2);
10613 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10614 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10615 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10617 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
10618 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10619 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10620 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10621 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10623 let events = nodes[0].node.get_and_clear_pending_events();
10624 assert_eq!(events.len(), 1);
10626 Event::FundingGenerationReady { .. } => (),
10627 _ => panic!("Unexpected event"),
10630 // Asserts the outbound channel has been removed from a nodes[0]'s peer state map.
10631 let check_outbound_channel_existence = |should_exist: bool| {
10632 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
10633 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
10634 assert_eq!(chan_lock.channel_by_id.contains_key(&temp_channel_id), should_exist);
10637 // Channel should exist without any timer ticks.
10638 check_outbound_channel_existence(true);
10640 // Channel should exist with 1 timer tick less than required.
10641 for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS - 1 {
10642 nodes[0].node.timer_tick_occurred();
10643 check_outbound_channel_existence(true)
10646 // Remove channel after reaching the required ticks.
10647 nodes[0].node.timer_tick_occurred();
10648 check_outbound_channel_existence(false);
10650 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
10651 assert_eq!(msg_events.len(), 1);
10652 match msg_events[0] {
10653 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
10654 assert_eq!(msg.data, "Force-closing pending channel due to timeout awaiting establishment handshake");
10656 _ => panic!("Unexpected event"),
10658 check_closed_event(&nodes[0], 1, ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(false) }, false, &[nodes[1].node.get_our_node_id()], 100000);
10662 fn test_remove_expired_inbound_unfunded_channels() {
10663 let chanmon_cfgs = create_chanmon_cfgs(2);
10664 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10665 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10666 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10668 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
10669 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10670 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10671 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10672 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10674 let events = nodes[0].node.get_and_clear_pending_events();
10675 assert_eq!(events.len(), 1);
10677 Event::FundingGenerationReady { .. } => (),
10678 _ => panic!("Unexpected event"),
10681 // Asserts the inbound channel has been removed from a nodes[1]'s peer state map.
10682 let check_inbound_channel_existence = |should_exist: bool| {
10683 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
10684 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
10685 assert_eq!(chan_lock.channel_by_id.contains_key(&temp_channel_id), should_exist);
10688 // Channel should exist without any timer ticks.
10689 check_inbound_channel_existence(true);
10691 // Channel should exist with 1 timer tick less than required.
10692 for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS - 1 {
10693 nodes[1].node.timer_tick_occurred();
10694 check_inbound_channel_existence(true)
10697 // Remove channel after reaching the required ticks.
10698 nodes[1].node.timer_tick_occurred();
10699 check_inbound_channel_existence(false);
10701 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
10702 assert_eq!(msg_events.len(), 1);
10703 match msg_events[0] {
10704 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
10705 assert_eq!(msg.data, "Force-closing pending channel due to timeout awaiting establishment handshake");
10707 _ => panic!("Unexpected event"),
10709 check_closed_event(&nodes[1], 1, ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(false) }, false, &[nodes[0].node.get_our_node_id()], 100000);
10713 fn test_channel_close_when_not_timely_accepted() {
10714 // Create network of two nodes
10715 let chanmon_cfgs = create_chanmon_cfgs(2);
10716 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10717 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10718 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10720 // Simulate peer-disconnects mid-handshake
10721 // The channel is initiated from the node 0 side,
10722 // but the nodes disconnect before node 1 could send accept channel
10723 let create_chan_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
10724 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10725 assert_eq!(open_channel_msg.common_fields.temporary_channel_id, create_chan_id);
10727 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
10728 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10730 // Make sure that we have not removed the OutboundV1Channel from node[0] immediately.
10731 assert_eq!(nodes[0].node.list_channels().len(), 1);
10733 // Since channel was inbound from node[1] perspective, it should have been dropped immediately.
10734 assert_eq!(nodes[1].node.list_channels().len(), 0);
10736 // In the meantime, some time passes.
10737 for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS {
10738 nodes[0].node.timer_tick_occurred();
10741 // Since we disconnected from peer and did not connect back within time,
10742 // we should have forced-closed the channel by now.
10743 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(false) }, [nodes[1].node.get_our_node_id()], 100000);
10744 assert_eq!(nodes[0].node.list_channels().len(), 0);
10747 // Since accept channel message was never received
10748 // The channel should be forced close by now from node 0 side
10749 // and the peer removed from per_peer_state
10750 let node_0_per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
10751 assert_eq!(node_0_per_peer_state.len(), 0);
10756 fn test_rebroadcast_open_channel_when_reconnect_mid_handshake() {
10757 // Create network of two nodes
10758 let chanmon_cfgs = create_chanmon_cfgs(2);
10759 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10760 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10761 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10763 // Simulate peer-disconnects mid-handshake
10764 // The channel is initiated from the node 0 side,
10765 // but the nodes disconnect before node 1 could send accept channel
10766 let create_chan_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
10767 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10768 assert_eq!(open_channel_msg.common_fields.temporary_channel_id, create_chan_id);
10770 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
10771 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10773 // Make sure that we have not removed the OutboundV1Channel from node[0] immediately.
10774 assert_eq!(nodes[0].node.list_channels().len(), 1);
10776 // Since channel was inbound from node[1] perspective, it should have been immediately dropped.
10777 assert_eq!(nodes[1].node.list_channels().len(), 0);
10779 // The peers now reconnect
10780 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
10781 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
10783 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
10784 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
10785 }, false).unwrap();
10787 // Make sure the SendOpenChannel message is added to node_0 pending message events
10788 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
10789 assert_eq!(msg_events.len(), 1);
10790 match &msg_events[0] {
10791 MessageSendEvent::SendOpenChannel { msg, .. } => assert_eq!(msg, &open_channel_msg),
10792 _ => panic!("Unexpected message."),
10796 fn do_test_multi_post_event_actions(do_reload: bool) {
10797 // Tests handling multiple post-Event actions at once.
10798 // There is specific code in ChannelManager to handle channels where multiple post-Event
10799 // `ChannelMonitorUpdates` are pending at once. This test exercises that code.
10801 // Specifically, we test calling `get_and_clear_pending_events` while there are two
10802 // PaymentSents from different channels and one channel has two pending `ChannelMonitorUpdate`s
10803 // - one from an RAA and one from an inbound commitment_signed.
10804 let chanmon_cfgs = create_chanmon_cfgs(3);
10805 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10806 let (persister, chain_monitor);
10807 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10808 let nodes_0_deserialized;
10809 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10811 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
10812 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 0, 2).2;
10814 send_payment(&nodes[0], &[&nodes[1]], 1_000_000);
10815 send_payment(&nodes[0], &[&nodes[2]], 1_000_000);
10817 let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
10818 let (payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[2]], 1_000_000);
10820 nodes[1].node.claim_funds(our_payment_preimage);
10821 check_added_monitors!(nodes[1], 1);
10822 expect_payment_claimed!(nodes[1], our_payment_hash, 1_000_000);
10824 nodes[2].node.claim_funds(payment_preimage_2);
10825 check_added_monitors!(nodes[2], 1);
10826 expect_payment_claimed!(nodes[2], payment_hash_2, 1_000_000);
10828 for dest in &[1, 2] {
10829 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[*dest], nodes[0].node.get_our_node_id());
10830 nodes[0].node.handle_update_fulfill_htlc(&nodes[*dest].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
10831 commitment_signed_dance!(nodes[0], nodes[*dest], htlc_fulfill_updates.commitment_signed, false);
10832 check_added_monitors(&nodes[0], 0);
10835 let (route, payment_hash_3, _, payment_secret_3) =
10836 get_route_and_payment_hash!(nodes[1], nodes[0], 100_000);
10837 let payment_id = PaymentId(payment_hash_3.0);
10838 nodes[1].node.send_payment_with_route(&route, payment_hash_3,
10839 RecipientOnionFields::secret_only(payment_secret_3), payment_id).unwrap();
10840 check_added_monitors(&nodes[1], 1);
10842 let send_event = SendEvent::from_node(&nodes[1]);
10843 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event.msgs[0]);
10844 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_event.commitment_msg);
10845 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
10848 let nodes_0_serialized = nodes[0].node.encode();
10849 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
10850 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_2).encode();
10851 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);
10853 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10854 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10856 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
10857 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[2]));
10860 let events = nodes[0].node.get_and_clear_pending_events();
10861 assert_eq!(events.len(), 4);
10862 if let Event::PaymentSent { payment_preimage, .. } = events[0] {
10863 assert!(payment_preimage == our_payment_preimage || payment_preimage == payment_preimage_2);
10864 } else { panic!(); }
10865 if let Event::PaymentSent { payment_preimage, .. } = events[1] {
10866 assert!(payment_preimage == our_payment_preimage || payment_preimage == payment_preimage_2);
10867 } else { panic!(); }
10868 if let Event::PaymentPathSuccessful { .. } = events[2] {} else { panic!(); }
10869 if let Event::PaymentPathSuccessful { .. } = events[3] {} else { panic!(); }
10871 // After the events are processed, the ChannelMonitorUpdates will be released and, upon their
10872 // completion, we'll respond to nodes[1] with an RAA + CS.
10873 get_revoke_commit_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
10874 check_added_monitors(&nodes[0], 3);
10878 fn test_multi_post_event_actions() {
10879 do_test_multi_post_event_actions(true);
10880 do_test_multi_post_event_actions(false);
10884 fn test_batch_channel_open() {
10885 let chanmon_cfgs = create_chanmon_cfgs(3);
10886 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10887 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10888 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10890 // Initiate channel opening and create the batch channel funding transaction.
10891 let (tx, funding_created_msgs) = create_batch_channel_funding(&nodes[0], &[
10892 (&nodes[1], 100_000, 0, 42, None),
10893 (&nodes[2], 200_000, 0, 43, None),
10896 // Go through the funding_created and funding_signed flow with node 1.
10897 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[0]);
10898 check_added_monitors(&nodes[1], 1);
10899 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
10901 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10902 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
10903 check_added_monitors(&nodes[0], 1);
10905 // The transaction should not have been broadcast before all channels are ready.
10906 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
10908 // Go through the funding_created and funding_signed flow with node 2.
10909 nodes[2].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[1]);
10910 check_added_monitors(&nodes[2], 1);
10911 expect_channel_pending_event(&nodes[2], &nodes[0].node.get_our_node_id());
10913 let funding_signed_msg = get_event_msg!(nodes[2], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10914 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
10915 nodes[0].node.handle_funding_signed(&nodes[2].node.get_our_node_id(), &funding_signed_msg);
10916 check_added_monitors(&nodes[0], 1);
10918 // The transaction should not have been broadcast before persisting all monitors has been
10920 assert_eq!(nodes[0].tx_broadcaster.txn_broadcast().len(), 0);
10921 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
10923 // Complete the persistence of the monitor.
10924 nodes[0].chain_monitor.complete_sole_pending_chan_update(
10925 &ChannelId::v1_from_funding_outpoint(OutPoint { txid: tx.txid(), index: 1 })
10927 let events = nodes[0].node.get_and_clear_pending_events();
10929 // The transaction should only have been broadcast now.
10930 let broadcasted_txs = nodes[0].tx_broadcaster.txn_broadcast();
10931 assert_eq!(broadcasted_txs.len(), 1);
10932 assert_eq!(broadcasted_txs[0], tx);
10934 assert_eq!(events.len(), 2);
10935 assert!(events.iter().any(|e| matches!(
10937 crate::events::Event::ChannelPending {
10938 ref counterparty_node_id,
10940 } if counterparty_node_id == &nodes[1].node.get_our_node_id(),
10942 assert!(events.iter().any(|e| matches!(
10944 crate::events::Event::ChannelPending {
10945 ref counterparty_node_id,
10947 } if counterparty_node_id == &nodes[2].node.get_our_node_id(),
10952 fn test_close_in_funding_batch() {
10953 // This test ensures that if one of the channels
10954 // in the batch closes, the complete batch will close.
10955 let chanmon_cfgs = create_chanmon_cfgs(3);
10956 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10957 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10958 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10960 // Initiate channel opening and create the batch channel funding transaction.
10961 let (tx, funding_created_msgs) = create_batch_channel_funding(&nodes[0], &[
10962 (&nodes[1], 100_000, 0, 42, None),
10963 (&nodes[2], 200_000, 0, 43, None),
10966 // Go through the funding_created and funding_signed flow with node 1.
10967 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[0]);
10968 check_added_monitors(&nodes[1], 1);
10969 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
10971 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10972 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
10973 check_added_monitors(&nodes[0], 1);
10975 // The transaction should not have been broadcast before all channels are ready.
10976 assert_eq!(nodes[0].tx_broadcaster.txn_broadcast().len(), 0);
10978 // Force-close the channel for which we've completed the initial monitor.
10979 let funding_txo_1 = OutPoint { txid: tx.txid(), index: 0 };
10980 let funding_txo_2 = OutPoint { txid: tx.txid(), index: 1 };
10981 let channel_id_1 = ChannelId::v1_from_funding_outpoint(funding_txo_1);
10982 let channel_id_2 = ChannelId::v1_from_funding_outpoint(funding_txo_2);
10983 let error_message = "Channel force-closed";
10984 nodes[0].node.force_close_broadcasting_latest_txn(&channel_id_1, &nodes[1].node.get_our_node_id(), error_message.to_string()).unwrap();
10986 // The monitor should become closed.
10987 check_added_monitors(&nodes[0], 1);
10989 let mut monitor_updates = nodes[0].chain_monitor.monitor_updates.lock().unwrap();
10990 let monitor_updates_1 = monitor_updates.get(&channel_id_1).unwrap();
10991 assert_eq!(monitor_updates_1.len(), 1);
10992 assert_eq!(monitor_updates_1[0].update_id, CLOSED_CHANNEL_UPDATE_ID);
10995 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
10996 match msg_events[0] {
10997 MessageSendEvent::HandleError { .. } => (),
10998 _ => panic!("Unexpected message."),
11001 // We broadcast the commitment transaction as part of the force-close.
11003 let broadcasted_txs = nodes[0].tx_broadcaster.txn_broadcast();
11004 assert_eq!(broadcasted_txs.len(), 1);
11005 assert!(broadcasted_txs[0].txid() != tx.txid());
11006 assert_eq!(broadcasted_txs[0].input.len(), 1);
11007 assert_eq!(broadcasted_txs[0].input[0].previous_output.txid, tx.txid());
11010 // All channels in the batch should close immediately.
11011 check_closed_events(&nodes[0], &[
11012 ExpectedCloseEvent {
11013 channel_id: Some(channel_id_1),
11014 discard_funding: true,
11015 channel_funding_txo: Some(funding_txo_1),
11016 user_channel_id: Some(42),
11017 ..Default::default()
11019 ExpectedCloseEvent {
11020 channel_id: Some(channel_id_2),
11021 discard_funding: true,
11022 channel_funding_txo: Some(funding_txo_2),
11023 user_channel_id: Some(43),
11024 ..Default::default()
11028 // Ensure the channels don't exist anymore.
11029 assert!(nodes[0].node.list_channels().is_empty());
11033 fn test_batch_funding_close_after_funding_signed() {
11034 let chanmon_cfgs = create_chanmon_cfgs(3);
11035 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
11036 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
11037 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
11039 // Initiate channel opening and create the batch channel funding transaction.
11040 let (tx, funding_created_msgs) = create_batch_channel_funding(&nodes[0], &[
11041 (&nodes[1], 100_000, 0, 42, None),
11042 (&nodes[2], 200_000, 0, 43, None),
11045 // Go through the funding_created and funding_signed flow with node 1.
11046 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[0]);
11047 check_added_monitors(&nodes[1], 1);
11048 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
11050 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
11051 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
11052 check_added_monitors(&nodes[0], 1);
11054 // Go through the funding_created and funding_signed flow with node 2.
11055 nodes[2].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[1]);
11056 check_added_monitors(&nodes[2], 1);
11057 expect_channel_pending_event(&nodes[2], &nodes[0].node.get_our_node_id());
11059 let funding_signed_msg = get_event_msg!(nodes[2], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
11060 chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
11061 nodes[0].node.handle_funding_signed(&nodes[2].node.get_our_node_id(), &funding_signed_msg);
11062 check_added_monitors(&nodes[0], 1);
11064 // The transaction should not have been broadcast before all channels are ready.
11065 assert_eq!(nodes[0].tx_broadcaster.txn_broadcast().len(), 0);
11067 // Force-close the channel for which we've completed the initial monitor.
11068 let funding_txo_1 = OutPoint { txid: tx.txid(), index: 0 };
11069 let funding_txo_2 = OutPoint { txid: tx.txid(), index: 1 };
11070 let channel_id_1 = ChannelId::v1_from_funding_outpoint(funding_txo_1);
11071 let channel_id_2 = ChannelId::v1_from_funding_outpoint(funding_txo_2);
11072 let error_message = "Channel force-closed";
11073 nodes[0].node.force_close_broadcasting_latest_txn(&channel_id_1, &nodes[1].node.get_our_node_id(), error_message.to_string()).unwrap();
11074 check_added_monitors(&nodes[0], 2);
11076 let mut monitor_updates = nodes[0].chain_monitor.monitor_updates.lock().unwrap();
11077 let monitor_updates_1 = monitor_updates.get(&channel_id_1).unwrap();
11078 assert_eq!(monitor_updates_1.len(), 1);
11079 assert_eq!(monitor_updates_1[0].update_id, CLOSED_CHANNEL_UPDATE_ID);
11080 let monitor_updates_2 = monitor_updates.get(&channel_id_2).unwrap();
11081 assert_eq!(monitor_updates_2.len(), 1);
11082 assert_eq!(monitor_updates_2[0].update_id, CLOSED_CHANNEL_UPDATE_ID);
11084 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
11085 match msg_events[0] {
11086 MessageSendEvent::HandleError { .. } => (),
11087 _ => panic!("Unexpected message."),
11090 // We broadcast the commitment transaction as part of the force-close.
11092 let broadcasted_txs = nodes[0].tx_broadcaster.txn_broadcast();
11093 assert_eq!(broadcasted_txs.len(), 1);
11094 assert!(broadcasted_txs[0].txid() != tx.txid());
11095 assert_eq!(broadcasted_txs[0].input.len(), 1);
11096 assert_eq!(broadcasted_txs[0].input[0].previous_output.txid, tx.txid());
11099 // All channels in the batch should close immediately.
11100 check_closed_events(&nodes[0], &[
11101 ExpectedCloseEvent {
11102 channel_id: Some(channel_id_1),
11103 discard_funding: true,
11104 channel_funding_txo: Some(funding_txo_1),
11105 user_channel_id: Some(42),
11106 ..Default::default()
11108 ExpectedCloseEvent {
11109 channel_id: Some(channel_id_2),
11110 discard_funding: true,
11111 channel_funding_txo: Some(funding_txo_2),
11112 user_channel_id: Some(43),
11113 ..Default::default()
11117 // Ensure the channels don't exist anymore.
11118 assert!(nodes[0].node.list_channels().is_empty());
11121 fn do_test_funding_and_commitment_tx_confirm_same_block(confirm_remote_commitment: bool) {
11122 // Tests that a node will forget the channel (when it only requires 1 confirmation) if the
11123 // funding and commitment transaction confirm in the same block.
11124 let chanmon_cfgs = create_chanmon_cfgs(2);
11125 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11126 let mut min_depth_1_block_cfg = test_default_channel_config();
11127 min_depth_1_block_cfg.channel_handshake_config.minimum_depth = 1;
11128 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(min_depth_1_block_cfg), Some(min_depth_1_block_cfg)]);
11129 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11131 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
11132 let chan_id = ChannelId::v1_from_funding_outpoint(chain::transaction::OutPoint { txid: funding_tx.txid(), index: 0 });
11134 assert_eq!(nodes[0].node.list_channels().len(), 1);
11135 assert_eq!(nodes[1].node.list_channels().len(), 1);
11137 let (closing_node, other_node) = if confirm_remote_commitment {
11138 (&nodes[1], &nodes[0])
11140 (&nodes[0], &nodes[1])
11142 let error_message = "Channel force-closed";
11143 closing_node.node.force_close_broadcasting_latest_txn(&chan_id, &other_node.node.get_our_node_id(), error_message.to_string()).unwrap();
11144 let mut msg_events = closing_node.node.get_and_clear_pending_msg_events();
11145 assert_eq!(msg_events.len(), 1);
11146 match msg_events.pop().unwrap() {
11147 MessageSendEvent::HandleError { action: msgs::ErrorAction::SendErrorMessage { .. }, .. } => {},
11148 _ => panic!("Unexpected event"),
11150 check_added_monitors(closing_node, 1);
11151 check_closed_event(closing_node, 1, ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(true) }, false, &[other_node.node.get_our_node_id()], 1_000_000);
11153 let commitment_tx = {
11154 let mut txn = closing_node.tx_broadcaster.txn_broadcast();
11155 assert_eq!(txn.len(), 1);
11156 let commitment_tx = txn.pop().unwrap();
11157 check_spends!(commitment_tx, funding_tx);
11161 mine_transactions(&nodes[0], &[&funding_tx, &commitment_tx]);
11162 mine_transactions(&nodes[1], &[&funding_tx, &commitment_tx]);
11164 check_closed_broadcast(other_node, 1, true);
11165 check_added_monitors(other_node, 1);
11166 check_closed_event(other_node, 1, ClosureReason::CommitmentTxConfirmed, false, &[closing_node.node.get_our_node_id()], 1_000_000);
11168 assert!(nodes[0].node.list_channels().is_empty());
11169 assert!(nodes[1].node.list_channels().is_empty());
11173 fn test_funding_and_commitment_tx_confirm_same_block() {
11174 do_test_funding_and_commitment_tx_confirm_same_block(false);
11175 do_test_funding_and_commitment_tx_confirm_same_block(true);
11179 fn test_accept_inbound_channel_errors_queued() {
11180 // For manually accepted inbound channels, tests that a close error is correctly handled
11181 // and the channel fails for the initiator.
11182 let mut config0 = test_default_channel_config();
11183 let mut config1 = config0.clone();
11184 config1.channel_handshake_limits.their_to_self_delay = 1000;
11185 config1.manually_accept_inbound_channels = true;
11186 config0.channel_handshake_config.our_to_self_delay = 2000;
11188 let chanmon_cfgs = create_chanmon_cfgs(2);
11189 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
11190 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config0), Some(config1)]);
11191 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
11193 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
11194 let open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
11196 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
11197 let events = nodes[1].node.get_and_clear_pending_events();
11199 Event::OpenChannelRequest { temporary_channel_id, .. } => {
11200 match nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23) {
11201 Err(APIError::ChannelUnavailable { err: _ }) => (),
11205 _ => panic!("Unexpected event"),
11207 assert_eq!(get_err_msg(&nodes[1], &nodes[0].node.get_our_node_id()).channel_id,
11208 open_channel_msg.common_fields.temporary_channel_id);