1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
15 use crate::chain::{ChannelMonitorUpdateStatus, Confirm, Listen, Watch};
16 use crate::chain::chaininterface::LowerBoundedFeeEstimator;
17 use crate::chain::channelmonitor;
18 use crate::chain::channelmonitor::{CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
19 use crate::chain::transaction::OutPoint;
20 use crate::sign::{ChannelSigner, EcdsaChannelSigner, EntropySource, SignerProvider};
21 use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentPurpose, ClosureReason, HTLCDestination, PaymentFailureReason};
22 use crate::ln::{ChannelId, PaymentPreimage, PaymentSecret, PaymentHash};
23 use crate::ln::channel::{commitment_tx_base_weight, COMMITMENT_TX_WEIGHT_PER_HTLC, CONCURRENT_INBOUND_HTLC_FEE_BUFFER, FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE, MIN_AFFORDABLE_HTLC_COUNT, get_holder_selected_channel_reserve_satoshis, OutboundV1Channel, InboundV1Channel};
24 use crate::ln::channelmanager::{self, PaymentId, RAACommitmentOrder, PaymentSendFailure, RecipientOnionFields, BREAKDOWN_TIMEOUT, ENABLE_GOSSIP_TICKS, DISABLE_GOSSIP_TICKS, MIN_CLTV_EXPIRY_DELTA};
25 use crate::ln::channel::{DISCONNECT_PEER_AWAITING_RESPONSE_TICKS, ChannelError};
26 use crate::ln::{chan_utils, onion_utils};
27 use crate::ln::chan_utils::{OFFERED_HTLC_SCRIPT_WEIGHT, htlc_success_tx_weight, htlc_timeout_tx_weight, HTLCOutputInCommitment};
28 use crate::routing::gossip::{NetworkGraph, NetworkUpdate};
29 use crate::routing::router::{Path, PaymentParameters, Route, RouteHop, get_route, RouteParameters};
30 use crate::ln::features::{ChannelFeatures, ChannelTypeFeatures, NodeFeatures};
32 use crate::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction};
33 use crate::util::test_channel_signer::TestChannelSigner;
34 use crate::util::test_utils::{self, WatchtowerPersister};
35 use crate::util::errors::APIError;
36 use crate::util::ser::{Writeable, ReadableArgs};
37 use crate::util::string::UntrustedString;
38 use crate::util::config::{UserConfig, MaxDustHTLCExposure};
40 use bitcoin::hash_types::BlockHash;
41 use bitcoin::blockdata::script::{Builder, Script};
42 use bitcoin::blockdata::opcodes;
43 use bitcoin::blockdata::constants::genesis_block;
44 use bitcoin::network::constants::Network;
45 use bitcoin::{PackedLockTime, Sequence, Transaction, TxIn, TxOut, Witness};
46 use bitcoin::OutPoint as BitcoinOutPoint;
48 use bitcoin::secp256k1::Secp256k1;
49 use bitcoin::secp256k1::{PublicKey,SecretKey};
54 use crate::prelude::*;
55 use alloc::collections::BTreeSet;
56 use core::default::Default;
57 use core::iter::repeat;
58 use bitcoin::hashes::Hash;
59 use crate::sync::{Arc, Mutex, RwLock};
61 use crate::ln::functional_test_utils::*;
62 use crate::ln::chan_utils::CommitmentTransaction;
64 use super::channel::UNFUNDED_CHANNEL_AGE_LIMIT_TICKS;
67 fn test_insane_channel_opens() {
68 // Stand up a network of 2 nodes
69 use crate::ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
70 let mut cfg = UserConfig::default();
71 cfg.channel_handshake_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
72 let chanmon_cfgs = create_chanmon_cfgs(2);
73 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
74 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
75 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
77 // Instantiate channel parameters where we push the maximum msats given our
79 let channel_value_sat = 31337; // same as funding satoshis
80 let channel_reserve_satoshis = get_holder_selected_channel_reserve_satoshis(channel_value_sat, &cfg);
81 let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
83 // Have node0 initiate a channel to node1 with aforementioned parameters
84 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
86 // Extract the channel open message from node0 to node1
87 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
89 // Test helper that asserts we get the correct error string given a mutator
90 // that supposedly makes the channel open message insane
91 let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
92 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &message_mutator(open_channel_message.clone()));
93 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
94 assert_eq!(msg_events.len(), 1);
95 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
96 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
98 &ErrorAction::SendErrorMessage { .. } => {
99 nodes[1].logger.assert_log_regex("lightning::ln::channelmanager", expected_regex, 1);
101 _ => panic!("unexpected event!"),
103 } else { assert!(false); }
106 use crate::ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
108 // Test all mutations that would make the channel open message insane
109 insane_open_helper(format!("Per our config, funding must be at most {}. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1, TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2; msg });
110 insane_open_helper(format!("Funding must be smaller than the total bitcoin supply. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS; msg });
112 insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
114 insane_open_helper(r"push_msat \d+ was larger than channel amount minus reserve \(\d+\)", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
116 insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
118 insane_open_helper(r"Minimum htlc value \(\d+\) was larger than full channel value \(\d+\)", |mut msg| { msg.htlc_minimum_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000; msg });
120 insane_open_helper("They wanted our payments to be delayed by a needlessly long period", |mut msg| { msg.to_self_delay = MAX_LOCAL_BREAKDOWN_TIMEOUT + 1; msg });
122 insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
124 insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
128 fn test_funding_exceeds_no_wumbo_limit() {
129 // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
131 use crate::ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
132 let chanmon_cfgs = create_chanmon_cfgs(2);
133 let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
134 *node_cfgs[1].override_init_features.borrow_mut() = Some(channelmanager::provided_init_features(&test_default_channel_config()).clear_wumbo());
135 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
136 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
138 match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None) {
139 Err(APIError::APIMisuseError { err }) => {
140 assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
146 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
147 // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
148 // but only for them. Because some LSPs do it with some level of trust of the clients (for a
149 // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
150 // in normal testing, we test it explicitly here.
151 let chanmon_cfgs = create_chanmon_cfgs(2);
152 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
153 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
154 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
155 let default_config = UserConfig::default();
157 // Have node0 initiate a channel to node1 with aforementioned parameters
158 let mut push_amt = 100_000_000;
159 let feerate_per_kw = 253;
160 let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
161 push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(&channel_type_features) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
162 push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
164 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, if send_from_initiator { 0 } else { push_amt }, 42, None).unwrap();
165 let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
166 if !send_from_initiator {
167 open_channel_message.channel_reserve_satoshis = 0;
168 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
170 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
172 // Extract the channel accept message from node1 to node0
173 let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
174 if send_from_initiator {
175 accept_channel_message.channel_reserve_satoshis = 0;
176 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
178 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
180 let sender_node = if send_from_initiator { &nodes[1] } else { &nodes[0] };
181 let counterparty_node = if send_from_initiator { &nodes[0] } else { &nodes[1] };
182 let mut sender_node_per_peer_lock;
183 let mut sender_node_peer_state_lock;
184 if send_from_initiator {
185 let chan = get_inbound_v1_channel_ref!(sender_node, counterparty_node, sender_node_per_peer_lock, sender_node_peer_state_lock, temp_channel_id);
186 chan.context.holder_selected_channel_reserve_satoshis = 0;
187 chan.context.holder_max_htlc_value_in_flight_msat = 100_000_000;
189 let chan = get_outbound_v1_channel_ref!(sender_node, counterparty_node, sender_node_per_peer_lock, sender_node_peer_state_lock, temp_channel_id);
190 chan.context.holder_selected_channel_reserve_satoshis = 0;
191 chan.context.holder_max_htlc_value_in_flight_msat = 100_000_000;
195 let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
196 let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
197 create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
199 // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
200 // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
201 if send_from_initiator {
202 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
203 // Note that for outbound channels we have to consider the commitment tx fee and the
204 // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
205 // well as an additional HTLC.
206 - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, &channel_type_features));
208 send_payment(&nodes[1], &[&nodes[0]], push_amt);
213 fn test_counterparty_no_reserve() {
214 do_test_counterparty_no_reserve(true);
215 do_test_counterparty_no_reserve(false);
219 fn test_async_inbound_update_fee() {
220 let chanmon_cfgs = create_chanmon_cfgs(2);
221 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
222 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
223 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
224 create_announced_chan_between_nodes(&nodes, 0, 1);
227 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
231 // send (1) commitment_signed -.
232 // <- update_add_htlc/commitment_signed
233 // send (2) RAA (awaiting remote revoke) -.
234 // (1) commitment_signed is delivered ->
235 // .- send (3) RAA (awaiting remote revoke)
236 // (2) RAA is delivered ->
237 // .- send (4) commitment_signed
238 // <- (3) RAA is delivered
239 // send (5) commitment_signed -.
240 // <- (4) commitment_signed is delivered
242 // (5) commitment_signed is delivered ->
244 // (6) RAA is delivered ->
246 // First nodes[0] generates an update_fee
248 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
251 nodes[0].node.timer_tick_occurred();
252 check_added_monitors!(nodes[0], 1);
254 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
255 assert_eq!(events_0.len(), 1);
256 let (update_msg, commitment_signed) = match events_0[0] { // (1)
257 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
258 (update_fee.as_ref(), commitment_signed)
260 _ => panic!("Unexpected event"),
263 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
265 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
266 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
267 nodes[1].node.send_payment_with_route(&route, our_payment_hash,
268 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
269 check_added_monitors!(nodes[1], 1);
271 let payment_event = {
272 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
273 assert_eq!(events_1.len(), 1);
274 SendEvent::from_event(events_1.remove(0))
276 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
277 assert_eq!(payment_event.msgs.len(), 1);
279 // ...now when the messages get delivered everyone should be happy
280 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
281 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
282 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
283 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
284 check_added_monitors!(nodes[0], 1);
286 // deliver(1), generate (3):
287 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
288 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
289 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
290 check_added_monitors!(nodes[1], 1);
292 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
293 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
294 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
295 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
296 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
297 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
298 assert!(bs_update.update_fee.is_none()); // (4)
299 check_added_monitors!(nodes[1], 1);
301 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
302 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
303 assert!(as_update.update_add_htlcs.is_empty()); // (5)
304 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
305 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
306 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
307 assert!(as_update.update_fee.is_none()); // (5)
308 check_added_monitors!(nodes[0], 1);
310 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
311 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
312 // only (6) so get_event_msg's assert(len == 1) passes
313 check_added_monitors!(nodes[0], 1);
315 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
316 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
317 check_added_monitors!(nodes[1], 1);
319 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
320 check_added_monitors!(nodes[0], 1);
322 let events_2 = nodes[0].node.get_and_clear_pending_events();
323 assert_eq!(events_2.len(), 1);
325 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
326 _ => panic!("Unexpected event"),
329 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
330 check_added_monitors!(nodes[1], 1);
334 fn test_update_fee_unordered_raa() {
335 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
336 // crash in an earlier version of the update_fee patch)
337 let chanmon_cfgs = create_chanmon_cfgs(2);
338 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
339 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
340 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
341 create_announced_chan_between_nodes(&nodes, 0, 1);
344 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
346 // First nodes[0] generates an update_fee
348 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
351 nodes[0].node.timer_tick_occurred();
352 check_added_monitors!(nodes[0], 1);
354 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
355 assert_eq!(events_0.len(), 1);
356 let update_msg = match events_0[0] { // (1)
357 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
360 _ => panic!("Unexpected event"),
363 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
365 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
366 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
367 nodes[1].node.send_payment_with_route(&route, our_payment_hash,
368 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
369 check_added_monitors!(nodes[1], 1);
371 let payment_event = {
372 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
373 assert_eq!(events_1.len(), 1);
374 SendEvent::from_event(events_1.remove(0))
376 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
377 assert_eq!(payment_event.msgs.len(), 1);
379 // ...now when the messages get delivered everyone should be happy
380 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
381 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
382 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
383 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
384 check_added_monitors!(nodes[0], 1);
386 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
387 check_added_monitors!(nodes[1], 1);
389 // We can't continue, sadly, because our (1) now has a bogus signature
393 fn test_multi_flight_update_fee() {
394 let chanmon_cfgs = create_chanmon_cfgs(2);
395 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
396 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
397 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
398 create_announced_chan_between_nodes(&nodes, 0, 1);
401 // update_fee/commitment_signed ->
402 // .- send (1) RAA and (2) commitment_signed
403 // update_fee (never committed) ->
405 // We have to manually generate the above update_fee, it is allowed by the protocol but we
406 // don't track which updates correspond to which revoke_and_ack responses so we're in
407 // AwaitingRAA mode and will not generate the update_fee yet.
408 // <- (1) RAA delivered
409 // (3) is generated and send (4) CS -.
410 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
411 // know the per_commitment_point to use for it.
412 // <- (2) commitment_signed delivered
414 // B should send no response here
415 // (4) commitment_signed delivered ->
416 // <- RAA/commitment_signed delivered
419 // First nodes[0] generates an update_fee
422 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
423 initial_feerate = *feerate_lock;
424 *feerate_lock = initial_feerate + 20;
426 nodes[0].node.timer_tick_occurred();
427 check_added_monitors!(nodes[0], 1);
429 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
430 assert_eq!(events_0.len(), 1);
431 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
432 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
433 (update_fee.as_ref().unwrap(), commitment_signed)
435 _ => panic!("Unexpected event"),
438 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
439 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
440 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
441 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
442 check_added_monitors!(nodes[1], 1);
444 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
447 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
448 *feerate_lock = initial_feerate + 40;
450 nodes[0].node.timer_tick_occurred();
451 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
452 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
454 // Create the (3) update_fee message that nodes[0] will generate before it does...
455 let mut update_msg_2 = msgs::UpdateFee {
456 channel_id: update_msg_1.channel_id.clone(),
457 feerate_per_kw: (initial_feerate + 30) as u32,
460 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
462 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
464 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
466 // Deliver (1), generating (3) and (4)
467 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
468 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
469 check_added_monitors!(nodes[0], 1);
470 assert!(as_second_update.update_add_htlcs.is_empty());
471 assert!(as_second_update.update_fulfill_htlcs.is_empty());
472 assert!(as_second_update.update_fail_htlcs.is_empty());
473 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
474 // Check that the update_fee newly generated matches what we delivered:
475 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
476 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
478 // Deliver (2) commitment_signed
479 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
480 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
481 check_added_monitors!(nodes[0], 1);
482 // No commitment_signed so get_event_msg's assert(len == 1) passes
484 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
485 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
486 check_added_monitors!(nodes[1], 1);
489 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
490 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
491 check_added_monitors!(nodes[1], 1);
493 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
494 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
495 check_added_monitors!(nodes[0], 1);
497 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
498 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
499 // No commitment_signed so get_event_msg's assert(len == 1) passes
500 check_added_monitors!(nodes[0], 1);
502 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
503 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
504 check_added_monitors!(nodes[1], 1);
507 fn do_test_sanity_on_in_flight_opens(steps: u8) {
508 // Previously, we had issues deserializing channels when we hadn't connected the first block
509 // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
510 // serialization round-trips and simply do steps towards opening a channel and then drop the
513 let chanmon_cfgs = create_chanmon_cfgs(2);
514 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
515 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
516 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
518 if steps & 0b1000_0000 != 0{
519 let block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
520 connect_block(&nodes[0], &block);
521 connect_block(&nodes[1], &block);
524 if steps & 0x0f == 0 { return; }
525 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
526 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
528 if steps & 0x0f == 1 { return; }
529 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
530 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
532 if steps & 0x0f == 2 { return; }
533 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
535 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
537 if steps & 0x0f == 3 { return; }
538 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
539 check_added_monitors!(nodes[0], 0);
540 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
542 if steps & 0x0f == 4 { return; }
543 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
545 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
546 assert_eq!(added_monitors.len(), 1);
547 assert_eq!(added_monitors[0].0, funding_output);
548 added_monitors.clear();
550 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
552 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
554 if steps & 0x0f == 5 { return; }
555 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
557 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
558 assert_eq!(added_monitors.len(), 1);
559 assert_eq!(added_monitors[0].0, funding_output);
560 added_monitors.clear();
563 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
564 let events_4 = nodes[0].node.get_and_clear_pending_events();
565 assert_eq!(events_4.len(), 0);
567 if steps & 0x0f == 6 { return; }
568 create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
570 if steps & 0x0f == 7 { return; }
571 confirm_transaction_at(&nodes[0], &tx, 2);
572 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
573 create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
574 expect_channel_ready_event(&nodes[0], &nodes[1].node.get_our_node_id());
578 fn test_sanity_on_in_flight_opens() {
579 do_test_sanity_on_in_flight_opens(0);
580 do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
581 do_test_sanity_on_in_flight_opens(1);
582 do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
583 do_test_sanity_on_in_flight_opens(2);
584 do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
585 do_test_sanity_on_in_flight_opens(3);
586 do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
587 do_test_sanity_on_in_flight_opens(4);
588 do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
589 do_test_sanity_on_in_flight_opens(5);
590 do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
591 do_test_sanity_on_in_flight_opens(6);
592 do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
593 do_test_sanity_on_in_flight_opens(7);
594 do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
595 do_test_sanity_on_in_flight_opens(8);
596 do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
600 fn test_update_fee_vanilla() {
601 let chanmon_cfgs = create_chanmon_cfgs(2);
602 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
603 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
604 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
605 create_announced_chan_between_nodes(&nodes, 0, 1);
608 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
611 nodes[0].node.timer_tick_occurred();
612 check_added_monitors!(nodes[0], 1);
614 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
615 assert_eq!(events_0.len(), 1);
616 let (update_msg, commitment_signed) = match events_0[0] {
617 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 } } => {
618 (update_fee.as_ref(), commitment_signed)
620 _ => panic!("Unexpected event"),
622 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
624 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
625 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
626 check_added_monitors!(nodes[1], 1);
628 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
629 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
630 check_added_monitors!(nodes[0], 1);
632 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
633 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
634 // No commitment_signed so get_event_msg's assert(len == 1) passes
635 check_added_monitors!(nodes[0], 1);
637 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
638 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
639 check_added_monitors!(nodes[1], 1);
643 fn test_update_fee_that_funder_cannot_afford() {
644 let chanmon_cfgs = create_chanmon_cfgs(2);
645 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
646 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
647 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
648 let channel_value = 5000;
650 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000);
651 let channel_id = chan.2;
652 let secp_ctx = Secp256k1::new();
653 let default_config = UserConfig::default();
654 let bs_channel_reserve_sats = get_holder_selected_channel_reserve_satoshis(channel_value, &default_config);
656 let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
658 // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
659 // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
660 // calculate two different feerates here - the expected local limit as well as the expected
662 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;
663 let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(&channel_type_features)) as u32;
665 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
666 *feerate_lock = feerate;
668 nodes[0].node.timer_tick_occurred();
669 check_added_monitors!(nodes[0], 1);
670 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
672 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
674 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
676 // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
678 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
680 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
681 assert_eq!(commitment_tx.output.len(), 2);
682 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, &channel_type_features) / 1000;
683 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
684 actual_fee = channel_value - actual_fee;
685 assert_eq!(total_fee, actual_fee);
689 // Increment the feerate by a small constant, accounting for rounding errors
690 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
693 nodes[0].node.timer_tick_occurred();
694 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
695 check_added_monitors!(nodes[0], 0);
697 const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
699 // Get the TestChannelSigner for each channel, which will be used to (1) get the keys
700 // needed to sign the new commitment tx and (2) sign the new commitment tx.
701 let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
702 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
703 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
704 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
705 let chan_signer = local_chan.get_signer();
706 let pubkeys = chan_signer.as_ref().pubkeys();
707 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
708 pubkeys.funding_pubkey)
710 let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
711 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
712 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
713 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
714 let chan_signer = remote_chan.get_signer();
715 let pubkeys = chan_signer.as_ref().pubkeys();
716 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
717 chan_signer.as_ref().get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
718 pubkeys.funding_pubkey)
721 // Assemble the set of keys we can use for signatures for our commitment_signed message.
722 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
723 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
726 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
727 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
728 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
729 let local_chan_signer = local_chan.get_signer();
730 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
731 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
732 INITIAL_COMMITMENT_NUMBER - 1,
734 channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, &channel_type_features) / 1000,
735 local_funding, remote_funding,
736 commit_tx_keys.clone(),
737 non_buffer_feerate + 4,
739 &local_chan.context.channel_transaction_parameters.as_counterparty_broadcastable()
741 local_chan_signer.as_ecdsa().unwrap().sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
744 let commit_signed_msg = msgs::CommitmentSigned {
747 htlc_signatures: res.1,
749 partial_signature_with_nonce: None,
752 let update_fee = msgs::UpdateFee {
754 feerate_per_kw: non_buffer_feerate + 4,
757 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
759 //While producing the commitment_signed response after handling a received update_fee request the
760 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
761 //Should produce and error.
762 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
763 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
764 check_added_monitors!(nodes[1], 1);
765 check_closed_broadcast!(nodes[1], true);
766 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") },
767 [nodes[0].node.get_our_node_id()], channel_value);
771 fn test_update_fee_with_fundee_update_add_htlc() {
772 let chanmon_cfgs = create_chanmon_cfgs(2);
773 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
774 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
775 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
776 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
779 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
782 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
785 nodes[0].node.timer_tick_occurred();
786 check_added_monitors!(nodes[0], 1);
788 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
789 assert_eq!(events_0.len(), 1);
790 let (update_msg, commitment_signed) = match events_0[0] {
791 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 } } => {
792 (update_fee.as_ref(), commitment_signed)
794 _ => panic!("Unexpected event"),
796 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
797 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
798 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
799 check_added_monitors!(nodes[1], 1);
801 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
803 // nothing happens since node[1] is in AwaitingRemoteRevoke
804 nodes[1].node.send_payment_with_route(&route, our_payment_hash,
805 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
807 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
808 assert_eq!(added_monitors.len(), 0);
809 added_monitors.clear();
811 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
812 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
813 // node[1] has nothing to do
815 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
816 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
817 check_added_monitors!(nodes[0], 1);
819 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
820 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
821 // No commitment_signed so get_event_msg's assert(len == 1) passes
822 check_added_monitors!(nodes[0], 1);
823 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
824 check_added_monitors!(nodes[1], 1);
825 // AwaitingRemoteRevoke ends here
827 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
828 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
829 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
830 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
831 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
832 assert_eq!(commitment_update.update_fee.is_none(), true);
834 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
835 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
836 check_added_monitors!(nodes[0], 1);
837 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
839 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
840 check_added_monitors!(nodes[1], 1);
841 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
843 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
844 check_added_monitors!(nodes[1], 1);
845 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
846 // No commitment_signed so get_event_msg's assert(len == 1) passes
848 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
849 check_added_monitors!(nodes[0], 1);
850 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
852 expect_pending_htlcs_forwardable!(nodes[0]);
854 let events = nodes[0].node.get_and_clear_pending_events();
855 assert_eq!(events.len(), 1);
857 Event::PaymentClaimable { .. } => { },
858 _ => panic!("Unexpected event"),
861 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
863 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
864 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
865 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
866 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
867 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
871 fn test_update_fee() {
872 let chanmon_cfgs = create_chanmon_cfgs(2);
873 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
874 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
875 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
876 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
877 let channel_id = chan.2;
880 // (1) update_fee/commitment_signed ->
881 // <- (2) revoke_and_ack
882 // .- send (3) commitment_signed
883 // (4) update_fee/commitment_signed ->
884 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
885 // <- (3) commitment_signed delivered
886 // send (6) revoke_and_ack -.
887 // <- (5) deliver revoke_and_ack
888 // (6) deliver revoke_and_ack ->
889 // .- send (7) commitment_signed in response to (4)
890 // <- (7) deliver commitment_signed
893 // Create and deliver (1)...
896 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
897 feerate = *feerate_lock;
898 *feerate_lock = feerate + 20;
900 nodes[0].node.timer_tick_occurred();
901 check_added_monitors!(nodes[0], 1);
903 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
904 assert_eq!(events_0.len(), 1);
905 let (update_msg, commitment_signed) = match events_0[0] {
906 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 } } => {
907 (update_fee.as_ref(), commitment_signed)
909 _ => panic!("Unexpected event"),
911 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
913 // Generate (2) and (3):
914 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
915 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
916 check_added_monitors!(nodes[1], 1);
919 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
920 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
921 check_added_monitors!(nodes[0], 1);
923 // Create and deliver (4)...
925 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
926 *feerate_lock = feerate + 30;
928 nodes[0].node.timer_tick_occurred();
929 check_added_monitors!(nodes[0], 1);
930 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
931 assert_eq!(events_0.len(), 1);
932 let (update_msg, commitment_signed) = match events_0[0] {
933 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 } } => {
934 (update_fee.as_ref(), commitment_signed)
936 _ => panic!("Unexpected event"),
939 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
940 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
941 check_added_monitors!(nodes[1], 1);
943 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
944 // No commitment_signed so get_event_msg's assert(len == 1) passes
946 // Handle (3), creating (6):
947 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
948 check_added_monitors!(nodes[0], 1);
949 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
950 // No commitment_signed so get_event_msg's assert(len == 1) passes
953 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
954 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
955 check_added_monitors!(nodes[0], 1);
957 // Deliver (6), creating (7):
958 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
959 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
960 assert!(commitment_update.update_add_htlcs.is_empty());
961 assert!(commitment_update.update_fulfill_htlcs.is_empty());
962 assert!(commitment_update.update_fail_htlcs.is_empty());
963 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
964 assert!(commitment_update.update_fee.is_none());
965 check_added_monitors!(nodes[1], 1);
968 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
969 check_added_monitors!(nodes[0], 1);
970 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
971 // No commitment_signed so get_event_msg's assert(len == 1) passes
973 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
974 check_added_monitors!(nodes[1], 1);
975 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
977 assert_eq!(get_feerate!(nodes[0], nodes[1], channel_id), feerate + 30);
978 assert_eq!(get_feerate!(nodes[1], nodes[0], channel_id), feerate + 30);
979 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
980 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
981 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
985 fn fake_network_test() {
986 // Simple test which builds a network of ChannelManagers, connects them to each other, and
987 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
988 let chanmon_cfgs = create_chanmon_cfgs(4);
989 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
990 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
991 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
993 // Create some initial channels
994 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
995 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
996 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
998 // Rebalance the network a bit by relaying one payment through all the channels...
999 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1000 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1001 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1002 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1004 // Send some more payments
1005 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
1006 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
1007 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
1009 // Test failure packets
1010 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1011 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1013 // Add a new channel that skips 3
1014 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
1016 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
1017 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
1018 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1019 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1020 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1021 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1022 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1024 // Do some rebalance loop payments, simultaneously
1025 let mut hops = Vec::with_capacity(3);
1026 hops.push(RouteHop {
1027 pubkey: nodes[2].node.get_our_node_id(),
1028 node_features: NodeFeatures::empty(),
1029 short_channel_id: chan_2.0.contents.short_channel_id,
1030 channel_features: ChannelFeatures::empty(),
1032 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1034 hops.push(RouteHop {
1035 pubkey: nodes[3].node.get_our_node_id(),
1036 node_features: NodeFeatures::empty(),
1037 short_channel_id: chan_3.0.contents.short_channel_id,
1038 channel_features: ChannelFeatures::empty(),
1040 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1042 hops.push(RouteHop {
1043 pubkey: nodes[1].node.get_our_node_id(),
1044 node_features: nodes[1].node.node_features(),
1045 short_channel_id: chan_4.0.contents.short_channel_id,
1046 channel_features: nodes[1].node.channel_features(),
1048 cltv_expiry_delta: TEST_FINAL_CLTV,
1050 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;
1051 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;
1052 let payment_preimage_1 = send_along_route(&nodes[1],
1053 Route { paths: vec![Path { hops, blinded_tail: None }], route_params: None },
1054 &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1056 let mut hops = Vec::with_capacity(3);
1057 hops.push(RouteHop {
1058 pubkey: nodes[3].node.get_our_node_id(),
1059 node_features: NodeFeatures::empty(),
1060 short_channel_id: chan_4.0.contents.short_channel_id,
1061 channel_features: ChannelFeatures::empty(),
1063 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1065 hops.push(RouteHop {
1066 pubkey: nodes[2].node.get_our_node_id(),
1067 node_features: NodeFeatures::empty(),
1068 short_channel_id: chan_3.0.contents.short_channel_id,
1069 channel_features: ChannelFeatures::empty(),
1071 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1073 hops.push(RouteHop {
1074 pubkey: nodes[1].node.get_our_node_id(),
1075 node_features: nodes[1].node.node_features(),
1076 short_channel_id: chan_2.0.contents.short_channel_id,
1077 channel_features: nodes[1].node.channel_features(),
1079 cltv_expiry_delta: TEST_FINAL_CLTV,
1081 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;
1082 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;
1083 let payment_hash_2 = send_along_route(&nodes[1],
1084 Route { paths: vec![Path { hops, blinded_tail: None }], route_params: None },
1085 &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1087 // Claim the rebalances...
1088 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1089 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1091 // Close down the channels...
1092 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1093 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1094 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
1095 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1096 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[2].node.get_our_node_id()], 100000);
1097 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1098 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1099 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure, [nodes[3].node.get_our_node_id()], 100000);
1100 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure, [nodes[2].node.get_our_node_id()], 100000);
1101 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1102 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[3].node.get_our_node_id()], 100000);
1103 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1107 fn holding_cell_htlc_counting() {
1108 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1109 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1110 // commitment dance rounds.
1111 let chanmon_cfgs = create_chanmon_cfgs(3);
1112 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1113 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1114 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1115 create_announced_chan_between_nodes(&nodes, 0, 1);
1116 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1118 // Fetch a route in advance as we will be unable to once we're unable to send.
1119 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1121 let mut payments = Vec::new();
1123 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1124 nodes[1].node.send_payment_with_route(&route, payment_hash,
1125 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1126 payments.push((payment_preimage, payment_hash));
1128 check_added_monitors!(nodes[1], 1);
1130 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1131 assert_eq!(events.len(), 1);
1132 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1133 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1135 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1136 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1139 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, payment_hash_1,
1140 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)
1141 ), true, APIError::ChannelUnavailable { .. }, {});
1142 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1145 // This should also be true if we try to forward a payment.
1146 let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1148 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1149 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1150 check_added_monitors!(nodes[0], 1);
1153 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1154 assert_eq!(events.len(), 1);
1155 let payment_event = SendEvent::from_event(events.pop().unwrap());
1156 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1158 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1159 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1160 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1161 // fails), the second will process the resulting failure and fail the HTLC backward.
1162 expect_pending_htlcs_forwardable!(nodes[1]);
1163 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 }]);
1164 check_added_monitors!(nodes[1], 1);
1166 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1167 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1168 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1170 expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1172 // Now forward all the pending HTLCs and claim them back
1173 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1174 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1175 check_added_monitors!(nodes[2], 1);
1177 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1178 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1179 check_added_monitors!(nodes[1], 1);
1180 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1182 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1183 check_added_monitors!(nodes[1], 1);
1184 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1186 for ref update in as_updates.update_add_htlcs.iter() {
1187 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1189 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1190 check_added_monitors!(nodes[2], 1);
1191 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1192 check_added_monitors!(nodes[2], 1);
1193 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1195 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1196 check_added_monitors!(nodes[1], 1);
1197 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1198 check_added_monitors!(nodes[1], 1);
1199 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1201 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1202 check_added_monitors!(nodes[2], 1);
1204 expect_pending_htlcs_forwardable!(nodes[2]);
1206 let events = nodes[2].node.get_and_clear_pending_events();
1207 assert_eq!(events.len(), payments.len());
1208 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1210 &Event::PaymentClaimable { ref payment_hash, .. } => {
1211 assert_eq!(*payment_hash, *hash);
1213 _ => panic!("Unexpected event"),
1217 for (preimage, _) in payments.drain(..) {
1218 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1221 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1225 fn duplicate_htlc_test() {
1226 // Test that we accept duplicate payment_hash HTLCs across the network and that
1227 // claiming/failing them are all separate and don't affect each other
1228 let chanmon_cfgs = create_chanmon_cfgs(6);
1229 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1230 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1231 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1233 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1234 create_announced_chan_between_nodes(&nodes, 0, 3);
1235 create_announced_chan_between_nodes(&nodes, 1, 3);
1236 create_announced_chan_between_nodes(&nodes, 2, 3);
1237 create_announced_chan_between_nodes(&nodes, 3, 4);
1238 create_announced_chan_between_nodes(&nodes, 3, 5);
1240 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1242 *nodes[0].network_payment_count.borrow_mut() -= 1;
1243 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1245 *nodes[0].network_payment_count.borrow_mut() -= 1;
1246 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1248 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1249 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1250 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1254 fn test_duplicate_htlc_different_direction_onchain() {
1255 // Test that ChannelMonitor doesn't generate 2 preimage txn
1256 // when we have 2 HTLCs with same preimage that go across a node
1257 // in opposite directions, even with the same payment secret.
1258 let chanmon_cfgs = create_chanmon_cfgs(2);
1259 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1260 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1261 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1263 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1266 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1268 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1270 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1271 let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
1272 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1274 // Provide preimage to node 0 by claiming payment
1275 nodes[0].node.claim_funds(payment_preimage);
1276 expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1277 check_added_monitors!(nodes[0], 1);
1279 // Broadcast node 1 commitment txn
1280 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1282 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1283 let mut has_both_htlcs = 0; // check htlcs match ones committed
1284 for outp in remote_txn[0].output.iter() {
1285 if outp.value == 800_000 / 1000 {
1286 has_both_htlcs += 1;
1287 } else if outp.value == 900_000 / 1000 {
1288 has_both_htlcs += 1;
1291 assert_eq!(has_both_htlcs, 2);
1293 mine_transaction(&nodes[0], &remote_txn[0]);
1294 check_added_monitors!(nodes[0], 1);
1295 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
1296 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
1298 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1299 assert_eq!(claim_txn.len(), 3);
1301 check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1302 check_spends!(claim_txn[1], remote_txn[0]);
1303 check_spends!(claim_txn[2], remote_txn[0]);
1304 let preimage_tx = &claim_txn[0];
1305 let (preimage_bump_tx, timeout_tx) = if claim_txn[1].input[0].previous_output == preimage_tx.input[0].previous_output {
1306 (&claim_txn[1], &claim_txn[2])
1308 (&claim_txn[2], &claim_txn[1])
1311 assert_eq!(preimage_tx.input.len(), 1);
1312 assert_eq!(preimage_bump_tx.input.len(), 1);
1314 assert_eq!(preimage_tx.input.len(), 1);
1315 assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1316 assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1318 assert_eq!(timeout_tx.input.len(), 1);
1319 assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1320 check_spends!(timeout_tx, remote_txn[0]);
1321 assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1323 let events = nodes[0].node.get_and_clear_pending_msg_events();
1324 assert_eq!(events.len(), 3);
1327 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1328 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1329 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1330 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1332 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, .. } } => {
1333 assert!(update_add_htlcs.is_empty());
1334 assert!(update_fail_htlcs.is_empty());
1335 assert_eq!(update_fulfill_htlcs.len(), 1);
1336 assert!(update_fail_malformed_htlcs.is_empty());
1337 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1339 _ => panic!("Unexpected event"),
1345 fn test_basic_channel_reserve() {
1346 let chanmon_cfgs = create_chanmon_cfgs(2);
1347 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1348 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1349 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1350 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1352 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1353 let channel_reserve = chan_stat.channel_reserve_msat;
1355 // The 2* and +1 are for the fee spike reserve.
1356 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));
1357 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1358 let (mut route, our_payment_hash, _, our_payment_secret) =
1359 get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
1360 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1361 let err = nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1362 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1364 PaymentSendFailure::AllFailedResendSafe(ref fails) => {
1365 if let &APIError::ChannelUnavailable { .. } = &fails[0] {}
1366 else { panic!("Unexpected error variant"); }
1368 _ => panic!("Unexpected error variant"),
1370 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1372 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1376 fn test_fee_spike_violation_fails_htlc() {
1377 let chanmon_cfgs = create_chanmon_cfgs(2);
1378 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1379 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1380 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1381 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1383 let (mut route, payment_hash, _, payment_secret) =
1384 get_route_and_payment_hash!(nodes[0], nodes[1], 3460000);
1385 route.paths[0].hops[0].fee_msat += 1;
1386 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1387 let secp_ctx = Secp256k1::new();
1388 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1390 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1392 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1393 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1394 3460001, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1395 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1396 let msg = msgs::UpdateAddHTLC {
1399 amount_msat: htlc_msat,
1400 payment_hash: payment_hash,
1401 cltv_expiry: htlc_cltv,
1402 onion_routing_packet: onion_packet,
1403 skimmed_fee_msat: None,
1406 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1408 // Now manually create the commitment_signed message corresponding to the update_add
1409 // nodes[0] just sent. In the code for construction of this message, "local" refers
1410 // to the sender of the message, and "remote" refers to the receiver.
1412 let feerate_per_kw = get_feerate!(nodes[0], nodes[1], chan.2);
1414 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1416 // Get the TestChannelSigner for each channel, which will be used to (1) get the keys
1417 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1418 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1419 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1420 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1421 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1422 let chan_signer = local_chan.get_signer();
1423 // Make the signer believe we validated another commitment, so we can release the secret
1424 chan_signer.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
1426 let pubkeys = chan_signer.as_ref().pubkeys();
1427 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1428 chan_signer.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1429 chan_signer.as_ref().get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1430 chan_signer.as_ref().pubkeys().funding_pubkey)
1432 let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1433 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
1434 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
1435 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1436 let chan_signer = remote_chan.get_signer();
1437 let pubkeys = chan_signer.as_ref().pubkeys();
1438 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1439 chan_signer.as_ref().get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1440 chan_signer.as_ref().pubkeys().funding_pubkey)
1443 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1444 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1445 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
1447 // Build the remote commitment transaction so we can sign it, and then later use the
1448 // signature for the commitment_signed message.
1449 let local_chan_balance = 1313;
1451 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1453 amount_msat: 3460001,
1454 cltv_expiry: htlc_cltv,
1456 transaction_output_index: Some(1),
1459 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1462 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1463 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1464 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
1465 let local_chan_signer = local_chan.get_signer();
1466 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1470 local_funding, remote_funding,
1471 commit_tx_keys.clone(),
1473 &mut vec![(accepted_htlc_info, ())],
1474 &local_chan.context.channel_transaction_parameters.as_counterparty_broadcastable()
1476 local_chan_signer.as_ecdsa().unwrap().sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1479 let commit_signed_msg = msgs::CommitmentSigned {
1482 htlc_signatures: res.1,
1484 partial_signature_with_nonce: None,
1487 // Send the commitment_signed message to the nodes[1].
1488 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1489 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1491 // Send the RAA to nodes[1].
1492 let raa_msg = msgs::RevokeAndACK {
1494 per_commitment_secret: local_secret,
1495 next_per_commitment_point: next_local_point,
1497 next_local_nonce: None,
1499 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1501 let events = nodes[1].node.get_and_clear_pending_msg_events();
1502 assert_eq!(events.len(), 1);
1503 // Make sure the HTLC failed in the way we expect.
1505 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1506 assert_eq!(update_fail_htlcs.len(), 1);
1507 update_fail_htlcs[0].clone()
1509 _ => panic!("Unexpected event"),
1511 nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1512 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", raa_msg.channel_id), 1);
1514 check_added_monitors!(nodes[1], 2);
1518 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1519 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1520 // Set the fee rate for the channel very high, to the point where the fundee
1521 // sending any above-dust amount would result in a channel reserve violation.
1522 // In this test we check that we would be prevented from sending an HTLC in
1524 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1525 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1526 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1527 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1528 let default_config = UserConfig::default();
1529 let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1531 let mut push_amt = 100_000_000;
1532 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1534 push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1536 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1538 // Fetch a route in advance as we will be unable to once we're unable to send.
1539 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1540 // Sending exactly enough to hit the reserve amount should be accepted
1541 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1542 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1545 // However one more HTLC should be significantly over the reserve amount and fail.
1546 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1547 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1548 ), true, APIError::ChannelUnavailable { .. }, {});
1549 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1553 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1554 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1555 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1556 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1557 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1558 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1559 let default_config = UserConfig::default();
1560 let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1562 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1563 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1564 // transaction fee with 0 HTLCs (183 sats)).
1565 let mut push_amt = 100_000_000;
1566 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1567 push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1568 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1570 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1571 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1572 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1575 let (mut route, payment_hash, _, payment_secret) =
1576 get_route_and_payment_hash!(nodes[1], nodes[0], 1000);
1577 route.paths[0].hops[0].fee_msat = 700_000;
1578 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1579 let secp_ctx = Secp256k1::new();
1580 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1581 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1582 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1583 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1584 700_000, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1585 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1586 let msg = msgs::UpdateAddHTLC {
1588 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1589 amount_msat: htlc_msat,
1590 payment_hash: payment_hash,
1591 cltv_expiry: htlc_cltv,
1592 onion_routing_packet: onion_packet,
1593 skimmed_fee_msat: None,
1596 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1597 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1598 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value".to_string(), 1);
1599 assert_eq!(nodes[0].node.list_channels().len(), 0);
1600 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1601 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1602 check_added_monitors!(nodes[0], 1);
1603 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() },
1604 [nodes[1].node.get_our_node_id()], 100000);
1608 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1609 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1610 // calculating our commitment transaction fee (this was previously broken).
1611 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1612 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1614 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1615 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1616 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1617 let default_config = UserConfig::default();
1618 let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1620 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1621 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1622 // transaction fee with 0 HTLCs (183 sats)).
1623 let mut push_amt = 100_000_000;
1624 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1625 push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1626 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt);
1628 let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1629 + feerate_per_kw as u64 * htlc_success_tx_weight(&channel_type_features) / 1000 * 1000 - 1;
1630 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1631 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1632 // commitment transaction fee.
1633 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1635 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1636 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1637 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1640 // One more than the dust amt should fail, however.
1641 let (mut route, our_payment_hash, _, our_payment_secret) =
1642 get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt);
1643 route.paths[0].hops[0].fee_msat += 1;
1644 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1645 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1646 ), true, APIError::ChannelUnavailable { .. }, {});
1650 fn test_chan_init_feerate_unaffordability() {
1651 // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1652 // channel reserve and feerate requirements.
1653 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1654 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1655 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1656 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1657 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1658 let default_config = UserConfig::default();
1659 let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1661 // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1663 let mut push_amt = 100_000_000;
1664 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1665 assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1666 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1668 // During open, we don't have a "counterparty channel reserve" to check against, so that
1669 // requirement only comes into play on the open_channel handling side.
1670 push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1671 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1672 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1673 open_channel_msg.push_msat += 1;
1674 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
1676 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1677 assert_eq!(msg_events.len(), 1);
1678 match msg_events[0] {
1679 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1680 assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1682 _ => panic!("Unexpected event"),
1687 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1688 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1689 // calculating our counterparty's commitment transaction fee (this was previously broken).
1690 let chanmon_cfgs = create_chanmon_cfgs(2);
1691 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1692 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1693 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1694 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000);
1696 let payment_amt = 46000; // Dust amount
1697 // In the previous code, these first four payments would succeed.
1698 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1699 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1700 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1701 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1703 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1704 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1705 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1706 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1707 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1708 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1710 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1711 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1712 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1713 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1717 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1718 let chanmon_cfgs = create_chanmon_cfgs(3);
1719 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1720 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1721 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1722 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1723 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
1726 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1727 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1728 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
1729 let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
1731 // Add a 2* and +1 for the fee spike reserve.
1732 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features);
1733 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;
1734 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1736 // Add a pending HTLC.
1737 let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1738 let payment_event_1 = {
1739 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1740 RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1741 check_added_monitors!(nodes[0], 1);
1743 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1744 assert_eq!(events.len(), 1);
1745 SendEvent::from_event(events.remove(0))
1747 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1749 // Attempt to trigger a channel reserve violation --> payment failure.
1750 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, &channel_type_features);
1751 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;
1752 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1753 let mut route_2 = route_1.clone();
1754 route_2.paths[0].hops.last_mut().unwrap().fee_msat = amt_msat_2;
1756 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1757 let secp_ctx = Secp256k1::new();
1758 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1759 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1760 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1761 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
1762 &route_2.paths[0], recv_value_2, RecipientOnionFields::spontaneous_empty(), cur_height, &None).unwrap();
1763 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1).unwrap();
1764 let msg = msgs::UpdateAddHTLC {
1767 amount_msat: htlc_msat + 1,
1768 payment_hash: our_payment_hash_1,
1769 cltv_expiry: htlc_cltv,
1770 onion_routing_packet: onion_packet,
1771 skimmed_fee_msat: None,
1774 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1775 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1776 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1777 assert_eq!(nodes[1].node.list_channels().len(), 1);
1778 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1779 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1780 check_added_monitors!(nodes[1], 1);
1781 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() },
1782 [nodes[0].node.get_our_node_id()], 100000);
1786 fn test_inbound_outbound_capacity_is_not_zero() {
1787 let chanmon_cfgs = create_chanmon_cfgs(2);
1788 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1789 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1790 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1791 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1792 let channels0 = node_chanmgrs[0].list_channels();
1793 let channels1 = node_chanmgrs[1].list_channels();
1794 let default_config = UserConfig::default();
1795 assert_eq!(channels0.len(), 1);
1796 assert_eq!(channels1.len(), 1);
1798 let reserve = get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1799 assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1800 assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1802 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1803 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1806 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, channel_type_features: &ChannelTypeFeatures) -> u64 {
1807 (commitment_tx_base_weight(channel_type_features) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1811 fn test_channel_reserve_holding_cell_htlcs() {
1812 let chanmon_cfgs = create_chanmon_cfgs(3);
1813 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1814 // When this test was written, the default base fee floated based on the HTLC count.
1815 // It is now fixed, so we simply set the fee to the expected value here.
1816 let mut config = test_default_channel_config();
1817 config.channel_config.forwarding_fee_base_msat = 239;
1818 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1819 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1820 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001);
1821 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001);
1823 let mut stat01 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1824 let mut stat11 = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
1826 let mut stat12 = get_channel_value_stat!(nodes[1], nodes[2], chan_2.2);
1827 let mut stat22 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
1829 macro_rules! expect_forward {
1831 let mut events = $node.node.get_and_clear_pending_msg_events();
1832 assert_eq!(events.len(), 1);
1833 check_added_monitors!($node, 1);
1834 let payment_event = SendEvent::from_event(events.remove(0));
1839 let feemsat = 239; // set above
1840 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1841 let feerate = get_feerate!(nodes[0], nodes[1], chan_1.2);
1842 let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_1.2);
1844 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1846 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1848 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1849 .with_bolt11_features(nodes[2].node.invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1850 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, recv_value_0);
1851 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1852 assert!(route.paths[0].hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1854 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1855 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1856 ), true, APIError::ChannelUnavailable { .. }, {});
1857 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1860 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1861 // nodes[0]'s wealth
1863 let amt_msat = recv_value_0 + total_fee_msat;
1864 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1865 // Also, ensure that each payment has enough to be over the dust limit to
1866 // ensure it'll be included in each commit tx fee calculation.
1867 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, &channel_type_features);
1868 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1869 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1873 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1874 .with_bolt11_features(nodes[2].node.invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1875 let route = get_route!(nodes[0], payment_params, recv_value_0).unwrap();
1876 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1877 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1879 let (stat01_, stat11_, stat12_, stat22_) = (
1880 get_channel_value_stat!(nodes[0], nodes[1], chan_1.2),
1881 get_channel_value_stat!(nodes[1], nodes[0], chan_1.2),
1882 get_channel_value_stat!(nodes[1], nodes[2], chan_2.2),
1883 get_channel_value_stat!(nodes[2], nodes[1], chan_2.2),
1886 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1887 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1888 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1889 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1890 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1893 // adding pending output.
1894 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1895 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1896 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1897 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1898 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1899 // cases where 1 msat over X amount will cause a payment failure, but anything less than
1900 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1901 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1902 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1904 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features);
1905 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1906 let amt_msat_1 = recv_value_1 + total_fee_msat;
1908 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);
1909 let payment_event_1 = {
1910 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1911 RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1912 check_added_monitors!(nodes[0], 1);
1914 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1915 assert_eq!(events.len(), 1);
1916 SendEvent::from_event(events.remove(0))
1918 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1920 // channel reserve test with htlc pending output > 0
1921 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1923 let mut route = route_1.clone();
1924 route.paths[0].hops.last_mut().unwrap().fee_msat = recv_value_2 + 1;
1925 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
1926 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1927 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1928 ), true, APIError::ChannelUnavailable { .. }, {});
1929 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1932 // split the rest to test holding cell
1933 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, &channel_type_features);
1934 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1935 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1936 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1938 let stat = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1939 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);
1942 // now see if they go through on both sides
1943 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);
1944 // but this will stuck in the holding cell
1945 nodes[0].node.send_payment_with_route(&route_21, our_payment_hash_21,
1946 RecipientOnionFields::secret_only(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
1947 check_added_monitors!(nodes[0], 0);
1948 let events = nodes[0].node.get_and_clear_pending_events();
1949 assert_eq!(events.len(), 0);
1951 // test with outbound holding cell amount > 0
1953 let (mut route, our_payment_hash, _, our_payment_secret) =
1954 get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22);
1955 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1956 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1957 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1958 ), true, APIError::ChannelUnavailable { .. }, {});
1959 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1962 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);
1963 // this will also stuck in the holding cell
1964 nodes[0].node.send_payment_with_route(&route_22, our_payment_hash_22,
1965 RecipientOnionFields::secret_only(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
1966 check_added_monitors!(nodes[0], 0);
1967 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1968 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1970 // flush the pending htlc
1971 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1972 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1973 check_added_monitors!(nodes[1], 1);
1975 // the pending htlc should be promoted to committed
1976 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1977 check_added_monitors!(nodes[0], 1);
1978 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1980 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1981 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1982 // No commitment_signed so get_event_msg's assert(len == 1) passes
1983 check_added_monitors!(nodes[0], 1);
1985 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1986 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1987 check_added_monitors!(nodes[1], 1);
1989 expect_pending_htlcs_forwardable!(nodes[1]);
1991 let ref payment_event_11 = expect_forward!(nodes[1]);
1992 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1993 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1995 expect_pending_htlcs_forwardable!(nodes[2]);
1996 expect_payment_claimable!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1998 // flush the htlcs in the holding cell
1999 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
2000 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
2001 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
2002 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
2003 expect_pending_htlcs_forwardable!(nodes[1]);
2005 let ref payment_event_3 = expect_forward!(nodes[1]);
2006 assert_eq!(payment_event_3.msgs.len(), 2);
2007 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
2008 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
2010 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2011 expect_pending_htlcs_forwardable!(nodes[2]);
2013 let events = nodes[2].node.get_and_clear_pending_events();
2014 assert_eq!(events.len(), 2);
2016 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2017 assert_eq!(our_payment_hash_21, *payment_hash);
2018 assert_eq!(recv_value_21, amount_msat);
2019 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2020 assert_eq!(via_channel_id, Some(chan_2.2));
2022 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2023 assert!(payment_preimage.is_none());
2024 assert_eq!(our_payment_secret_21, *payment_secret);
2026 _ => panic!("expected PaymentPurpose::InvoicePayment")
2029 _ => panic!("Unexpected event"),
2032 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2033 assert_eq!(our_payment_hash_22, *payment_hash);
2034 assert_eq!(recv_value_22, amount_msat);
2035 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2036 assert_eq!(via_channel_id, Some(chan_2.2));
2038 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2039 assert!(payment_preimage.is_none());
2040 assert_eq!(our_payment_secret_22, *payment_secret);
2042 _ => panic!("expected PaymentPurpose::InvoicePayment")
2045 _ => panic!("Unexpected event"),
2048 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2049 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2050 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2052 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, &channel_type_features);
2053 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2054 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2056 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
2057 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);
2058 let stat0 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
2059 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2060 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2062 let stat2 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
2063 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2067 fn channel_reserve_in_flight_removes() {
2068 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2069 // can send to its counterparty, but due to update ordering, the other side may not yet have
2070 // considered those HTLCs fully removed.
2071 // This tests that we don't count HTLCs which will not be included in the next remote
2072 // commitment transaction towards the reserve value (as it implies no commitment transaction
2073 // will be generated which violates the remote reserve value).
2074 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2076 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2077 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2078 // you only consider the value of the first HTLC, it may not),
2079 // * start routing a third HTLC from A to B,
2080 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2081 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2082 // * deliver the first fulfill from B
2083 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2085 // * deliver A's response CS and RAA.
2086 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2087 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
2088 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2089 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2090 let chanmon_cfgs = create_chanmon_cfgs(2);
2091 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2092 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2093 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2094 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2096 let b_chan_values = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
2097 // Route the first two HTLCs.
2098 let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2099 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2100 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2102 // Start routing the third HTLC (this is just used to get everyone in the right state).
2103 let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2105 nodes[0].node.send_payment_with_route(&route, payment_hash_3,
2106 RecipientOnionFields::secret_only(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2107 check_added_monitors!(nodes[0], 1);
2108 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2109 assert_eq!(events.len(), 1);
2110 SendEvent::from_event(events.remove(0))
2113 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2114 // initial fulfill/CS.
2115 nodes[1].node.claim_funds(payment_preimage_1);
2116 expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2117 check_added_monitors!(nodes[1], 1);
2118 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2120 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2121 // remove the second HTLC when we send the HTLC back from B to A.
2122 nodes[1].node.claim_funds(payment_preimage_2);
2123 expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2124 check_added_monitors!(nodes[1], 1);
2125 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2127 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2128 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2129 check_added_monitors!(nodes[0], 1);
2130 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2131 expect_payment_sent(&nodes[0], payment_preimage_1, None, false, false);
2133 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2134 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2135 check_added_monitors!(nodes[1], 1);
2136 // B is already AwaitingRAA, so cant generate a CS here
2137 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2139 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2140 check_added_monitors!(nodes[1], 1);
2141 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2143 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2144 check_added_monitors!(nodes[0], 1);
2145 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2147 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2148 check_added_monitors!(nodes[1], 1);
2149 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2151 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2152 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2153 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2154 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2155 // on-chain as necessary).
2156 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2157 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2158 check_added_monitors!(nodes[0], 1);
2159 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2160 expect_payment_sent(&nodes[0], payment_preimage_2, None, false, false);
2162 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2163 check_added_monitors!(nodes[1], 1);
2164 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2166 expect_pending_htlcs_forwardable!(nodes[1]);
2167 expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2169 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2170 // resolve the second HTLC from A's point of view.
2171 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2172 check_added_monitors!(nodes[0], 1);
2173 expect_payment_path_successful!(nodes[0]);
2174 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2176 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2177 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2178 let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2180 nodes[1].node.send_payment_with_route(&route, payment_hash_4,
2181 RecipientOnionFields::secret_only(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2182 check_added_monitors!(nodes[1], 1);
2183 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2184 assert_eq!(events.len(), 1);
2185 SendEvent::from_event(events.remove(0))
2188 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2189 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2190 check_added_monitors!(nodes[0], 1);
2191 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2193 // Now just resolve all the outstanding messages/HTLCs for completeness...
2195 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2196 check_added_monitors!(nodes[1], 1);
2197 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2199 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2200 check_added_monitors!(nodes[1], 1);
2202 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2203 check_added_monitors!(nodes[0], 1);
2204 expect_payment_path_successful!(nodes[0]);
2205 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2207 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2208 check_added_monitors!(nodes[1], 1);
2209 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2211 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2212 check_added_monitors!(nodes[0], 1);
2214 expect_pending_htlcs_forwardable!(nodes[0]);
2215 expect_payment_claimable!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2217 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2218 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2222 fn channel_monitor_network_test() {
2223 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2224 // tests that ChannelMonitor is able to recover from various states.
2225 let chanmon_cfgs = create_chanmon_cfgs(5);
2226 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2227 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2228 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2230 // Create some initial channels
2231 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2232 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2233 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2234 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
2236 // Make sure all nodes are at the same starting height
2237 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2238 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2239 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2240 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2241 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2243 // Rebalance the network a bit by relaying one payment through all the channels...
2244 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2245 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2246 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2247 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2249 // Simple case with no pending HTLCs:
2250 nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2251 check_added_monitors!(nodes[1], 1);
2252 check_closed_broadcast!(nodes[1], true);
2254 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2255 assert_eq!(node_txn.len(), 1);
2256 mine_transaction(&nodes[0], &node_txn[0]);
2257 check_added_monitors!(nodes[0], 1);
2258 test_txn_broadcast(&nodes[0], &chan_1, Some(node_txn[0].clone()), HTLCType::NONE);
2260 check_closed_broadcast!(nodes[0], true);
2261 assert_eq!(nodes[0].node.list_channels().len(), 0);
2262 assert_eq!(nodes[1].node.list_channels().len(), 1);
2263 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2264 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[0].node.get_our_node_id()], 100000);
2266 // One pending HTLC is discarded by the force-close:
2267 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2269 // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2270 // broadcasted until we reach the timelock time).
2271 nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2272 check_closed_broadcast!(nodes[1], true);
2273 check_added_monitors!(nodes[1], 1);
2275 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2276 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2277 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2278 mine_transaction(&nodes[2], &node_txn[0]);
2279 check_added_monitors!(nodes[2], 1);
2280 test_txn_broadcast(&nodes[2], &chan_2, Some(node_txn[0].clone()), HTLCType::NONE);
2282 check_closed_broadcast!(nodes[2], true);
2283 assert_eq!(nodes[1].node.list_channels().len(), 0);
2284 assert_eq!(nodes[2].node.list_channels().len(), 1);
2285 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[2].node.get_our_node_id()], 100000);
2286 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2288 macro_rules! claim_funds {
2289 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2291 $node.node.claim_funds($preimage);
2292 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2293 check_added_monitors!($node, 1);
2295 let events = $node.node.get_and_clear_pending_msg_events();
2296 assert_eq!(events.len(), 1);
2298 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2299 assert!(update_add_htlcs.is_empty());
2300 assert!(update_fail_htlcs.is_empty());
2301 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2303 _ => panic!("Unexpected event"),
2309 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2310 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2311 nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2312 check_added_monitors!(nodes[2], 1);
2313 check_closed_broadcast!(nodes[2], true);
2314 let node2_commitment_txid;
2316 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2317 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2318 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2319 node2_commitment_txid = node_txn[0].txid();
2321 // Claim the payment on nodes[3], giving it knowledge of the preimage
2322 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2323 mine_transaction(&nodes[3], &node_txn[0]);
2324 check_added_monitors!(nodes[3], 1);
2325 check_preimage_claim(&nodes[3], &node_txn);
2327 check_closed_broadcast!(nodes[3], true);
2328 assert_eq!(nodes[2].node.list_channels().len(), 0);
2329 assert_eq!(nodes[3].node.list_channels().len(), 1);
2330 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed, [nodes[3].node.get_our_node_id()], 100000);
2331 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
2333 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2334 // confusing us in the following tests.
2335 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2337 // One pending HTLC to time out:
2338 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2339 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2342 let (close_chan_update_1, close_chan_update_2) = {
2343 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2344 let events = nodes[3].node.get_and_clear_pending_msg_events();
2345 assert_eq!(events.len(), 2);
2346 let close_chan_update_1 = match events[0] {
2347 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2350 _ => panic!("Unexpected event"),
2353 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2354 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2356 _ => panic!("Unexpected event"),
2358 check_added_monitors!(nodes[3], 1);
2360 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2362 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2363 node_txn.retain(|tx| {
2364 if tx.input[0].previous_output.txid == node2_commitment_txid {
2370 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2372 // Claim the payment on nodes[4], giving it knowledge of the preimage
2373 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2375 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2376 let events = nodes[4].node.get_and_clear_pending_msg_events();
2377 assert_eq!(events.len(), 2);
2378 let close_chan_update_2 = match events[0] {
2379 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2382 _ => panic!("Unexpected event"),
2385 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2386 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2388 _ => panic!("Unexpected event"),
2390 check_added_monitors!(nodes[4], 1);
2391 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2393 mine_transaction(&nodes[4], &node_txn[0]);
2394 check_preimage_claim(&nodes[4], &node_txn);
2395 (close_chan_update_1, close_chan_update_2)
2397 nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2398 nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2399 assert_eq!(nodes[3].node.list_channels().len(), 0);
2400 assert_eq!(nodes[4].node.list_channels().len(), 0);
2402 assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2403 ChannelMonitorUpdateStatus::Completed);
2404 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed, [nodes[4].node.get_our_node_id()], 100000);
2405 check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed, [nodes[3].node.get_our_node_id()], 100000);
2409 fn test_justice_tx_htlc_timeout() {
2410 // Test justice txn built on revoked HTLC-Timeout tx, against both sides
2411 let mut alice_config = UserConfig::default();
2412 alice_config.channel_handshake_config.announced_channel = true;
2413 alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2414 alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2415 let mut bob_config = UserConfig::default();
2416 bob_config.channel_handshake_config.announced_channel = true;
2417 bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2418 bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2419 let user_cfgs = [Some(alice_config), Some(bob_config)];
2420 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2421 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2422 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2423 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2424 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2425 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2426 // Create some new channels:
2427 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
2429 // A pending HTLC which will be revoked:
2430 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2431 // Get the will-be-revoked local txn from nodes[0]
2432 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2433 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2434 assert_eq!(revoked_local_txn[0].input.len(), 1);
2435 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2436 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2437 assert_eq!(revoked_local_txn[1].input.len(), 1);
2438 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2439 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2440 // Revoke the old state
2441 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2444 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2446 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2447 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2448 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2449 check_spends!(node_txn[0], revoked_local_txn[0]);
2450 node_txn.swap_remove(0);
2452 check_added_monitors!(nodes[1], 1);
2453 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2454 test_txn_broadcast(&nodes[1], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2456 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2457 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2458 // Verify broadcast of revoked HTLC-timeout
2459 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2460 check_added_monitors!(nodes[0], 1);
2461 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2462 // Broadcast revoked HTLC-timeout on node 1
2463 mine_transaction(&nodes[1], &node_txn[1]);
2464 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2466 get_announce_close_broadcast_events(&nodes, 0, 1);
2467 assert_eq!(nodes[0].node.list_channels().len(), 0);
2468 assert_eq!(nodes[1].node.list_channels().len(), 0);
2472 fn test_justice_tx_htlc_success() {
2473 // Test justice txn built on revoked HTLC-Success tx, against both sides
2474 let mut alice_config = UserConfig::default();
2475 alice_config.channel_handshake_config.announced_channel = true;
2476 alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2477 alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2478 let mut bob_config = UserConfig::default();
2479 bob_config.channel_handshake_config.announced_channel = true;
2480 bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2481 bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2482 let user_cfgs = [Some(alice_config), Some(bob_config)];
2483 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2484 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2485 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2486 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2487 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2488 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2489 // Create some new channels:
2490 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
2492 // A pending HTLC which will be revoked:
2493 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2494 // Get the will-be-revoked local txn from B
2495 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2496 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2497 assert_eq!(revoked_local_txn[0].input.len(), 1);
2498 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2499 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2500 // Revoke the old state
2501 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2503 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2505 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2506 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2507 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2509 check_spends!(node_txn[0], revoked_local_txn[0]);
2510 node_txn.swap_remove(0);
2512 check_added_monitors!(nodes[0], 1);
2513 test_txn_broadcast(&nodes[0], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2515 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2516 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2517 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2518 check_added_monitors!(nodes[1], 1);
2519 mine_transaction(&nodes[0], &node_txn[1]);
2520 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2521 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2523 get_announce_close_broadcast_events(&nodes, 0, 1);
2524 assert_eq!(nodes[0].node.list_channels().len(), 0);
2525 assert_eq!(nodes[1].node.list_channels().len(), 0);
2529 fn revoked_output_claim() {
2530 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2531 // transaction is broadcast by its counterparty
2532 let chanmon_cfgs = create_chanmon_cfgs(2);
2533 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2534 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2535 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2536 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2537 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2538 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2539 assert_eq!(revoked_local_txn.len(), 1);
2540 // Only output is the full channel value back to nodes[0]:
2541 assert_eq!(revoked_local_txn[0].output.len(), 1);
2542 // Send a payment through, updating everyone's latest commitment txn
2543 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2545 // Inform nodes[1] that nodes[0] broadcast a stale tx
2546 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2547 check_added_monitors!(nodes[1], 1);
2548 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2549 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2550 assert_eq!(node_txn.len(), 1); // ChannelMonitor: justice tx against revoked to_local output
2552 check_spends!(node_txn[0], revoked_local_txn[0]);
2554 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2555 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2556 get_announce_close_broadcast_events(&nodes, 0, 1);
2557 check_added_monitors!(nodes[0], 1);
2558 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2562 fn test_forming_justice_tx_from_monitor_updates() {
2563 do_test_forming_justice_tx_from_monitor_updates(true);
2564 do_test_forming_justice_tx_from_monitor_updates(false);
2567 fn do_test_forming_justice_tx_from_monitor_updates(broadcast_initial_commitment: bool) {
2568 // Simple test to make sure that the justice tx formed in WatchtowerPersister
2569 // is properly formed and can be broadcasted/confirmed successfully in the event
2570 // that a revoked commitment transaction is broadcasted
2571 // (Similar to `revoked_output_claim` test but we get the justice tx + broadcast manually)
2572 let chanmon_cfgs = create_chanmon_cfgs(2);
2573 let destination_script0 = chanmon_cfgs[0].keys_manager.get_destination_script().unwrap();
2574 let destination_script1 = chanmon_cfgs[1].keys_manager.get_destination_script().unwrap();
2575 let persisters = vec![WatchtowerPersister::new(destination_script0),
2576 WatchtowerPersister::new(destination_script1)];
2577 let node_cfgs = create_node_cfgs_with_persisters(2, &chanmon_cfgs, persisters.iter().collect());
2578 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2579 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2580 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
2581 let funding_txo = OutPoint { txid: funding_tx.txid(), index: 0 };
2583 if !broadcast_initial_commitment {
2584 // Send a payment to move the channel forward
2585 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5_000_000);
2588 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output.
2589 // We'll keep this commitment transaction to broadcast once it's revoked.
2590 let revoked_local_txn = get_local_commitment_txn!(nodes[0], channel_id);
2591 assert_eq!(revoked_local_txn.len(), 1);
2592 let revoked_commitment_tx = &revoked_local_txn[0];
2594 // Send another payment, now revoking the previous commitment tx
2595 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5_000_000);
2597 let justice_tx = persisters[1].justice_tx(funding_txo, &revoked_commitment_tx.txid()).unwrap();
2598 check_spends!(justice_tx, revoked_commitment_tx);
2600 mine_transactions(&nodes[1], &[revoked_commitment_tx, &justice_tx]);
2601 mine_transactions(&nodes[0], &[revoked_commitment_tx, &justice_tx]);
2603 check_added_monitors!(nodes[1], 1);
2604 check_closed_event(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false,
2605 &[nodes[0].node.get_our_node_id()], 100_000);
2606 get_announce_close_broadcast_events(&nodes, 1, 0);
2608 check_added_monitors!(nodes[0], 1);
2609 check_closed_event(&nodes[0], 1, ClosureReason::CommitmentTxConfirmed, false,
2610 &[nodes[1].node.get_our_node_id()], 100_000);
2612 // Check that the justice tx has sent the revoked output value to nodes[1]
2613 let monitor = get_monitor!(nodes[1], channel_id);
2614 let total_claimable_balance = monitor.get_claimable_balances().iter().fold(0, |sum, balance| {
2616 channelmonitor::Balance::ClaimableAwaitingConfirmations { amount_satoshis, .. } => sum + amount_satoshis,
2617 _ => panic!("Unexpected balance type"),
2620 // On the first commitment, node[1]'s balance was below dust so it didn't have an output
2621 let node1_channel_balance = if broadcast_initial_commitment { 0 } else { revoked_commitment_tx.output[0].value };
2622 let expected_claimable_balance = node1_channel_balance + justice_tx.output[0].value;
2623 assert_eq!(total_claimable_balance, expected_claimable_balance);
2628 fn claim_htlc_outputs_shared_tx() {
2629 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2630 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2631 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2632 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2633 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2634 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2636 // Create some new channel:
2637 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2639 // Rebalance the network to generate htlc in the two directions
2640 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2641 // 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
2642 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2643 let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2645 // Get the will-be-revoked local txn from node[0]
2646 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2647 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2648 assert_eq!(revoked_local_txn[0].input.len(), 1);
2649 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2650 assert_eq!(revoked_local_txn[1].input.len(), 1);
2651 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2652 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2653 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2655 //Revoke the old state
2656 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2659 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2660 check_added_monitors!(nodes[0], 1);
2661 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2662 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2663 check_added_monitors!(nodes[1], 1);
2664 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2665 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2666 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2668 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2669 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2671 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2672 check_spends!(node_txn[0], revoked_local_txn[0]);
2674 let mut witness_lens = BTreeSet::new();
2675 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2676 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2677 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2678 assert_eq!(witness_lens.len(), 3);
2679 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2680 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2681 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2683 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2684 // ANTI_REORG_DELAY confirmations.
2685 mine_transaction(&nodes[1], &node_txn[0]);
2686 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2687 expect_payment_failed!(nodes[1], payment_hash_2, false);
2689 get_announce_close_broadcast_events(&nodes, 0, 1);
2690 assert_eq!(nodes[0].node.list_channels().len(), 0);
2691 assert_eq!(nodes[1].node.list_channels().len(), 0);
2695 fn claim_htlc_outputs_single_tx() {
2696 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2697 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2698 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2699 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2700 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2701 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
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, but this
2708 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2709 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2710 let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2712 // Get the will-be-revoked local txn from node[0]
2713 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2715 //Revoke the old state
2716 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2719 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2720 check_added_monitors!(nodes[0], 1);
2721 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2722 check_added_monitors!(nodes[1], 1);
2723 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2724 let mut events = nodes[0].node.get_and_clear_pending_events();
2725 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2726 match events.last().unwrap() {
2727 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2728 _ => panic!("Unexpected event"),
2731 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2732 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2734 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcast();
2736 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2737 assert_eq!(node_txn[0].input.len(), 1);
2738 check_spends!(node_txn[0], chan_1.3);
2739 assert_eq!(node_txn[1].input.len(), 1);
2740 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2741 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2742 check_spends!(node_txn[1], node_txn[0]);
2744 // Filter out any non justice transactions.
2745 node_txn.retain(|tx| tx.input[0].previous_output.txid == revoked_local_txn[0].txid());
2746 assert!(node_txn.len() > 3);
2748 assert_eq!(node_txn[0].input.len(), 1);
2749 assert_eq!(node_txn[1].input.len(), 1);
2750 assert_eq!(node_txn[2].input.len(), 1);
2752 check_spends!(node_txn[0], revoked_local_txn[0]);
2753 check_spends!(node_txn[1], revoked_local_txn[0]);
2754 check_spends!(node_txn[2], revoked_local_txn[0]);
2756 let mut witness_lens = BTreeSet::new();
2757 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2758 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2759 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2760 assert_eq!(witness_lens.len(), 3);
2761 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2762 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2763 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2765 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2766 // ANTI_REORG_DELAY confirmations.
2767 mine_transaction(&nodes[1], &node_txn[0]);
2768 mine_transaction(&nodes[1], &node_txn[1]);
2769 mine_transaction(&nodes[1], &node_txn[2]);
2770 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2771 expect_payment_failed!(nodes[1], payment_hash_2, false);
2773 get_announce_close_broadcast_events(&nodes, 0, 1);
2774 assert_eq!(nodes[0].node.list_channels().len(), 0);
2775 assert_eq!(nodes[1].node.list_channels().len(), 0);
2779 fn test_htlc_on_chain_success() {
2780 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2781 // the preimage backward accordingly. So here we test that ChannelManager is
2782 // broadcasting the right event to other nodes in payment path.
2783 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2784 // A --------------------> B ----------------------> C (preimage)
2785 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2786 // commitment transaction was broadcast.
2787 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2789 // B should be able to claim via preimage if A then broadcasts its local tx.
2790 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2791 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2792 // PaymentSent event).
2794 let chanmon_cfgs = create_chanmon_cfgs(3);
2795 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2796 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2797 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2799 // Create some initial channels
2800 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2801 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2803 // Ensure all nodes are at the same height
2804 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2805 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2806 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2807 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2809 // Rebalance the network a bit by relaying one payment through all the channels...
2810 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2811 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2813 let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2814 let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2816 // Broadcast legit commitment tx from C on B's chain
2817 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2818 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2819 assert_eq!(commitment_tx.len(), 1);
2820 check_spends!(commitment_tx[0], chan_2.3);
2821 nodes[2].node.claim_funds(our_payment_preimage);
2822 expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2823 nodes[2].node.claim_funds(our_payment_preimage_2);
2824 expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2825 check_added_monitors!(nodes[2], 2);
2826 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2827 assert!(updates.update_add_htlcs.is_empty());
2828 assert!(updates.update_fail_htlcs.is_empty());
2829 assert!(updates.update_fail_malformed_htlcs.is_empty());
2830 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2832 mine_transaction(&nodes[2], &commitment_tx[0]);
2833 check_closed_broadcast!(nodes[2], true);
2834 check_added_monitors!(nodes[2], 1);
2835 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2836 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 2 (2 * HTLC-Success tx)
2837 assert_eq!(node_txn.len(), 2);
2838 check_spends!(node_txn[0], commitment_tx[0]);
2839 check_spends!(node_txn[1], commitment_tx[0]);
2840 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2841 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2842 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2843 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2844 assert_eq!(node_txn[0].lock_time.0, 0);
2845 assert_eq!(node_txn[1].lock_time.0, 0);
2847 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2848 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()]));
2849 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2851 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2852 assert_eq!(added_monitors.len(), 1);
2853 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2854 added_monitors.clear();
2856 let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2857 assert_eq!(forwarded_events.len(), 3);
2858 match forwarded_events[0] {
2859 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2860 _ => panic!("Unexpected event"),
2862 let chan_id = Some(chan_1.2);
2863 match forwarded_events[1] {
2864 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2865 assert_eq!(fee_earned_msat, Some(1000));
2866 assert_eq!(prev_channel_id, chan_id);
2867 assert_eq!(claim_from_onchain_tx, true);
2868 assert_eq!(next_channel_id, Some(chan_2.2));
2869 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2873 match forwarded_events[2] {
2874 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2875 assert_eq!(fee_earned_msat, Some(1000));
2876 assert_eq!(prev_channel_id, chan_id);
2877 assert_eq!(claim_from_onchain_tx, true);
2878 assert_eq!(next_channel_id, Some(chan_2.2));
2879 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2883 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2885 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2886 assert_eq!(added_monitors.len(), 2);
2887 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2888 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2889 added_monitors.clear();
2891 assert_eq!(events.len(), 3);
2893 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
2894 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
2896 match nodes_2_event {
2897 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2898 _ => panic!("Unexpected event"),
2901 match nodes_0_event {
2902 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, .. } } => {
2903 assert!(update_add_htlcs.is_empty());
2904 assert!(update_fail_htlcs.is_empty());
2905 assert_eq!(update_fulfill_htlcs.len(), 1);
2906 assert!(update_fail_malformed_htlcs.is_empty());
2907 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2909 _ => panic!("Unexpected event"),
2912 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
2914 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2915 _ => panic!("Unexpected event"),
2918 macro_rules! check_tx_local_broadcast {
2919 ($node: expr, $htlc_offered: expr, $commitment_tx: expr) => { {
2920 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2921 assert_eq!(node_txn.len(), 2);
2922 // Node[1]: 2 * HTLC-timeout tx
2923 // Node[0]: 2 * HTLC-timeout tx
2924 check_spends!(node_txn[0], $commitment_tx);
2925 check_spends!(node_txn[1], $commitment_tx);
2926 assert_ne!(node_txn[0].lock_time.0, 0);
2927 assert_ne!(node_txn[1].lock_time.0, 0);
2929 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2930 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2931 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2932 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2934 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2935 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2936 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2937 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2942 // nodes[1] now broadcasts its own timeout-claim of the output that nodes[2] just claimed via success.
2943 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0]);
2945 // Broadcast legit commitment tx from A on B's chain
2946 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2947 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2948 check_spends!(node_a_commitment_tx[0], chan_1.3);
2949 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2950 check_closed_broadcast!(nodes[1], true);
2951 check_added_monitors!(nodes[1], 1);
2952 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2953 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2954 assert!(node_txn.len() == 1 || node_txn.len() == 3); // HTLC-Success, 2* RBF bumps of above HTLC txn
2955 let commitment_spend =
2956 if node_txn.len() == 1 {
2959 // Certain `ConnectStyle`s will cause RBF bumps of the previous HTLC transaction to be broadcast.
2960 // FullBlockViaListen
2961 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2962 check_spends!(node_txn[1], commitment_tx[0]);
2963 check_spends!(node_txn[2], commitment_tx[0]);
2964 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2967 check_spends!(node_txn[0], commitment_tx[0]);
2968 check_spends!(node_txn[1], commitment_tx[0]);
2969 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2974 check_spends!(commitment_spend, node_a_commitment_tx[0]);
2975 assert_eq!(commitment_spend.input.len(), 2);
2976 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2977 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2978 assert_eq!(commitment_spend.lock_time.0, nodes[1].best_block_info().1);
2979 assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2980 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2981 // we already checked the same situation with A.
2983 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2984 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()]));
2985 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
2986 check_closed_broadcast!(nodes[0], true);
2987 check_added_monitors!(nodes[0], 1);
2988 let events = nodes[0].node.get_and_clear_pending_events();
2989 assert_eq!(events.len(), 5);
2990 let mut first_claimed = false;
2991 for event in events {
2993 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2994 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2995 assert!(!first_claimed);
2996 first_claimed = true;
2998 assert_eq!(payment_preimage, our_payment_preimage_2);
2999 assert_eq!(payment_hash, payment_hash_2);
3002 Event::PaymentPathSuccessful { .. } => {},
3003 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
3004 _ => panic!("Unexpected event"),
3007 check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0]);
3010 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
3011 // Test that in case of a unilateral close onchain, we detect the state of output and
3012 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
3013 // broadcasting the right event to other nodes in payment path.
3014 // A ------------------> B ----------------------> C (timeout)
3015 // B's commitment tx C's commitment tx
3017 // B's HTLC timeout tx B's timeout tx
3019 let chanmon_cfgs = create_chanmon_cfgs(3);
3020 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3021 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3022 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3023 *nodes[0].connect_style.borrow_mut() = connect_style;
3024 *nodes[1].connect_style.borrow_mut() = connect_style;
3025 *nodes[2].connect_style.borrow_mut() = connect_style;
3027 // Create some intial channels
3028 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
3029 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3031 // Rebalance the network a bit by relaying one payment thorugh all the channels...
3032 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
3033 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
3035 let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
3037 // Broadcast legit commitment tx from C on B's chain
3038 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
3039 check_spends!(commitment_tx[0], chan_2.3);
3040 nodes[2].node.fail_htlc_backwards(&payment_hash);
3041 check_added_monitors!(nodes[2], 0);
3042 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
3043 check_added_monitors!(nodes[2], 1);
3045 let events = nodes[2].node.get_and_clear_pending_msg_events();
3046 assert_eq!(events.len(), 1);
3048 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, .. } } => {
3049 assert!(update_add_htlcs.is_empty());
3050 assert!(!update_fail_htlcs.is_empty());
3051 assert!(update_fulfill_htlcs.is_empty());
3052 assert!(update_fail_malformed_htlcs.is_empty());
3053 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
3055 _ => panic!("Unexpected event"),
3057 mine_transaction(&nodes[2], &commitment_tx[0]);
3058 check_closed_broadcast!(nodes[2], true);
3059 check_added_monitors!(nodes[2], 1);
3060 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
3061 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
3062 assert_eq!(node_txn.len(), 0);
3064 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
3065 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
3066 mine_transaction(&nodes[1], &commitment_tx[0]);
3067 check_closed_event!(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false
3068 , [nodes[2].node.get_our_node_id()], 100000);
3069 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
3071 let mut txn = nodes[1].tx_broadcaster.txn_broadcast();
3072 if nodes[1].connect_style.borrow().skips_blocks() {
3073 assert_eq!(txn.len(), 1);
3075 assert_eq!(txn.len(), 3); // Two extra fee bumps for timeout transaction
3077 txn.iter().for_each(|tx| check_spends!(tx, commitment_tx[0]));
3078 assert_eq!(txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3082 mine_transaction(&nodes[1], &timeout_tx);
3083 check_added_monitors!(nodes[1], 1);
3084 check_closed_broadcast!(nodes[1], true);
3086 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3088 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 }]);
3089 check_added_monitors!(nodes[1], 1);
3090 let events = nodes[1].node.get_and_clear_pending_msg_events();
3091 assert_eq!(events.len(), 1);
3093 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, .. } } => {
3094 assert!(update_add_htlcs.is_empty());
3095 assert!(!update_fail_htlcs.is_empty());
3096 assert!(update_fulfill_htlcs.is_empty());
3097 assert!(update_fail_malformed_htlcs.is_empty());
3098 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3100 _ => panic!("Unexpected event"),
3103 // Broadcast legit commitment tx from B on A's chain
3104 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3105 check_spends!(commitment_tx[0], chan_1.3);
3107 mine_transaction(&nodes[0], &commitment_tx[0]);
3108 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
3110 check_closed_broadcast!(nodes[0], true);
3111 check_added_monitors!(nodes[0], 1);
3112 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
3113 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // 1 timeout tx
3114 assert_eq!(node_txn.len(), 1);
3115 check_spends!(node_txn[0], commitment_tx[0]);
3116 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3120 fn test_htlc_on_chain_timeout() {
3121 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3122 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3123 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3127 fn test_simple_commitment_revoked_fail_backward() {
3128 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3129 // and fail backward accordingly.
3131 let chanmon_cfgs = create_chanmon_cfgs(3);
3132 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3133 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3134 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3136 // Create some initial channels
3137 create_announced_chan_between_nodes(&nodes, 0, 1);
3138 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3140 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3141 // Get the will-be-revoked local txn from nodes[2]
3142 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3143 // Revoke the old state
3144 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3146 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3148 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3149 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
3150 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3151 check_added_monitors!(nodes[1], 1);
3152 check_closed_broadcast!(nodes[1], true);
3154 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 }]);
3155 check_added_monitors!(nodes[1], 1);
3156 let events = nodes[1].node.get_and_clear_pending_msg_events();
3157 assert_eq!(events.len(), 1);
3159 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, .. } } => {
3160 assert!(update_add_htlcs.is_empty());
3161 assert_eq!(update_fail_htlcs.len(), 1);
3162 assert!(update_fulfill_htlcs.is_empty());
3163 assert!(update_fail_malformed_htlcs.is_empty());
3164 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3166 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3167 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3168 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3170 _ => panic!("Unexpected event"),
3174 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3175 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3176 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3177 // commitment transaction anymore.
3178 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3179 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3180 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3181 // technically disallowed and we should probably handle it reasonably.
3182 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3183 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3185 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3186 // commitment_signed (implying it will be in the latest remote commitment transaction).
3187 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3188 // and once they revoke the previous commitment transaction (allowing us to send a new
3189 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3190 let chanmon_cfgs = create_chanmon_cfgs(3);
3191 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3192 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3193 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3195 // Create some initial channels
3196 create_announced_chan_between_nodes(&nodes, 0, 1);
3197 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3199 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3200 // Get the will-be-revoked local txn from nodes[2]
3201 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3202 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3203 // Revoke the old state
3204 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3206 let value = if use_dust {
3207 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3208 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3209 nodes[2].node.per_peer_state.read().unwrap().get(&nodes[1].node.get_our_node_id())
3210 .unwrap().lock().unwrap().channel_by_id.get(&chan_2.2).unwrap().context.holder_dust_limit_satoshis * 1000
3213 let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3214 let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3215 let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3217 nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3218 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3219 check_added_monitors!(nodes[2], 1);
3220 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3221 assert!(updates.update_add_htlcs.is_empty());
3222 assert!(updates.update_fulfill_htlcs.is_empty());
3223 assert!(updates.update_fail_malformed_htlcs.is_empty());
3224 assert_eq!(updates.update_fail_htlcs.len(), 1);
3225 assert!(updates.update_fee.is_none());
3226 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3227 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3228 // Drop the last RAA from 3 -> 2
3230 nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3231 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3232 check_added_monitors!(nodes[2], 1);
3233 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3234 assert!(updates.update_add_htlcs.is_empty());
3235 assert!(updates.update_fulfill_htlcs.is_empty());
3236 assert!(updates.update_fail_malformed_htlcs.is_empty());
3237 assert_eq!(updates.update_fail_htlcs.len(), 1);
3238 assert!(updates.update_fee.is_none());
3239 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3240 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3241 check_added_monitors!(nodes[1], 1);
3242 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3243 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3244 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3245 check_added_monitors!(nodes[2], 1);
3247 nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3248 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3249 check_added_monitors!(nodes[2], 1);
3250 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3251 assert!(updates.update_add_htlcs.is_empty());
3252 assert!(updates.update_fulfill_htlcs.is_empty());
3253 assert!(updates.update_fail_malformed_htlcs.is_empty());
3254 assert_eq!(updates.update_fail_htlcs.len(), 1);
3255 assert!(updates.update_fee.is_none());
3256 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3257 // At this point first_payment_hash has dropped out of the latest two commitment
3258 // transactions that nodes[1] is tracking...
3259 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3260 check_added_monitors!(nodes[1], 1);
3261 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3262 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3263 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3264 check_added_monitors!(nodes[2], 1);
3266 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3267 // on nodes[2]'s RAA.
3268 let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3269 nodes[1].node.send_payment_with_route(&route, fourth_payment_hash,
3270 RecipientOnionFields::secret_only(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3271 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3272 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3273 check_added_monitors!(nodes[1], 0);
3276 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3277 // One monitor for the new revocation preimage, no second on as we won't generate a new
3278 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3279 check_added_monitors!(nodes[1], 1);
3280 let events = nodes[1].node.get_and_clear_pending_events();
3281 assert_eq!(events.len(), 2);
3283 Event::PendingHTLCsForwardable { .. } => { },
3284 _ => panic!("Unexpected event"),
3287 Event::HTLCHandlingFailed { .. } => { },
3288 _ => panic!("Unexpected event"),
3290 // Deliberately don't process the pending fail-back so they all fail back at once after
3291 // block connection just like the !deliver_bs_raa case
3294 let mut failed_htlcs = HashSet::new();
3295 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3297 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3298 check_added_monitors!(nodes[1], 1);
3299 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3301 let events = nodes[1].node.get_and_clear_pending_events();
3302 assert_eq!(events.len(), if deliver_bs_raa { 3 + nodes.len() - 1 } else { 4 + nodes.len() });
3304 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3305 _ => panic!("Unexepected event"),
3308 Event::PaymentPathFailed { ref payment_hash, .. } => {
3309 assert_eq!(*payment_hash, fourth_payment_hash);
3311 _ => panic!("Unexpected event"),
3314 Event::PaymentFailed { ref payment_hash, .. } => {
3315 assert_eq!(*payment_hash, fourth_payment_hash);
3317 _ => panic!("Unexpected event"),
3320 nodes[1].node.process_pending_htlc_forwards();
3321 check_added_monitors!(nodes[1], 1);
3323 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
3324 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3327 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3328 match nodes_2_event {
3329 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, .. } } => {
3330 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3331 assert_eq!(update_add_htlcs.len(), 1);
3332 assert!(update_fulfill_htlcs.is_empty());
3333 assert!(update_fail_htlcs.is_empty());
3334 assert!(update_fail_malformed_htlcs.is_empty());
3336 _ => panic!("Unexpected event"),
3340 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3341 match nodes_2_event {
3342 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3343 assert_eq!(channel_id, chan_2.2);
3344 assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3346 _ => panic!("Unexpected event"),
3349 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
3350 match nodes_0_event {
3351 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, .. } } => {
3352 assert!(update_add_htlcs.is_empty());
3353 assert_eq!(update_fail_htlcs.len(), 3);
3354 assert!(update_fulfill_htlcs.is_empty());
3355 assert!(update_fail_malformed_htlcs.is_empty());
3356 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3358 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3359 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3360 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3362 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3364 let events = nodes[0].node.get_and_clear_pending_events();
3365 assert_eq!(events.len(), 6);
3367 Event::PaymentPathFailed { ref payment_hash, ref failure, .. } => {
3368 assert!(failed_htlcs.insert(payment_hash.0));
3369 // If we delivered B's RAA we got an unknown preimage error, not something
3370 // that we should update our routing table for.
3371 if !deliver_bs_raa {
3372 if let PathFailure::OnPath { network_update: Some(_) } = failure { } else { panic!("Unexpected path failure") }
3375 _ => panic!("Unexpected event"),
3378 Event::PaymentFailed { ref payment_hash, .. } => {
3379 assert_eq!(*payment_hash, first_payment_hash);
3381 _ => panic!("Unexpected event"),
3384 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3385 assert!(failed_htlcs.insert(payment_hash.0));
3387 _ => panic!("Unexpected event"),
3390 Event::PaymentFailed { ref payment_hash, .. } => {
3391 assert_eq!(*payment_hash, second_payment_hash);
3393 _ => panic!("Unexpected event"),
3396 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3397 assert!(failed_htlcs.insert(payment_hash.0));
3399 _ => panic!("Unexpected event"),
3402 Event::PaymentFailed { ref payment_hash, .. } => {
3403 assert_eq!(*payment_hash, third_payment_hash);
3405 _ => panic!("Unexpected event"),
3408 _ => panic!("Unexpected event"),
3411 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
3413 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3414 _ => panic!("Unexpected event"),
3417 assert!(failed_htlcs.contains(&first_payment_hash.0));
3418 assert!(failed_htlcs.contains(&second_payment_hash.0));
3419 assert!(failed_htlcs.contains(&third_payment_hash.0));
3423 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3424 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3425 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3426 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3427 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3431 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3432 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3433 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3434 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3435 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3439 fn fail_backward_pending_htlc_upon_channel_failure() {
3440 let chanmon_cfgs = create_chanmon_cfgs(2);
3441 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3442 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3443 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3444 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
3446 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3448 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3449 nodes[0].node.send_payment_with_route(&route, payment_hash, RecipientOnionFields::secret_only(payment_secret),
3450 PaymentId(payment_hash.0)).unwrap();
3451 check_added_monitors!(nodes[0], 1);
3453 let payment_event = {
3454 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3455 assert_eq!(events.len(), 1);
3456 SendEvent::from_event(events.remove(0))
3458 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3459 assert_eq!(payment_event.msgs.len(), 1);
3462 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3463 let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3465 nodes[0].node.send_payment_with_route(&route, failed_payment_hash,
3466 RecipientOnionFields::secret_only(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3467 check_added_monitors!(nodes[0], 0);
3469 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3472 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3474 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3476 let secp_ctx = Secp256k1::new();
3477 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3478 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3479 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(
3480 &route.paths[0], 50_000, RecipientOnionFields::secret_only(payment_secret), current_height, &None).unwrap();
3481 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3482 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
3484 // Send a 0-msat update_add_htlc to fail the channel.
3485 let update_add_htlc = msgs::UpdateAddHTLC {
3491 onion_routing_packet,
3492 skimmed_fee_msat: None,
3494 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3496 let events = nodes[0].node.get_and_clear_pending_events();
3497 assert_eq!(events.len(), 3);
3498 // Check that Alice fails backward the pending HTLC from the second payment.
3500 Event::PaymentPathFailed { payment_hash, .. } => {
3501 assert_eq!(payment_hash, failed_payment_hash);
3503 _ => panic!("Unexpected event"),
3506 Event::PaymentFailed { payment_hash, .. } => {
3507 assert_eq!(payment_hash, failed_payment_hash);
3509 _ => panic!("Unexpected event"),
3512 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3513 assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3515 _ => panic!("Unexpected event {:?}", events[1]),
3517 check_closed_broadcast!(nodes[0], true);
3518 check_added_monitors!(nodes[0], 1);
3522 fn test_htlc_ignore_latest_remote_commitment() {
3523 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3524 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3525 let chanmon_cfgs = create_chanmon_cfgs(2);
3526 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3527 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3528 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3529 if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3530 // We rely on the ability to connect a block redundantly, which isn't allowed via
3531 // `chain::Listen`, so we never run the test if we randomly get assigned that
3535 create_announced_chan_between_nodes(&nodes, 0, 1);
3537 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3538 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3539 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3540 check_closed_broadcast!(nodes[0], true);
3541 check_added_monitors!(nodes[0], 1);
3542 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
3544 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3545 assert_eq!(node_txn.len(), 3);
3546 assert_eq!(node_txn[0].txid(), node_txn[1].txid());
3548 let block = create_dummy_block(nodes[1].best_block_hash(), 42, vec![node_txn[0].clone(), node_txn[1].clone()]);
3549 connect_block(&nodes[1], &block);
3550 check_closed_broadcast!(nodes[1], true);
3551 check_added_monitors!(nodes[1], 1);
3552 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
3554 // Duplicate the connect_block call since this may happen due to other listeners
3555 // registering new transactions
3556 connect_block(&nodes[1], &block);
3560 fn test_force_close_fail_back() {
3561 // Check which HTLCs are failed-backwards on channel force-closure
3562 let chanmon_cfgs = create_chanmon_cfgs(3);
3563 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3564 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3565 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3566 create_announced_chan_between_nodes(&nodes, 0, 1);
3567 create_announced_chan_between_nodes(&nodes, 1, 2);
3569 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3571 let mut payment_event = {
3572 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
3573 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3574 check_added_monitors!(nodes[0], 1);
3576 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3577 assert_eq!(events.len(), 1);
3578 SendEvent::from_event(events.remove(0))
3581 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3582 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3584 expect_pending_htlcs_forwardable!(nodes[1]);
3586 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3587 assert_eq!(events_2.len(), 1);
3588 payment_event = SendEvent::from_event(events_2.remove(0));
3589 assert_eq!(payment_event.msgs.len(), 1);
3591 check_added_monitors!(nodes[1], 1);
3592 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3593 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3594 check_added_monitors!(nodes[2], 1);
3595 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3597 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3598 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3599 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3601 nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3602 check_closed_broadcast!(nodes[2], true);
3603 check_added_monitors!(nodes[2], 1);
3604 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
3606 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3607 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3608 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3609 // back to nodes[1] upon timeout otherwise.
3610 assert_eq!(node_txn.len(), 1);
3614 mine_transaction(&nodes[1], &tx);
3616 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3617 check_closed_broadcast!(nodes[1], true);
3618 check_added_monitors!(nodes[1], 1);
3619 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
3621 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3623 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3624 .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);
3626 mine_transaction(&nodes[2], &tx);
3627 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3628 assert_eq!(node_txn.len(), 1);
3629 assert_eq!(node_txn[0].input.len(), 1);
3630 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3631 assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3632 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3634 check_spends!(node_txn[0], tx);
3638 fn test_dup_events_on_peer_disconnect() {
3639 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3640 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3641 // as we used to generate the event immediately upon receipt of the payment preimage in the
3642 // update_fulfill_htlc message.
3644 let chanmon_cfgs = create_chanmon_cfgs(2);
3645 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3646 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3647 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3648 create_announced_chan_between_nodes(&nodes, 0, 1);
3650 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3652 nodes[1].node.claim_funds(payment_preimage);
3653 expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3654 check_added_monitors!(nodes[1], 1);
3655 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3656 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3657 expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
3659 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3660 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3662 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3663 reconnect_args.pending_htlc_claims.0 = 1;
3664 reconnect_nodes(reconnect_args);
3665 expect_payment_path_successful!(nodes[0]);
3669 fn test_peer_disconnected_before_funding_broadcasted() {
3670 // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3671 // before the funding transaction has been broadcasted.
3672 let chanmon_cfgs = create_chanmon_cfgs(2);
3673 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3674 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3675 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3677 // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3678 // broadcasted, even though it's created by `nodes[0]`.
3679 let expected_temporary_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
3680 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3681 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
3682 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3683 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
3685 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3686 assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3688 assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3690 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3691 assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3693 // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3694 // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3697 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3700 // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3701 // disconnected before the funding transaction was broadcasted.
3702 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3703 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3705 check_closed_event!(&nodes[0], 1, ClosureReason::DisconnectedPeer, false
3706 , [nodes[1].node.get_our_node_id()], 1000000);
3707 check_closed_event!(&nodes[1], 1, ClosureReason::DisconnectedPeer, false
3708 , [nodes[0].node.get_our_node_id()], 1000000);
3712 fn test_simple_peer_disconnect() {
3713 // Test that we can reconnect when there are no lost messages
3714 let chanmon_cfgs = create_chanmon_cfgs(3);
3715 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3716 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3717 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3718 create_announced_chan_between_nodes(&nodes, 0, 1);
3719 create_announced_chan_between_nodes(&nodes, 1, 2);
3721 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3722 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3723 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3724 reconnect_args.send_channel_ready = (true, true);
3725 reconnect_nodes(reconnect_args);
3727 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3728 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3729 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3730 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3732 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3733 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3734 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3736 let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3737 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3738 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3739 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3741 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3742 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3744 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3745 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3747 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3748 reconnect_args.pending_cell_htlc_fails.0 = 1;
3749 reconnect_args.pending_cell_htlc_claims.0 = 1;
3750 reconnect_nodes(reconnect_args);
3752 let events = nodes[0].node.get_and_clear_pending_events();
3753 assert_eq!(events.len(), 4);
3755 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3756 assert_eq!(payment_preimage, payment_preimage_3);
3757 assert_eq!(payment_hash, payment_hash_3);
3759 _ => panic!("Unexpected event"),
3762 Event::PaymentPathSuccessful { .. } => {},
3763 _ => panic!("Unexpected event"),
3766 Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3767 assert_eq!(payment_hash, payment_hash_5);
3768 assert!(payment_failed_permanently);
3770 _ => panic!("Unexpected event"),
3773 Event::PaymentFailed { payment_hash, .. } => {
3774 assert_eq!(payment_hash, payment_hash_5);
3776 _ => panic!("Unexpected event"),
3779 check_added_monitors(&nodes[0], 1);
3781 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3782 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3785 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3786 // Test that we can reconnect when in-flight HTLC updates get dropped
3787 let chanmon_cfgs = create_chanmon_cfgs(2);
3788 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3789 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3790 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3792 let mut as_channel_ready = None;
3793 let channel_id = if messages_delivered == 0 {
3794 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3795 as_channel_ready = Some(channel_ready);
3796 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3797 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3798 // it before the channel_reestablish message.
3801 create_announced_chan_between_nodes(&nodes, 0, 1).2
3804 let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3806 let payment_event = {
3807 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
3808 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3809 check_added_monitors!(nodes[0], 1);
3811 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3812 assert_eq!(events.len(), 1);
3813 SendEvent::from_event(events.remove(0))
3815 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3817 if messages_delivered < 2 {
3818 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3820 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3821 if messages_delivered >= 3 {
3822 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3823 check_added_monitors!(nodes[1], 1);
3824 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3826 if messages_delivered >= 4 {
3827 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3828 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3829 check_added_monitors!(nodes[0], 1);
3831 if messages_delivered >= 5 {
3832 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3833 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3834 // No commitment_signed so get_event_msg's assert(len == 1) passes
3835 check_added_monitors!(nodes[0], 1);
3837 if messages_delivered >= 6 {
3838 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3839 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3840 check_added_monitors!(nodes[1], 1);
3847 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3848 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3849 if messages_delivered < 3 {
3850 if simulate_broken_lnd {
3851 // lnd has a long-standing bug where they send a channel_ready prior to a
3852 // channel_reestablish if you reconnect prior to channel_ready time.
3854 // Here we simulate that behavior, delivering a channel_ready immediately on
3855 // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3856 // in `reconnect_nodes` but we currently don't fail based on that.
3858 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3859 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3861 // Even if the channel_ready messages get exchanged, as long as nothing further was
3862 // received on either side, both sides will need to resend them.
3863 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3864 reconnect_args.send_channel_ready = (true, true);
3865 reconnect_args.pending_htlc_adds.1 = 1;
3866 reconnect_nodes(reconnect_args);
3867 } else if messages_delivered == 3 {
3868 // nodes[0] still wants its RAA + commitment_signed
3869 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3870 reconnect_args.pending_htlc_adds.0 = -1;
3871 reconnect_args.pending_raa.0 = true;
3872 reconnect_nodes(reconnect_args);
3873 } else if messages_delivered == 4 {
3874 // nodes[0] still wants its commitment_signed
3875 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3876 reconnect_args.pending_htlc_adds.0 = -1;
3877 reconnect_nodes(reconnect_args);
3878 } else if messages_delivered == 5 {
3879 // nodes[1] still wants its final RAA
3880 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3881 reconnect_args.pending_raa.1 = true;
3882 reconnect_nodes(reconnect_args);
3883 } else if messages_delivered == 6 {
3884 // Everything was delivered...
3885 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3888 let events_1 = nodes[1].node.get_and_clear_pending_events();
3889 if messages_delivered == 0 {
3890 assert_eq!(events_1.len(), 2);
3892 Event::ChannelReady { .. } => { },
3893 _ => panic!("Unexpected event"),
3896 Event::PendingHTLCsForwardable { .. } => { },
3897 _ => panic!("Unexpected event"),
3900 assert_eq!(events_1.len(), 1);
3902 Event::PendingHTLCsForwardable { .. } => { },
3903 _ => panic!("Unexpected event"),
3907 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3908 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3909 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3911 nodes[1].node.process_pending_htlc_forwards();
3913 let events_2 = nodes[1].node.get_and_clear_pending_events();
3914 assert_eq!(events_2.len(), 1);
3916 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
3917 assert_eq!(payment_hash_1, *payment_hash);
3918 assert_eq!(amount_msat, 1_000_000);
3919 assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3920 assert_eq!(via_channel_id, Some(channel_id));
3922 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3923 assert!(payment_preimage.is_none());
3924 assert_eq!(payment_secret_1, *payment_secret);
3926 _ => panic!("expected PaymentPurpose::InvoicePayment")
3929 _ => panic!("Unexpected event"),
3932 nodes[1].node.claim_funds(payment_preimage_1);
3933 check_added_monitors!(nodes[1], 1);
3934 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3936 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3937 assert_eq!(events_3.len(), 1);
3938 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3939 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3940 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3941 assert!(updates.update_add_htlcs.is_empty());
3942 assert!(updates.update_fail_htlcs.is_empty());
3943 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3944 assert!(updates.update_fail_malformed_htlcs.is_empty());
3945 assert!(updates.update_fee.is_none());
3946 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3948 _ => panic!("Unexpected event"),
3951 if messages_delivered >= 1 {
3952 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3954 let events_4 = nodes[0].node.get_and_clear_pending_events();
3955 assert_eq!(events_4.len(), 1);
3957 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3958 assert_eq!(payment_preimage_1, *payment_preimage);
3959 assert_eq!(payment_hash_1, *payment_hash);
3961 _ => panic!("Unexpected event"),
3964 if messages_delivered >= 2 {
3965 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3966 check_added_monitors!(nodes[0], 1);
3967 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3969 if messages_delivered >= 3 {
3970 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3971 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3972 check_added_monitors!(nodes[1], 1);
3974 if messages_delivered >= 4 {
3975 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3976 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3977 // No commitment_signed so get_event_msg's assert(len == 1) passes
3978 check_added_monitors!(nodes[1], 1);
3980 if messages_delivered >= 5 {
3981 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3982 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3983 check_added_monitors!(nodes[0], 1);
3990 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3991 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3992 if messages_delivered < 2 {
3993 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3994 reconnect_args.pending_htlc_claims.0 = 1;
3995 reconnect_nodes(reconnect_args);
3996 if messages_delivered < 1 {
3997 expect_payment_sent!(nodes[0], payment_preimage_1);
3999 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4001 } else if messages_delivered == 2 {
4002 // nodes[0] still wants its RAA + commitment_signed
4003 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4004 reconnect_args.pending_htlc_adds.1 = -1;
4005 reconnect_args.pending_raa.1 = true;
4006 reconnect_nodes(reconnect_args);
4007 } else if messages_delivered == 3 {
4008 // nodes[0] still wants its commitment_signed
4009 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4010 reconnect_args.pending_htlc_adds.1 = -1;
4011 reconnect_nodes(reconnect_args);
4012 } else if messages_delivered == 4 {
4013 // nodes[1] still wants its final RAA
4014 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4015 reconnect_args.pending_raa.0 = true;
4016 reconnect_nodes(reconnect_args);
4017 } else if messages_delivered == 5 {
4018 // Everything was delivered...
4019 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
4022 if messages_delivered == 1 || messages_delivered == 2 {
4023 expect_payment_path_successful!(nodes[0]);
4025 if messages_delivered <= 5 {
4026 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4027 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4029 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
4031 if messages_delivered > 2 {
4032 expect_payment_path_successful!(nodes[0]);
4035 // Channel should still work fine...
4036 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4037 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
4038 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4042 fn test_drop_messages_peer_disconnect_a() {
4043 do_test_drop_messages_peer_disconnect(0, true);
4044 do_test_drop_messages_peer_disconnect(0, false);
4045 do_test_drop_messages_peer_disconnect(1, false);
4046 do_test_drop_messages_peer_disconnect(2, false);
4050 fn test_drop_messages_peer_disconnect_b() {
4051 do_test_drop_messages_peer_disconnect(3, false);
4052 do_test_drop_messages_peer_disconnect(4, false);
4053 do_test_drop_messages_peer_disconnect(5, false);
4054 do_test_drop_messages_peer_disconnect(6, false);
4058 fn test_channel_ready_without_best_block_updated() {
4059 // Previously, if we were offline when a funding transaction was locked in, and then we came
4060 // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
4061 // generate a channel_ready until a later best_block_updated. This tests that we generate the
4062 // channel_ready immediately instead.
4063 let chanmon_cfgs = create_chanmon_cfgs(2);
4064 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4065 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4066 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4067 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
4069 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
4071 let conf_height = nodes[0].best_block_info().1 + 1;
4072 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4073 let block_txn = [funding_tx];
4074 let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
4075 let conf_block_header = nodes[0].get_block_header(conf_height);
4076 nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
4078 // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4079 let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4080 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4084 fn test_drop_messages_peer_disconnect_dual_htlc() {
4085 // Test that we can handle reconnecting when both sides of a channel have pending
4086 // commitment_updates when we disconnect.
4087 let chanmon_cfgs = create_chanmon_cfgs(2);
4088 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4089 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4090 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4091 create_announced_chan_between_nodes(&nodes, 0, 1);
4093 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
4095 // Now try to send a second payment which will fail to send
4096 let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4097 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
4098 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
4099 check_added_monitors!(nodes[0], 1);
4101 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4102 assert_eq!(events_1.len(), 1);
4104 MessageSendEvent::UpdateHTLCs { .. } => {},
4105 _ => panic!("Unexpected event"),
4108 nodes[1].node.claim_funds(payment_preimage_1);
4109 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4110 check_added_monitors!(nodes[1], 1);
4112 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4113 assert_eq!(events_2.len(), 1);
4115 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 } } => {
4116 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4117 assert!(update_add_htlcs.is_empty());
4118 assert_eq!(update_fulfill_htlcs.len(), 1);
4119 assert!(update_fail_htlcs.is_empty());
4120 assert!(update_fail_malformed_htlcs.is_empty());
4121 assert!(update_fee.is_none());
4123 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4124 let events_3 = nodes[0].node.get_and_clear_pending_events();
4125 assert_eq!(events_3.len(), 1);
4127 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4128 assert_eq!(*payment_preimage, payment_preimage_1);
4129 assert_eq!(*payment_hash, payment_hash_1);
4131 _ => panic!("Unexpected event"),
4134 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4135 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4136 // No commitment_signed so get_event_msg's assert(len == 1) passes
4137 check_added_monitors!(nodes[0], 1);
4139 _ => panic!("Unexpected event"),
4142 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4143 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4145 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
4146 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
4148 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4149 assert_eq!(reestablish_1.len(), 1);
4150 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
4151 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
4153 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4154 assert_eq!(reestablish_2.len(), 1);
4156 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4157 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4158 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4159 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4161 assert!(as_resp.0.is_none());
4162 assert!(bs_resp.0.is_none());
4164 assert!(bs_resp.1.is_none());
4165 assert!(bs_resp.2.is_none());
4167 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4169 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4170 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4171 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4172 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4173 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4174 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4175 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4176 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4177 // No commitment_signed so get_event_msg's assert(len == 1) passes
4178 check_added_monitors!(nodes[1], 1);
4180 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4181 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4182 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4183 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4184 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4185 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4186 assert!(bs_second_commitment_signed.update_fee.is_none());
4187 check_added_monitors!(nodes[1], 1);
4189 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4190 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4191 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4192 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4193 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4194 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4195 assert!(as_commitment_signed.update_fee.is_none());
4196 check_added_monitors!(nodes[0], 1);
4198 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4199 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4200 // No commitment_signed so get_event_msg's assert(len == 1) passes
4201 check_added_monitors!(nodes[0], 1);
4203 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4204 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4205 // No commitment_signed so get_event_msg's assert(len == 1) passes
4206 check_added_monitors!(nodes[1], 1);
4208 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4209 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4210 check_added_monitors!(nodes[1], 1);
4212 expect_pending_htlcs_forwardable!(nodes[1]);
4214 let events_5 = nodes[1].node.get_and_clear_pending_events();
4215 assert_eq!(events_5.len(), 1);
4217 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4218 assert_eq!(payment_hash_2, *payment_hash);
4220 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4221 assert!(payment_preimage.is_none());
4222 assert_eq!(payment_secret_2, *payment_secret);
4224 _ => panic!("expected PaymentPurpose::InvoicePayment")
4227 _ => panic!("Unexpected event"),
4230 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4231 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4232 check_added_monitors!(nodes[0], 1);
4234 expect_payment_path_successful!(nodes[0]);
4235 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4238 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4239 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4240 // to avoid our counterparty failing the channel.
4241 let chanmon_cfgs = create_chanmon_cfgs(2);
4242 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4243 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4244 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4246 create_announced_chan_between_nodes(&nodes, 0, 1);
4248 let our_payment_hash = if send_partial_mpp {
4249 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4250 // Use the utility function send_payment_along_path to send the payment with MPP data which
4251 // indicates there are more HTLCs coming.
4252 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.
4253 let payment_id = PaymentId([42; 32]);
4254 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
4255 RecipientOnionFields::secret_only(payment_secret), payment_id, &route).unwrap();
4256 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
4257 RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id,
4258 &None, session_privs[0]).unwrap();
4259 check_added_monitors!(nodes[0], 1);
4260 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4261 assert_eq!(events.len(), 1);
4262 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4263 // hop should *not* yet generate any PaymentClaimable event(s).
4264 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4267 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4270 let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
4271 connect_block(&nodes[0], &block);
4272 connect_block(&nodes[1], &block);
4273 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4274 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4275 block.header.prev_blockhash = block.block_hash();
4276 connect_block(&nodes[0], &block);
4277 connect_block(&nodes[1], &block);
4280 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4282 check_added_monitors!(nodes[1], 1);
4283 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4284 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4285 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4286 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4287 assert!(htlc_timeout_updates.update_fee.is_none());
4289 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4290 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4291 // 100_000 msat as u64, followed by the height at which we failed back above
4292 let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4293 expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4294 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4298 fn test_htlc_timeout() {
4299 do_test_htlc_timeout(true);
4300 do_test_htlc_timeout(false);
4303 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4304 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4305 let chanmon_cfgs = create_chanmon_cfgs(3);
4306 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4307 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4308 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4309 create_announced_chan_between_nodes(&nodes, 0, 1);
4310 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4312 // Make sure all nodes are at the same starting height
4313 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4314 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4315 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4317 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4318 let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4319 nodes[1].node.send_payment_with_route(&route, first_payment_hash,
4320 RecipientOnionFields::secret_only(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4321 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4322 check_added_monitors!(nodes[1], 1);
4324 // Now attempt to route a second payment, which should be placed in the holding cell
4325 let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4326 let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4327 sending_node.node.send_payment_with_route(&route, second_payment_hash,
4328 RecipientOnionFields::secret_only(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4330 check_added_monitors!(nodes[0], 1);
4331 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4332 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4333 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4334 expect_pending_htlcs_forwardable!(nodes[1]);
4336 check_added_monitors!(nodes[1], 0);
4338 connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4339 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4340 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4341 connect_blocks(&nodes[1], 1);
4344 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 }]);
4345 check_added_monitors!(nodes[1], 1);
4346 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4347 assert_eq!(fail_commit.len(), 1);
4348 match fail_commit[0] {
4349 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4350 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4351 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4353 _ => unreachable!(),
4355 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4357 expect_payment_failed!(nodes[1], second_payment_hash, false);
4362 fn test_holding_cell_htlc_add_timeouts() {
4363 do_test_holding_cell_htlc_add_timeouts(false);
4364 do_test_holding_cell_htlc_add_timeouts(true);
4367 macro_rules! check_spendable_outputs {
4368 ($node: expr, $keysinterface: expr) => {
4370 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4371 let mut txn = Vec::new();
4372 let mut all_outputs = Vec::new();
4373 let secp_ctx = Secp256k1::new();
4374 for event in events.drain(..) {
4376 Event::SpendableOutputs { mut outputs, channel_id: _ } => {
4377 for outp in outputs.drain(..) {
4378 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());
4379 all_outputs.push(outp);
4382 _ => panic!("Unexpected event"),
4385 if all_outputs.len() > 1 {
4386 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) {
4396 fn test_claim_sizeable_push_msat() {
4397 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4398 let chanmon_cfgs = create_chanmon_cfgs(2);
4399 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4400 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4401 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4403 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4404 nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4405 check_closed_broadcast!(nodes[1], true);
4406 check_added_monitors!(nodes[1], 1);
4407 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[0].node.get_our_node_id()], 100000);
4408 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4409 assert_eq!(node_txn.len(), 1);
4410 check_spends!(node_txn[0], chan.3);
4411 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
4413 mine_transaction(&nodes[1], &node_txn[0]);
4414 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4416 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4417 assert_eq!(spend_txn.len(), 1);
4418 assert_eq!(spend_txn[0].input.len(), 1);
4419 check_spends!(spend_txn[0], node_txn[0]);
4420 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4424 fn test_claim_on_remote_sizeable_push_msat() {
4425 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4426 // to_remote output is encumbered by a P2WPKH
4427 let chanmon_cfgs = create_chanmon_cfgs(2);
4428 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4429 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4430 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4432 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4433 nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4434 check_closed_broadcast!(nodes[0], true);
4435 check_added_monitors!(nodes[0], 1);
4436 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
4438 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4439 assert_eq!(node_txn.len(), 1);
4440 check_spends!(node_txn[0], chan.3);
4441 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
4443 mine_transaction(&nodes[1], &node_txn[0]);
4444 check_closed_broadcast!(nodes[1], true);
4445 check_added_monitors!(nodes[1], 1);
4446 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4447 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4449 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4450 assert_eq!(spend_txn.len(), 1);
4451 check_spends!(spend_txn[0], node_txn[0]);
4455 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4456 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4457 // to_remote output is encumbered by a P2WPKH
4459 let chanmon_cfgs = create_chanmon_cfgs(2);
4460 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4461 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4462 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4464 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4465 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4466 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4467 assert_eq!(revoked_local_txn[0].input.len(), 1);
4468 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4470 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4471 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4472 check_closed_broadcast!(nodes[1], true);
4473 check_added_monitors!(nodes[1], 1);
4474 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4476 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4477 mine_transaction(&nodes[1], &node_txn[0]);
4478 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4480 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4481 assert_eq!(spend_txn.len(), 3);
4482 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4483 check_spends!(spend_txn[1], node_txn[0]);
4484 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4488 fn test_static_spendable_outputs_preimage_tx() {
4489 let chanmon_cfgs = create_chanmon_cfgs(2);
4490 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4491 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4492 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4494 // Create some initial channels
4495 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4497 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4499 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4500 assert_eq!(commitment_tx[0].input.len(), 1);
4501 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4503 // Settle A's commitment tx on B's chain
4504 nodes[1].node.claim_funds(payment_preimage);
4505 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4506 check_added_monitors!(nodes[1], 1);
4507 mine_transaction(&nodes[1], &commitment_tx[0]);
4508 check_added_monitors!(nodes[1], 1);
4509 let events = nodes[1].node.get_and_clear_pending_msg_events();
4511 MessageSendEvent::UpdateHTLCs { .. } => {},
4512 _ => panic!("Unexpected event"),
4515 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4516 _ => panic!("Unexepected event"),
4519 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4520 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4521 assert_eq!(node_txn.len(), 1);
4522 check_spends!(node_txn[0], commitment_tx[0]);
4523 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4525 mine_transaction(&nodes[1], &node_txn[0]);
4526 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4527 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4529 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4530 assert_eq!(spend_txn.len(), 1);
4531 check_spends!(spend_txn[0], node_txn[0]);
4535 fn test_static_spendable_outputs_timeout_tx() {
4536 let chanmon_cfgs = create_chanmon_cfgs(2);
4537 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4538 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4539 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4541 // Create some initial channels
4542 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4544 // Rebalance the network a bit by relaying one payment through all the channels ...
4545 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4547 let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4549 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4550 assert_eq!(commitment_tx[0].input.len(), 1);
4551 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4553 // Settle A's commitment tx on B' chain
4554 mine_transaction(&nodes[1], &commitment_tx[0]);
4555 check_added_monitors!(nodes[1], 1);
4556 let events = nodes[1].node.get_and_clear_pending_msg_events();
4558 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4559 _ => panic!("Unexpected event"),
4561 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4563 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4564 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4565 assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4566 check_spends!(node_txn[0], commitment_tx[0].clone());
4567 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4569 mine_transaction(&nodes[1], &node_txn[0]);
4570 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4571 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4572 expect_payment_failed!(nodes[1], our_payment_hash, false);
4574 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4575 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4576 check_spends!(spend_txn[0], commitment_tx[0]);
4577 check_spends!(spend_txn[1], node_txn[0]);
4578 check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4582 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4583 let chanmon_cfgs = create_chanmon_cfgs(2);
4584 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4585 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4586 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4588 // Create some initial channels
4589 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4591 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4592 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4593 assert_eq!(revoked_local_txn[0].input.len(), 1);
4594 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4596 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4598 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4599 check_closed_broadcast!(nodes[1], true);
4600 check_added_monitors!(nodes[1], 1);
4601 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4603 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4604 assert_eq!(node_txn.len(), 1);
4605 assert_eq!(node_txn[0].input.len(), 2);
4606 check_spends!(node_txn[0], revoked_local_txn[0]);
4608 mine_transaction(&nodes[1], &node_txn[0]);
4609 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4611 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4612 assert_eq!(spend_txn.len(), 1);
4613 check_spends!(spend_txn[0], node_txn[0]);
4617 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4618 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4619 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4620 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4621 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4622 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4624 // Create some initial channels
4625 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4627 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4628 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4629 assert_eq!(revoked_local_txn[0].input.len(), 1);
4630 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4632 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4634 // A will generate HTLC-Timeout from revoked commitment tx
4635 mine_transaction(&nodes[0], &revoked_local_txn[0]);
4636 check_closed_broadcast!(nodes[0], true);
4637 check_added_monitors!(nodes[0], 1);
4638 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4639 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4641 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4642 assert_eq!(revoked_htlc_txn.len(), 1);
4643 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4644 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4645 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4646 assert_ne!(revoked_htlc_txn[0].lock_time.0, 0); // HTLC-Timeout
4648 // B will generate justice tx from A's revoked commitment/HTLC tx
4649 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4650 check_closed_broadcast!(nodes[1], true);
4651 check_added_monitors!(nodes[1], 1);
4652 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4654 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4655 assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4656 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4657 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4658 // transactions next...
4659 assert_eq!(node_txn[0].input.len(), 3);
4660 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4662 assert_eq!(node_txn[1].input.len(), 2);
4663 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4664 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4665 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4667 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4668 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4671 mine_transaction(&nodes[1], &node_txn[1]);
4672 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4674 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4675 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4676 assert_eq!(spend_txn.len(), 1);
4677 assert_eq!(spend_txn[0].input.len(), 1);
4678 check_spends!(spend_txn[0], node_txn[1]);
4682 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4683 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4684 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4685 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4686 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4687 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4689 // Create some initial channels
4690 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4692 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4693 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4694 assert_eq!(revoked_local_txn[0].input.len(), 1);
4695 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4697 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4698 assert_eq!(revoked_local_txn[0].output.len(), 2);
4700 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4702 // B will generate HTLC-Success from revoked commitment tx
4703 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4704 check_closed_broadcast!(nodes[1], true);
4705 check_added_monitors!(nodes[1], 1);
4706 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4707 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4709 assert_eq!(revoked_htlc_txn.len(), 1);
4710 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4711 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4712 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4714 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4715 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4716 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4718 // A will generate justice tx from B's revoked commitment/HTLC tx
4719 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4720 check_closed_broadcast!(nodes[0], true);
4721 check_added_monitors!(nodes[0], 1);
4722 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4724 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4725 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4727 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4728 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4729 // transactions next...
4730 assert_eq!(node_txn[0].input.len(), 2);
4731 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4732 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4733 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4735 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4736 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4739 assert_eq!(node_txn[1].input.len(), 1);
4740 check_spends!(node_txn[1], revoked_htlc_txn[0]);
4742 mine_transaction(&nodes[0], &node_txn[1]);
4743 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4745 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4746 // didn't try to generate any new transactions.
4748 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4749 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4750 assert_eq!(spend_txn.len(), 3);
4751 assert_eq!(spend_txn[0].input.len(), 1);
4752 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4753 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4754 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4755 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4759 fn test_onchain_to_onchain_claim() {
4760 // Test that in case of channel closure, we detect the state of output and claim HTLC
4761 // on downstream peer's remote commitment tx.
4762 // First, have C claim an HTLC against its own latest commitment transaction.
4763 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4765 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4768 let chanmon_cfgs = create_chanmon_cfgs(3);
4769 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4770 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4771 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4773 // Create some initial channels
4774 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4775 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4777 // Ensure all nodes are at the same height
4778 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4779 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4780 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4781 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4783 // Rebalance the network a bit by relaying one payment through all the channels ...
4784 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4785 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4787 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4788 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4789 check_spends!(commitment_tx[0], chan_2.3);
4790 nodes[2].node.claim_funds(payment_preimage);
4791 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4792 check_added_monitors!(nodes[2], 1);
4793 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4794 assert!(updates.update_add_htlcs.is_empty());
4795 assert!(updates.update_fail_htlcs.is_empty());
4796 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4797 assert!(updates.update_fail_malformed_htlcs.is_empty());
4799 mine_transaction(&nodes[2], &commitment_tx[0]);
4800 check_closed_broadcast!(nodes[2], true);
4801 check_added_monitors!(nodes[2], 1);
4802 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4804 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4805 assert_eq!(c_txn.len(), 1);
4806 check_spends!(c_txn[0], commitment_tx[0]);
4807 assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4808 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4809 assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
4811 // 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
4812 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![commitment_tx[0].clone(), c_txn[0].clone()]));
4813 check_added_monitors!(nodes[1], 1);
4814 let events = nodes[1].node.get_and_clear_pending_events();
4815 assert_eq!(events.len(), 2);
4817 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4818 _ => panic!("Unexpected event"),
4821 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
4822 assert_eq!(fee_earned_msat, Some(1000));
4823 assert_eq!(prev_channel_id, Some(chan_1.2));
4824 assert_eq!(claim_from_onchain_tx, true);
4825 assert_eq!(next_channel_id, Some(chan_2.2));
4826 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
4828 _ => panic!("Unexpected event"),
4830 check_added_monitors!(nodes[1], 1);
4831 let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4832 assert_eq!(msg_events.len(), 3);
4833 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut msg_events);
4834 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut msg_events);
4836 match nodes_2_event {
4837 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
4838 _ => panic!("Unexpected event"),
4841 match nodes_0_event {
4842 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, .. } } => {
4843 assert!(update_add_htlcs.is_empty());
4844 assert!(update_fail_htlcs.is_empty());
4845 assert_eq!(update_fulfill_htlcs.len(), 1);
4846 assert!(update_fail_malformed_htlcs.is_empty());
4847 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4849 _ => panic!("Unexpected event"),
4852 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
4853 match msg_events[0] {
4854 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4855 _ => panic!("Unexpected event"),
4858 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4859 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4860 mine_transaction(&nodes[1], &commitment_tx[0]);
4861 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4862 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4863 // ChannelMonitor: HTLC-Success tx
4864 assert_eq!(b_txn.len(), 1);
4865 check_spends!(b_txn[0], commitment_tx[0]);
4866 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4867 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4868 assert_eq!(b_txn[0].lock_time.0, nodes[1].best_block_info().1); // Success tx
4870 check_closed_broadcast!(nodes[1], true);
4871 check_added_monitors!(nodes[1], 1);
4875 fn test_duplicate_payment_hash_one_failure_one_success() {
4876 // Topology : A --> B --> C --> D
4877 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4878 // Note that because C will refuse to generate two payment secrets for the same payment hash,
4879 // we forward one of the payments onwards to D.
4880 let chanmon_cfgs = create_chanmon_cfgs(4);
4881 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4882 // When this test was written, the default base fee floated based on the HTLC count.
4883 // It is now fixed, so we simply set the fee to the expected value here.
4884 let mut config = test_default_channel_config();
4885 config.channel_config.forwarding_fee_base_msat = 196;
4886 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4887 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4888 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4890 create_announced_chan_between_nodes(&nodes, 0, 1);
4891 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4892 create_announced_chan_between_nodes(&nodes, 2, 3);
4894 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4895 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4896 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4897 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4898 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4900 let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
4902 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
4903 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4904 // script push size limit so that the below script length checks match
4905 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
4906 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV - 40)
4907 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
4908 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000);
4909 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
4911 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4912 assert_eq!(commitment_txn[0].input.len(), 1);
4913 check_spends!(commitment_txn[0], chan_2.3);
4915 mine_transaction(&nodes[1], &commitment_txn[0]);
4916 check_closed_broadcast!(nodes[1], true);
4917 check_added_monitors!(nodes[1], 1);
4918 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
4919 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
4921 let htlc_timeout_tx;
4922 { // Extract one of the two HTLC-Timeout transaction
4923 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4924 // ChannelMonitor: timeout tx * 2-or-3
4925 assert!(node_txn.len() == 2 || node_txn.len() == 3);
4927 check_spends!(node_txn[0], commitment_txn[0]);
4928 assert_eq!(node_txn[0].input.len(), 1);
4929 assert_eq!(node_txn[0].output.len(), 1);
4931 if node_txn.len() > 2 {
4932 check_spends!(node_txn[1], commitment_txn[0]);
4933 assert_eq!(node_txn[1].input.len(), 1);
4934 assert_eq!(node_txn[1].output.len(), 1);
4935 assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4937 check_spends!(node_txn[2], commitment_txn[0]);
4938 assert_eq!(node_txn[2].input.len(), 1);
4939 assert_eq!(node_txn[2].output.len(), 1);
4940 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
4942 check_spends!(node_txn[1], commitment_txn[0]);
4943 assert_eq!(node_txn[1].input.len(), 1);
4944 assert_eq!(node_txn[1].output.len(), 1);
4945 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4948 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4949 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4950 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
4951 // (with value 900 sats) will be claimed in the below `claim_funds` call.
4952 if node_txn.len() > 2 {
4953 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4954 htlc_timeout_tx = if node_txn[2].output[0].value < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
4956 htlc_timeout_tx = if node_txn[0].output[0].value < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
4960 nodes[2].node.claim_funds(our_payment_preimage);
4961 expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
4963 mine_transaction(&nodes[2], &commitment_txn[0]);
4964 check_added_monitors!(nodes[2], 2);
4965 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4966 let events = nodes[2].node.get_and_clear_pending_msg_events();
4968 MessageSendEvent::UpdateHTLCs { .. } => {},
4969 _ => panic!("Unexpected event"),
4972 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4973 _ => panic!("Unexepected event"),
4975 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4976 assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
4977 check_spends!(htlc_success_txn[0], commitment_txn[0]);
4978 check_spends!(htlc_success_txn[1], commitment_txn[0]);
4979 assert_eq!(htlc_success_txn[0].input.len(), 1);
4980 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4981 assert_eq!(htlc_success_txn[1].input.len(), 1);
4982 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4983 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
4984 assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
4986 mine_transaction(&nodes[1], &htlc_timeout_tx);
4987 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4988 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 }]);
4989 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4990 assert!(htlc_updates.update_add_htlcs.is_empty());
4991 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4992 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
4993 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4994 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4995 check_added_monitors!(nodes[1], 1);
4997 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4998 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5000 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5002 expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5004 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5005 mine_transaction(&nodes[1], &htlc_success_txn[1]);
5006 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
5007 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5008 assert!(updates.update_add_htlcs.is_empty());
5009 assert!(updates.update_fail_htlcs.is_empty());
5010 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5011 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5012 assert!(updates.update_fail_malformed_htlcs.is_empty());
5013 check_added_monitors!(nodes[1], 1);
5015 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5016 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5017 expect_payment_sent(&nodes[0], our_payment_preimage, None, true, true);
5021 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5022 let chanmon_cfgs = create_chanmon_cfgs(2);
5023 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5024 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5025 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5027 // Create some initial channels
5028 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5030 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
5031 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5032 assert_eq!(local_txn.len(), 1);
5033 assert_eq!(local_txn[0].input.len(), 1);
5034 check_spends!(local_txn[0], chan_1.3);
5036 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5037 nodes[1].node.claim_funds(payment_preimage);
5038 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
5039 check_added_monitors!(nodes[1], 1);
5041 mine_transaction(&nodes[1], &local_txn[0]);
5042 check_added_monitors!(nodes[1], 1);
5043 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
5044 let events = nodes[1].node.get_and_clear_pending_msg_events();
5046 MessageSendEvent::UpdateHTLCs { .. } => {},
5047 _ => panic!("Unexpected event"),
5050 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5051 _ => panic!("Unexepected event"),
5054 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5055 assert_eq!(node_txn.len(), 1);
5056 assert_eq!(node_txn[0].input.len(), 1);
5057 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5058 check_spends!(node_txn[0], local_txn[0]);
5062 mine_transaction(&nodes[1], &node_tx);
5063 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5065 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5066 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5067 assert_eq!(spend_txn.len(), 1);
5068 assert_eq!(spend_txn[0].input.len(), 1);
5069 check_spends!(spend_txn[0], node_tx);
5070 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5073 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5074 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5075 // unrevoked commitment transaction.
5076 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5077 // a remote RAA before they could be failed backwards (and combinations thereof).
5078 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5079 // use the same payment hashes.
5080 // Thus, we use a six-node network:
5085 // And test where C fails back to A/B when D announces its latest commitment transaction
5086 let chanmon_cfgs = create_chanmon_cfgs(6);
5087 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5088 // When this test was written, the default base fee floated based on the HTLC count.
5089 // It is now fixed, so we simply set the fee to the expected value here.
5090 let mut config = test_default_channel_config();
5091 config.channel_config.forwarding_fee_base_msat = 196;
5092 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5093 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5094 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5096 let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2);
5097 let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5098 let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5099 let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
5100 let chan_3_5 = create_announced_chan_between_nodes(&nodes, 3, 5);
5102 // Rebalance and check output sanity...
5103 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5104 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5105 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
5107 let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
5108 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().context.holder_dust_limit_satoshis;
5110 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
5112 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
5113 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5115 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
5117 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
5119 let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5121 let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5122 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5124 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());
5126 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());
5129 let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5131 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5132 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
5135 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
5137 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5138 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());
5140 // Double-check that six of the new HTLC were added
5141 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5142 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5143 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5144 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5146 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5147 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5148 nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5149 nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5150 nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5151 nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5152 check_added_monitors!(nodes[4], 0);
5154 let failed_destinations = vec![
5155 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5156 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5157 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5158 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5160 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5161 check_added_monitors!(nodes[4], 1);
5163 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5164 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5165 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5166 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5167 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5168 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5170 // Fail 3rd below-dust and 7th above-dust HTLCs
5171 nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5172 nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5173 check_added_monitors!(nodes[5], 0);
5175 let failed_destinations_2 = vec![
5176 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5177 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5179 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5180 check_added_monitors!(nodes[5], 1);
5182 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5183 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5184 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5185 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5187 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5189 // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5190 let failed_destinations_3 = vec![
5191 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5192 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5193 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5194 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5195 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5196 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5198 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5199 check_added_monitors!(nodes[3], 1);
5200 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5201 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5202 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5203 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5204 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5205 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5206 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5207 if deliver_last_raa {
5208 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5210 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5213 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5214 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5215 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5216 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5218 // We now broadcast the latest commitment transaction, which *should* result in failures for
5219 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5220 // the non-broadcast above-dust HTLCs.
5222 // Alternatively, we may broadcast the previous commitment transaction, which should only
5223 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5224 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5226 if announce_latest {
5227 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5229 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5231 let events = nodes[2].node.get_and_clear_pending_events();
5232 let close_event = if deliver_last_raa {
5233 assert_eq!(events.len(), 2 + 6);
5234 events.last().clone().unwrap()
5236 assert_eq!(events.len(), 1);
5237 events.last().clone().unwrap()
5240 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5241 _ => panic!("Unexpected event"),
5244 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5245 check_closed_broadcast!(nodes[2], true);
5246 if deliver_last_raa {
5247 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5249 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();
5250 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5252 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5253 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5255 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5258 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5260 check_added_monitors!(nodes[2], 3);
5262 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5263 assert_eq!(cs_msgs.len(), 2);
5264 let mut a_done = false;
5265 for msg in cs_msgs {
5267 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5268 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5269 // should be failed-backwards here.
5270 let target = if *node_id == nodes[0].node.get_our_node_id() {
5271 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5272 for htlc in &updates.update_fail_htlcs {
5273 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 });
5275 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5280 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5281 for htlc in &updates.update_fail_htlcs {
5282 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5284 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5285 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5288 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5289 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5290 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5291 if announce_latest {
5292 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5293 if *node_id == nodes[0].node.get_our_node_id() {
5294 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5297 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5299 _ => panic!("Unexpected event"),
5303 let as_events = nodes[0].node.get_and_clear_pending_events();
5304 assert_eq!(as_events.len(), if announce_latest { 10 } else { 6 });
5305 let mut as_failds = HashSet::new();
5306 let mut as_updates = 0;
5307 for event in as_events.iter() {
5308 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5309 assert!(as_failds.insert(*payment_hash));
5310 if *payment_hash != payment_hash_2 {
5311 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5313 assert!(!payment_failed_permanently);
5315 if let PathFailure::OnPath { network_update: Some(_) } = failure {
5318 } else if let &Event::PaymentFailed { .. } = event {
5319 } else { panic!("Unexpected event"); }
5321 assert!(as_failds.contains(&payment_hash_1));
5322 assert!(as_failds.contains(&payment_hash_2));
5323 if announce_latest {
5324 assert!(as_failds.contains(&payment_hash_3));
5325 assert!(as_failds.contains(&payment_hash_5));
5327 assert!(as_failds.contains(&payment_hash_6));
5329 let bs_events = nodes[1].node.get_and_clear_pending_events();
5330 assert_eq!(bs_events.len(), if announce_latest { 8 } else { 6 });
5331 let mut bs_failds = HashSet::new();
5332 let mut bs_updates = 0;
5333 for event in bs_events.iter() {
5334 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5335 assert!(bs_failds.insert(*payment_hash));
5336 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5337 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5339 assert!(!payment_failed_permanently);
5341 if let PathFailure::OnPath { network_update: Some(_) } = failure {
5344 } else if let &Event::PaymentFailed { .. } = event {
5345 } else { panic!("Unexpected event"); }
5347 assert!(bs_failds.contains(&payment_hash_1));
5348 assert!(bs_failds.contains(&payment_hash_2));
5349 if announce_latest {
5350 assert!(bs_failds.contains(&payment_hash_4));
5352 assert!(bs_failds.contains(&payment_hash_5));
5354 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5355 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5356 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5357 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5358 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5359 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5363 fn test_fail_backwards_latest_remote_announce_a() {
5364 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5368 fn test_fail_backwards_latest_remote_announce_b() {
5369 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5373 fn test_fail_backwards_previous_remote_announce() {
5374 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5375 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5376 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5380 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5381 let chanmon_cfgs = create_chanmon_cfgs(2);
5382 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5383 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5384 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5386 // Create some initial channels
5387 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5389 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5390 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5391 assert_eq!(local_txn[0].input.len(), 1);
5392 check_spends!(local_txn[0], chan_1.3);
5394 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5395 mine_transaction(&nodes[0], &local_txn[0]);
5396 check_closed_broadcast!(nodes[0], true);
5397 check_added_monitors!(nodes[0], 1);
5398 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5399 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5401 let htlc_timeout = {
5402 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5403 assert_eq!(node_txn.len(), 1);
5404 assert_eq!(node_txn[0].input.len(), 1);
5405 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5406 check_spends!(node_txn[0], local_txn[0]);
5410 mine_transaction(&nodes[0], &htlc_timeout);
5411 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5412 expect_payment_failed!(nodes[0], our_payment_hash, false);
5414 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5415 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5416 assert_eq!(spend_txn.len(), 3);
5417 check_spends!(spend_txn[0], local_txn[0]);
5418 assert_eq!(spend_txn[1].input.len(), 1);
5419 check_spends!(spend_txn[1], htlc_timeout);
5420 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5421 assert_eq!(spend_txn[2].input.len(), 2);
5422 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5423 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5424 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5428 fn test_key_derivation_params() {
5429 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5430 // manager rotation to test that `channel_keys_id` returned in
5431 // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5432 // then derive a `delayed_payment_key`.
5434 let chanmon_cfgs = create_chanmon_cfgs(3);
5436 // We manually create the node configuration to backup the seed.
5437 let seed = [42; 32];
5438 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5439 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);
5440 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[0].logger));
5441 let scorer = RwLock::new(test_utils::TestScorer::new());
5442 let router = test_utils::TestRouter::new(network_graph.clone(), &scorer);
5443 let node = NodeCfg { chain_source: &chanmon_cfgs[0].chain_source, logger: &chanmon_cfgs[0].logger, tx_broadcaster: &chanmon_cfgs[0].tx_broadcaster, fee_estimator: &chanmon_cfgs[0].fee_estimator, router, chain_monitor, keys_manager: &keys_manager, network_graph, node_seed: seed, override_init_features: alloc::rc::Rc::new(core::cell::RefCell::new(None)) };
5444 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5445 node_cfgs.remove(0);
5446 node_cfgs.insert(0, node);
5448 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5449 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5451 // Create some initial channels
5452 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5454 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2);
5455 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5456 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5458 // Ensure all nodes are at the same height
5459 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5460 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5461 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5462 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5464 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5465 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5466 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5467 assert_eq!(local_txn_1[0].input.len(), 1);
5468 check_spends!(local_txn_1[0], chan_1.3);
5470 // We check funding pubkey are unique
5471 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]));
5472 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]));
5473 if from_0_funding_key_0 == from_1_funding_key_0
5474 || from_0_funding_key_0 == from_1_funding_key_1
5475 || from_0_funding_key_1 == from_1_funding_key_0
5476 || from_0_funding_key_1 == from_1_funding_key_1 {
5477 panic!("Funding pubkeys aren't unique");
5480 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5481 mine_transaction(&nodes[0], &local_txn_1[0]);
5482 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5483 check_closed_broadcast!(nodes[0], true);
5484 check_added_monitors!(nodes[0], 1);
5485 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5487 let htlc_timeout = {
5488 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5489 assert_eq!(node_txn.len(), 1);
5490 assert_eq!(node_txn[0].input.len(), 1);
5491 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5492 check_spends!(node_txn[0], local_txn_1[0]);
5496 mine_transaction(&nodes[0], &htlc_timeout);
5497 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5498 expect_payment_failed!(nodes[0], our_payment_hash, false);
5500 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5501 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5502 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5503 assert_eq!(spend_txn.len(), 3);
5504 check_spends!(spend_txn[0], local_txn_1[0]);
5505 assert_eq!(spend_txn[1].input.len(), 1);
5506 check_spends!(spend_txn[1], htlc_timeout);
5507 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5508 assert_eq!(spend_txn[2].input.len(), 2);
5509 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5510 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5511 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5515 fn test_static_output_closing_tx() {
5516 let chanmon_cfgs = create_chanmon_cfgs(2);
5517 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5518 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5519 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5521 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5523 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5524 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5526 mine_transaction(&nodes[0], &closing_tx);
5527 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
5528 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5530 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5531 assert_eq!(spend_txn.len(), 1);
5532 check_spends!(spend_txn[0], closing_tx);
5534 mine_transaction(&nodes[1], &closing_tx);
5535 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
5536 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5538 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5539 assert_eq!(spend_txn.len(), 1);
5540 check_spends!(spend_txn[0], closing_tx);
5543 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5544 let chanmon_cfgs = create_chanmon_cfgs(2);
5545 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5546 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5547 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5548 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5550 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5552 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5553 // present in B's local commitment transaction, but none of A's commitment transactions.
5554 nodes[1].node.claim_funds(payment_preimage);
5555 check_added_monitors!(nodes[1], 1);
5556 expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5558 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5559 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5560 expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
5562 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5563 check_added_monitors!(nodes[0], 1);
5564 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5565 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5566 check_added_monitors!(nodes[1], 1);
5568 let starting_block = nodes[1].best_block_info();
5569 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5570 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5571 connect_block(&nodes[1], &block);
5572 block.header.prev_blockhash = block.block_hash();
5574 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5575 check_closed_broadcast!(nodes[1], true);
5576 check_added_monitors!(nodes[1], 1);
5577 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
5580 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5581 let chanmon_cfgs = create_chanmon_cfgs(2);
5582 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5583 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5584 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5585 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5587 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5588 nodes[0].node.send_payment_with_route(&route, payment_hash,
5589 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
5590 check_added_monitors!(nodes[0], 1);
5592 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5594 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5595 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5596 // to "time out" the HTLC.
5598 let starting_block = nodes[1].best_block_info();
5599 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5601 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5602 connect_block(&nodes[0], &block);
5603 block.header.prev_blockhash = block.block_hash();
5605 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5606 check_closed_broadcast!(nodes[0], true);
5607 check_added_monitors!(nodes[0], 1);
5608 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5611 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5612 let chanmon_cfgs = create_chanmon_cfgs(3);
5613 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5614 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5615 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5616 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5618 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5619 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5620 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5621 // actually revoked.
5622 let htlc_value = if use_dust { 50000 } else { 3000000 };
5623 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5624 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5625 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5626 check_added_monitors!(nodes[1], 1);
5628 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5629 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5630 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5631 check_added_monitors!(nodes[0], 1);
5632 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5633 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5634 check_added_monitors!(nodes[1], 1);
5635 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5636 check_added_monitors!(nodes[1], 1);
5637 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5639 if check_revoke_no_close {
5640 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5641 check_added_monitors!(nodes[0], 1);
5644 let starting_block = nodes[1].best_block_info();
5645 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5646 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5647 connect_block(&nodes[0], &block);
5648 block.header.prev_blockhash = block.block_hash();
5650 if !check_revoke_no_close {
5651 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5652 check_closed_broadcast!(nodes[0], true);
5653 check_added_monitors!(nodes[0], 1);
5654 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5656 expect_payment_failed!(nodes[0], our_payment_hash, true);
5660 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5661 // There are only a few cases to test here:
5662 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5663 // broadcastable commitment transactions result in channel closure,
5664 // * its included in an unrevoked-but-previous remote commitment transaction,
5665 // * its included in the latest remote or local commitment transactions.
5666 // We test each of the three possible commitment transactions individually and use both dust and
5668 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5669 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5670 // tested for at least one of the cases in other tests.
5672 fn htlc_claim_single_commitment_only_a() {
5673 do_htlc_claim_local_commitment_only(true);
5674 do_htlc_claim_local_commitment_only(false);
5676 do_htlc_claim_current_remote_commitment_only(true);
5677 do_htlc_claim_current_remote_commitment_only(false);
5681 fn htlc_claim_single_commitment_only_b() {
5682 do_htlc_claim_previous_remote_commitment_only(true, false);
5683 do_htlc_claim_previous_remote_commitment_only(false, false);
5684 do_htlc_claim_previous_remote_commitment_only(true, true);
5685 do_htlc_claim_previous_remote_commitment_only(false, true);
5690 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5691 let chanmon_cfgs = create_chanmon_cfgs(2);
5692 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5693 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5694 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5695 // Force duplicate randomness for every get-random call
5696 for node in nodes.iter() {
5697 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5700 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5701 let channel_value_satoshis=10000;
5702 let push_msat=10001;
5703 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5704 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5705 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5706 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5708 // Create a second channel with the same random values. This used to panic due to a colliding
5709 // channel_id, but now panics due to a colliding outbound SCID alias.
5710 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5714 fn bolt2_open_channel_sending_node_checks_part2() {
5715 let chanmon_cfgs = create_chanmon_cfgs(2);
5716 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5717 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5718 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5720 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5721 let channel_value_satoshis=2^24;
5722 let push_msat=10001;
5723 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5725 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5726 let channel_value_satoshis=10000;
5727 // Test when push_msat is equal to 1000 * funding_satoshis.
5728 let push_msat=1000*channel_value_satoshis+1;
5729 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5731 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5732 let channel_value_satoshis=10000;
5733 let push_msat=10001;
5734 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_ok()); //Create a valid channel
5735 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5736 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5738 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5739 // 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
5740 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5742 // 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.
5743 assert!(BREAKDOWN_TIMEOUT>0);
5744 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5746 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5747 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5748 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5750 // 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.
5751 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5752 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5753 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5754 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5755 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5759 fn bolt2_open_channel_sane_dust_limit() {
5760 let chanmon_cfgs = create_chanmon_cfgs(2);
5761 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5762 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5763 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5765 let channel_value_satoshis=1000000;
5766 let push_msat=10001;
5767 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5768 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5769 node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5770 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5772 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5773 let events = nodes[1].node.get_and_clear_pending_msg_events();
5774 let err_msg = match events[0] {
5775 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5778 _ => panic!("Unexpected event"),
5780 assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5783 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5784 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5785 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5786 // is no longer affordable once it's freed.
5788 fn test_fail_holding_cell_htlc_upon_free() {
5789 let chanmon_cfgs = create_chanmon_cfgs(2);
5790 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5791 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5792 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5793 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5795 // First nodes[0] generates an update_fee, setting the channel's
5796 // pending_update_fee.
5798 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5799 *feerate_lock += 20;
5801 nodes[0].node.timer_tick_occurred();
5802 check_added_monitors!(nodes[0], 1);
5804 let events = nodes[0].node.get_and_clear_pending_msg_events();
5805 assert_eq!(events.len(), 1);
5806 let (update_msg, commitment_signed) = match events[0] {
5807 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5808 (update_fee.as_ref(), commitment_signed)
5810 _ => panic!("Unexpected event"),
5813 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5815 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5816 let channel_reserve = chan_stat.channel_reserve_msat;
5817 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5818 let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
5820 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5821 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
5822 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5824 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5825 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5826 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5827 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5828 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5830 // Flush the pending fee update.
5831 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5832 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5833 check_added_monitors!(nodes[1], 1);
5834 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5835 check_added_monitors!(nodes[0], 1);
5837 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5838 // HTLC, but now that the fee has been raised the payment will now fail, causing
5839 // us to surface its failure to the user.
5840 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5841 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5842 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Freeing holding cell with 1 HTLC updates in channel {}", chan.2), 1);
5844 // Check that the payment failed to be sent out.
5845 let events = nodes[0].node.get_and_clear_pending_events();
5846 assert_eq!(events.len(), 2);
5848 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5849 assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5850 assert_eq!(our_payment_hash.clone(), *payment_hash);
5851 assert_eq!(*payment_failed_permanently, false);
5852 assert_eq!(*short_channel_id, Some(route.paths[0].hops[0].short_channel_id));
5854 _ => panic!("Unexpected event"),
5857 &Event::PaymentFailed { ref payment_hash, .. } => {
5858 assert_eq!(our_payment_hash.clone(), *payment_hash);
5860 _ => panic!("Unexpected event"),
5864 // Test that if multiple HTLCs are released from the holding cell and one is
5865 // valid but the other is no longer valid upon release, the valid HTLC can be
5866 // successfully completed while the other one fails as expected.
5868 fn test_free_and_fail_holding_cell_htlcs() {
5869 let chanmon_cfgs = create_chanmon_cfgs(2);
5870 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5871 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5872 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5873 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5875 // First nodes[0] generates an update_fee, setting the channel's
5876 // pending_update_fee.
5878 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5879 *feerate_lock += 200;
5881 nodes[0].node.timer_tick_occurred();
5882 check_added_monitors!(nodes[0], 1);
5884 let events = nodes[0].node.get_and_clear_pending_msg_events();
5885 assert_eq!(events.len(), 1);
5886 let (update_msg, commitment_signed) = match events[0] {
5887 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5888 (update_fee.as_ref(), commitment_signed)
5890 _ => panic!("Unexpected event"),
5893 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5895 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5896 let channel_reserve = chan_stat.channel_reserve_msat;
5897 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5898 let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
5900 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5902 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features) - amt_1;
5903 let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5904 let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5906 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5907 nodes[0].node.send_payment_with_route(&route_1, payment_hash_1,
5908 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
5909 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5910 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
5911 let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
5912 nodes[0].node.send_payment_with_route(&route_2, payment_hash_2,
5913 RecipientOnionFields::secret_only(payment_secret_2), payment_id_2).unwrap();
5914 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5915 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
5917 // Flush the pending fee update.
5918 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5919 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5920 check_added_monitors!(nodes[1], 1);
5921 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
5922 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5923 check_added_monitors!(nodes[0], 2);
5925 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
5926 // but now that the fee has been raised the second payment will now fail, causing us
5927 // to surface its failure to the user. The first payment should succeed.
5928 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5929 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5930 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Freeing holding cell with 2 HTLC updates in channel {}", chan.2), 1);
5932 // Check that the second payment failed to be sent out.
5933 let events = nodes[0].node.get_and_clear_pending_events();
5934 assert_eq!(events.len(), 2);
5936 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5937 assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
5938 assert_eq!(payment_hash_2.clone(), *payment_hash);
5939 assert_eq!(*payment_failed_permanently, false);
5940 assert_eq!(*short_channel_id, Some(route_2.paths[0].hops[0].short_channel_id));
5942 _ => panic!("Unexpected event"),
5945 &Event::PaymentFailed { ref payment_hash, .. } => {
5946 assert_eq!(payment_hash_2.clone(), *payment_hash);
5948 _ => panic!("Unexpected event"),
5951 // Complete the first payment and the RAA from the fee update.
5952 let (payment_event, send_raa_event) = {
5953 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
5954 assert_eq!(msgs.len(), 2);
5955 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
5957 let raa = match send_raa_event {
5958 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
5959 _ => panic!("Unexpected event"),
5961 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5962 check_added_monitors!(nodes[1], 1);
5963 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5964 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5965 let events = nodes[1].node.get_and_clear_pending_events();
5966 assert_eq!(events.len(), 1);
5968 Event::PendingHTLCsForwardable { .. } => {},
5969 _ => panic!("Unexpected event"),
5971 nodes[1].node.process_pending_htlc_forwards();
5972 let events = nodes[1].node.get_and_clear_pending_events();
5973 assert_eq!(events.len(), 1);
5975 Event::PaymentClaimable { .. } => {},
5976 _ => panic!("Unexpected event"),
5978 nodes[1].node.claim_funds(payment_preimage_1);
5979 check_added_monitors!(nodes[1], 1);
5980 expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
5982 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5983 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
5984 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
5985 expect_payment_sent!(nodes[0], payment_preimage_1);
5988 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
5989 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
5990 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
5993 fn test_fail_holding_cell_htlc_upon_free_multihop() {
5994 let chanmon_cfgs = create_chanmon_cfgs(3);
5995 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5996 // Avoid having to include routing fees in calculations
5997 let mut config = test_default_channel_config();
5998 config.channel_config.forwarding_fee_base_msat = 0;
5999 config.channel_config.forwarding_fee_proportional_millionths = 0;
6000 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6001 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6002 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6003 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
6005 // First nodes[1] generates an update_fee, setting the channel's
6006 // pending_update_fee.
6008 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6009 *feerate_lock += 20;
6011 nodes[1].node.timer_tick_occurred();
6012 check_added_monitors!(nodes[1], 1);
6014 let events = nodes[1].node.get_and_clear_pending_msg_events();
6015 assert_eq!(events.len(), 1);
6016 let (update_msg, commitment_signed) = match events[0] {
6017 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6018 (update_fee.as_ref(), commitment_signed)
6020 _ => panic!("Unexpected event"),
6023 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6025 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan_0_1.2);
6026 let channel_reserve = chan_stat.channel_reserve_msat;
6027 let feerate = get_feerate!(nodes[0], nodes[1], chan_0_1.2);
6028 let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_0_1.2);
6030 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6031 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
6032 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6033 let payment_event = {
6034 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6035 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6036 check_added_monitors!(nodes[0], 1);
6038 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6039 assert_eq!(events.len(), 1);
6041 SendEvent::from_event(events.remove(0))
6043 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6044 check_added_monitors!(nodes[1], 0);
6045 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6046 expect_pending_htlcs_forwardable!(nodes[1]);
6048 chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
6049 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6051 // Flush the pending fee update.
6052 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6053 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6054 check_added_monitors!(nodes[2], 1);
6055 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6056 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6057 check_added_monitors!(nodes[1], 2);
6059 // A final RAA message is generated to finalize the fee update.
6060 let events = nodes[1].node.get_and_clear_pending_msg_events();
6061 assert_eq!(events.len(), 1);
6063 let raa_msg = match &events[0] {
6064 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6067 _ => panic!("Unexpected event"),
6070 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6071 check_added_monitors!(nodes[2], 1);
6072 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6074 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6075 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6076 assert_eq!(process_htlc_forwards_event.len(), 2);
6077 match &process_htlc_forwards_event[0] {
6078 &Event::PendingHTLCsForwardable { .. } => {},
6079 _ => panic!("Unexpected event"),
6082 // In response, we call ChannelManager's process_pending_htlc_forwards
6083 nodes[1].node.process_pending_htlc_forwards();
6084 check_added_monitors!(nodes[1], 1);
6086 // This causes the HTLC to be failed backwards.
6087 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6088 assert_eq!(fail_event.len(), 1);
6089 let (fail_msg, commitment_signed) = match &fail_event[0] {
6090 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6091 assert_eq!(updates.update_add_htlcs.len(), 0);
6092 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6093 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6094 assert_eq!(updates.update_fail_htlcs.len(), 1);
6095 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6097 _ => panic!("Unexpected event"),
6100 // Pass the failure messages back to nodes[0].
6101 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6102 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6104 // Complete the HTLC failure+removal process.
6105 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6106 check_added_monitors!(nodes[0], 1);
6107 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6108 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6109 check_added_monitors!(nodes[1], 2);
6110 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6111 assert_eq!(final_raa_event.len(), 1);
6112 let raa = match &final_raa_event[0] {
6113 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6114 _ => panic!("Unexpected event"),
6116 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6117 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6118 check_added_monitors!(nodes[0], 1);
6121 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6122 // 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.
6123 //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.
6126 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6127 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6128 let chanmon_cfgs = create_chanmon_cfgs(2);
6129 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6130 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6131 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6132 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6134 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6135 route.paths[0].hops[0].fee_msat = 100;
6137 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6138 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6139 ), true, APIError::ChannelUnavailable { .. }, {});
6140 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6144 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6145 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6146 let chanmon_cfgs = create_chanmon_cfgs(2);
6147 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6148 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6149 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6150 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6152 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6153 route.paths[0].hops[0].fee_msat = 0;
6154 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6155 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)),
6156 true, APIError::ChannelUnavailable { ref err },
6157 assert_eq!(err, "Cannot send 0-msat HTLC"));
6159 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6160 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send 0-msat HTLC", 1);
6164 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6165 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6166 let chanmon_cfgs = create_chanmon_cfgs(2);
6167 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6168 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6169 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6170 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6172 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6173 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6174 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6175 check_added_monitors!(nodes[0], 1);
6176 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6177 updates.update_add_htlcs[0].amount_msat = 0;
6179 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6180 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6181 check_closed_broadcast!(nodes[1], true).unwrap();
6182 check_added_monitors!(nodes[1], 1);
6183 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() },
6184 [nodes[0].node.get_our_node_id()], 100000);
6188 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6189 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6190 //It is enforced when constructing a route.
6191 let chanmon_cfgs = create_chanmon_cfgs(2);
6192 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6193 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6194 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6195 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6197 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6198 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
6199 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);
6200 route.paths[0].hops.last_mut().unwrap().cltv_expiry_delta = 500000001;
6201 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6202 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6203 ), true, APIError::InvalidRoute { ref err },
6204 assert_eq!(err, &"Channel CLTV overflowed?"));
6208 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6209 //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.
6210 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6211 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6212 let chanmon_cfgs = create_chanmon_cfgs(2);
6213 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6214 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6215 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6216 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6217 let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6218 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context.counterparty_max_accepted_htlcs as u64;
6220 // Fetch a route in advance as we will be unable to once we're unable to send.
6221 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6222 for i in 0..max_accepted_htlcs {
6223 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6224 let payment_event = {
6225 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6226 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6227 check_added_monitors!(nodes[0], 1);
6229 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6230 assert_eq!(events.len(), 1);
6231 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6232 assert_eq!(htlcs[0].htlc_id, i);
6236 SendEvent::from_event(events.remove(0))
6238 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6239 check_added_monitors!(nodes[1], 0);
6240 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6242 expect_pending_htlcs_forwardable!(nodes[1]);
6243 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6245 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6246 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6247 ), true, APIError::ChannelUnavailable { .. }, {});
6249 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6253 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6254 //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.
6255 let chanmon_cfgs = create_chanmon_cfgs(2);
6256 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6257 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6258 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6259 let channel_value = 100000;
6260 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6261 let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6263 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6265 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6266 // Manually create a route over our max in flight (which our router normally automatically
6268 route.paths[0].hops[0].fee_msat = max_in_flight + 1;
6269 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6270 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6271 ), true, APIError::ChannelUnavailable { .. }, {});
6272 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6274 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6277 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6279 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6280 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6281 let chanmon_cfgs = create_chanmon_cfgs(2);
6282 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6283 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6284 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6285 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6286 let htlc_minimum_msat: u64;
6288 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6289 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6290 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6291 htlc_minimum_msat = channel.context.get_holder_htlc_minimum_msat();
6294 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6295 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6296 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6297 check_added_monitors!(nodes[0], 1);
6298 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6299 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6300 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6301 assert!(nodes[1].node.list_channels().is_empty());
6302 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6303 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()));
6304 check_added_monitors!(nodes[1], 1);
6305 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6309 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6310 //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
6311 let chanmon_cfgs = create_chanmon_cfgs(2);
6312 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6313 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6314 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6315 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6317 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6318 let channel_reserve = chan_stat.channel_reserve_msat;
6319 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6320 let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
6321 // The 2* and +1 are for the fee spike reserve.
6322 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
6324 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6325 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6326 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6327 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6328 check_added_monitors!(nodes[0], 1);
6329 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6331 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6332 // at this time channel-initiatee receivers are not required to enforce that senders
6333 // respect the fee_spike_reserve.
6334 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6335 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6337 assert!(nodes[1].node.list_channels().is_empty());
6338 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6339 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6340 check_added_monitors!(nodes[1], 1);
6341 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6345 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6346 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6347 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6348 let chanmon_cfgs = create_chanmon_cfgs(2);
6349 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6350 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6351 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6352 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6354 let send_amt = 3999999;
6355 let (mut route, our_payment_hash, _, our_payment_secret) =
6356 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
6357 route.paths[0].hops[0].fee_msat = send_amt;
6358 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6359 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6360 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6361 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
6362 &route.paths[0], send_amt, RecipientOnionFields::secret_only(our_payment_secret), cur_height, &None).unwrap();
6363 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
6365 let mut msg = msgs::UpdateAddHTLC {
6369 payment_hash: our_payment_hash,
6370 cltv_expiry: htlc_cltv,
6371 onion_routing_packet: onion_packet.clone(),
6372 skimmed_fee_msat: None,
6376 msg.htlc_id = i as u64;
6377 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6379 msg.htlc_id = (50) as u64;
6380 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6382 assert!(nodes[1].node.list_channels().is_empty());
6383 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6384 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6385 check_added_monitors!(nodes[1], 1);
6386 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6390 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6391 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6392 let chanmon_cfgs = create_chanmon_cfgs(2);
6393 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6394 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6395 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6396 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6398 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6399 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6400 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6401 check_added_monitors!(nodes[0], 1);
6402 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6403 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;
6404 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6406 assert!(nodes[1].node.list_channels().is_empty());
6407 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6408 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6409 check_added_monitors!(nodes[1], 1);
6410 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 1000000);
6414 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6415 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6416 let chanmon_cfgs = create_chanmon_cfgs(2);
6417 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6418 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6419 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6421 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6422 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6423 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6424 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6425 check_added_monitors!(nodes[0], 1);
6426 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6427 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6428 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6430 assert!(nodes[1].node.list_channels().is_empty());
6431 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6432 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6433 check_added_monitors!(nodes[1], 1);
6434 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6438 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6439 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6440 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6441 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6442 let chanmon_cfgs = create_chanmon_cfgs(2);
6443 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6444 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6445 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6447 create_announced_chan_between_nodes(&nodes, 0, 1);
6448 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6449 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6450 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6451 check_added_monitors!(nodes[0], 1);
6452 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6453 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6455 //Disconnect and Reconnect
6456 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
6457 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
6458 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
6459 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
6461 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6462 assert_eq!(reestablish_1.len(), 1);
6463 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
6464 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
6466 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6467 assert_eq!(reestablish_2.len(), 1);
6468 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6469 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6470 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6471 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6474 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6475 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6476 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6477 check_added_monitors!(nodes[1], 1);
6478 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6480 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6482 assert!(nodes[1].node.list_channels().is_empty());
6483 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6484 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6485 check_added_monitors!(nodes[1], 1);
6486 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6490 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6491 //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.
6493 let chanmon_cfgs = create_chanmon_cfgs(2);
6494 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6495 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6496 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6497 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6498 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6499 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6500 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6502 check_added_monitors!(nodes[0], 1);
6503 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6504 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6506 let update_msg = msgs::UpdateFulfillHTLC{
6509 payment_preimage: our_payment_preimage,
6512 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6514 assert!(nodes[0].node.list_channels().is_empty());
6515 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6516 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()));
6517 check_added_monitors!(nodes[0], 1);
6518 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6522 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6523 //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.
6525 let chanmon_cfgs = create_chanmon_cfgs(2);
6526 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6527 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6528 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6529 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6531 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6532 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6533 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6534 check_added_monitors!(nodes[0], 1);
6535 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6536 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6538 let update_msg = msgs::UpdateFailHTLC{
6541 reason: msgs::OnionErrorPacket { data: Vec::new()},
6544 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6546 assert!(nodes[0].node.list_channels().is_empty());
6547 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6548 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()));
6549 check_added_monitors!(nodes[0], 1);
6550 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6554 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6555 //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.
6557 let chanmon_cfgs = create_chanmon_cfgs(2);
6558 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6559 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6560 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6561 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6563 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6564 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6565 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6566 check_added_monitors!(nodes[0], 1);
6567 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6568 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6569 let update_msg = msgs::UpdateFailMalformedHTLC{
6572 sha256_of_onion: [1; 32],
6573 failure_code: 0x8000,
6576 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6578 assert!(nodes[0].node.list_channels().is_empty());
6579 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6580 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()));
6581 check_added_monitors!(nodes[0], 1);
6582 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6586 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6587 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6589 let chanmon_cfgs = create_chanmon_cfgs(2);
6590 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6591 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6592 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6593 create_announced_chan_between_nodes(&nodes, 0, 1);
6595 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6597 nodes[1].node.claim_funds(our_payment_preimage);
6598 check_added_monitors!(nodes[1], 1);
6599 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6601 let events = nodes[1].node.get_and_clear_pending_msg_events();
6602 assert_eq!(events.len(), 1);
6603 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6605 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, .. } } => {
6606 assert!(update_add_htlcs.is_empty());
6607 assert_eq!(update_fulfill_htlcs.len(), 1);
6608 assert!(update_fail_htlcs.is_empty());
6609 assert!(update_fail_malformed_htlcs.is_empty());
6610 assert!(update_fee.is_none());
6611 update_fulfill_htlcs[0].clone()
6613 _ => panic!("Unexpected event"),
6617 update_fulfill_msg.htlc_id = 1;
6619 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6621 assert!(nodes[0].node.list_channels().is_empty());
6622 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6623 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6624 check_added_monitors!(nodes[0], 1);
6625 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6629 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6630 //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.
6632 let chanmon_cfgs = create_chanmon_cfgs(2);
6633 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6634 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6635 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6636 create_announced_chan_between_nodes(&nodes, 0, 1);
6638 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6640 nodes[1].node.claim_funds(our_payment_preimage);
6641 check_added_monitors!(nodes[1], 1);
6642 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6644 let events = nodes[1].node.get_and_clear_pending_msg_events();
6645 assert_eq!(events.len(), 1);
6646 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6648 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, .. } } => {
6649 assert!(update_add_htlcs.is_empty());
6650 assert_eq!(update_fulfill_htlcs.len(), 1);
6651 assert!(update_fail_htlcs.is_empty());
6652 assert!(update_fail_malformed_htlcs.is_empty());
6653 assert!(update_fee.is_none());
6654 update_fulfill_htlcs[0].clone()
6656 _ => panic!("Unexpected event"),
6660 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6662 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6664 assert!(nodes[0].node.list_channels().is_empty());
6665 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6666 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6667 check_added_monitors!(nodes[0], 1);
6668 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6672 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6673 //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.
6675 let chanmon_cfgs = create_chanmon_cfgs(2);
6676 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6677 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6678 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6679 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6681 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6682 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6683 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6684 check_added_monitors!(nodes[0], 1);
6686 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6687 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6689 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6690 check_added_monitors!(nodes[1], 0);
6691 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6693 let events = nodes[1].node.get_and_clear_pending_msg_events();
6695 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6697 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, .. } } => {
6698 assert!(update_add_htlcs.is_empty());
6699 assert!(update_fulfill_htlcs.is_empty());
6700 assert!(update_fail_htlcs.is_empty());
6701 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6702 assert!(update_fee.is_none());
6703 update_fail_malformed_htlcs[0].clone()
6705 _ => panic!("Unexpected event"),
6708 update_msg.failure_code &= !0x8000;
6709 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6711 assert!(nodes[0].node.list_channels().is_empty());
6712 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6713 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6714 check_added_monitors!(nodes[0], 1);
6715 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 1000000);
6719 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6720 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6721 // * 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.
6723 let chanmon_cfgs = create_chanmon_cfgs(3);
6724 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6725 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6726 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6727 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6728 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000);
6730 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6733 let mut payment_event = {
6734 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6735 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6736 check_added_monitors!(nodes[0], 1);
6737 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6738 assert_eq!(events.len(), 1);
6739 SendEvent::from_event(events.remove(0))
6741 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6742 check_added_monitors!(nodes[1], 0);
6743 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6744 expect_pending_htlcs_forwardable!(nodes[1]);
6745 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6746 assert_eq!(events_2.len(), 1);
6747 check_added_monitors!(nodes[1], 1);
6748 payment_event = SendEvent::from_event(events_2.remove(0));
6749 assert_eq!(payment_event.msgs.len(), 1);
6752 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6753 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6754 check_added_monitors!(nodes[2], 0);
6755 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6757 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6758 assert_eq!(events_3.len(), 1);
6759 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6761 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 } } => {
6762 assert!(update_add_htlcs.is_empty());
6763 assert!(update_fulfill_htlcs.is_empty());
6764 assert!(update_fail_htlcs.is_empty());
6765 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6766 assert!(update_fee.is_none());
6767 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6769 _ => panic!("Unexpected event"),
6773 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6775 check_added_monitors!(nodes[1], 0);
6776 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6777 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 }]);
6778 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6779 assert_eq!(events_4.len(), 1);
6781 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6783 MessageSendEvent::UpdateHTLCs { node_id: _ , updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, .. } } => {
6784 assert!(update_add_htlcs.is_empty());
6785 assert!(update_fulfill_htlcs.is_empty());
6786 assert_eq!(update_fail_htlcs.len(), 1);
6787 assert!(update_fail_malformed_htlcs.is_empty());
6788 assert!(update_fee.is_none());
6790 _ => panic!("Unexpected event"),
6793 check_added_monitors!(nodes[1], 1);
6797 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6798 let chanmon_cfgs = create_chanmon_cfgs(3);
6799 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6800 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6801 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6802 create_announced_chan_between_nodes(&nodes, 0, 1);
6803 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6805 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6808 let mut payment_event = {
6809 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6810 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6811 check_added_monitors!(nodes[0], 1);
6812 SendEvent::from_node(&nodes[0])
6815 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6816 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6817 expect_pending_htlcs_forwardable!(nodes[1]);
6818 check_added_monitors!(nodes[1], 1);
6819 payment_event = SendEvent::from_node(&nodes[1]);
6820 assert_eq!(payment_event.msgs.len(), 1);
6823 payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6824 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6825 check_added_monitors!(nodes[2], 0);
6826 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6828 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6829 assert_eq!(events_3.len(), 1);
6831 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6832 let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6833 // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6834 update_msg.failure_code |= 0x2000;
6836 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6837 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6839 _ => panic!("Unexpected event"),
6842 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6843 vec![HTLCDestination::NextHopChannel {
6844 node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6845 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6846 assert_eq!(events_4.len(), 1);
6847 check_added_monitors!(nodes[1], 1);
6850 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6851 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6852 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6854 _ => panic!("Unexpected event"),
6857 let events_5 = nodes[0].node.get_and_clear_pending_events();
6858 assert_eq!(events_5.len(), 2);
6860 // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6861 // the node originating the error to its next hop.
6863 Event::PaymentPathFailed { error_code, failure: PathFailure::OnPath { network_update: Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }) }, ..
6865 assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6866 assert!(is_permanent);
6867 assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
6869 _ => panic!("Unexpected event"),
6872 Event::PaymentFailed { payment_hash, .. } => {
6873 assert_eq!(payment_hash, our_payment_hash);
6875 _ => panic!("Unexpected event"),
6878 // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
6881 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6882 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6883 // 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
6884 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6886 let mut chanmon_cfgs = create_chanmon_cfgs(2);
6887 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6888 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6889 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6890 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6891 let chan =create_announced_chan_between_nodes(&nodes, 0, 1);
6893 let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6894 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context.holder_dust_limit_satoshis;
6896 // We route 2 dust-HTLCs between A and B
6897 let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6898 let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6899 route_payment(&nodes[0], &[&nodes[1]], 1000000);
6901 // Cache one local commitment tx as previous
6902 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6904 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6905 nodes[1].node.fail_htlc_backwards(&payment_hash_2);
6906 check_added_monitors!(nodes[1], 0);
6907 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
6908 check_added_monitors!(nodes[1], 1);
6910 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6911 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6912 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6913 check_added_monitors!(nodes[0], 1);
6915 // Cache one local commitment tx as lastest
6916 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6918 let events = nodes[0].node.get_and_clear_pending_msg_events();
6920 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6921 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6923 _ => panic!("Unexpected event"),
6926 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6927 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6929 _ => panic!("Unexpected event"),
6932 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6933 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6934 if announce_latest {
6935 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6937 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6940 check_closed_broadcast!(nodes[0], true);
6941 check_added_monitors!(nodes[0], 1);
6942 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
6944 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6945 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6946 let events = nodes[0].node.get_and_clear_pending_events();
6947 // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
6948 assert_eq!(events.len(), 4);
6949 let mut first_failed = false;
6950 for event in events {
6952 Event::PaymentPathFailed { payment_hash, .. } => {
6953 if payment_hash == payment_hash_1 {
6954 assert!(!first_failed);
6955 first_failed = true;
6957 assert_eq!(payment_hash, payment_hash_2);
6960 Event::PaymentFailed { .. } => {}
6961 _ => panic!("Unexpected event"),
6967 fn test_failure_delay_dust_htlc_local_commitment() {
6968 do_test_failure_delay_dust_htlc_local_commitment(true);
6969 do_test_failure_delay_dust_htlc_local_commitment(false);
6972 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6973 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6974 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6975 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6976 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6977 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6978 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6980 let chanmon_cfgs = create_chanmon_cfgs(3);
6981 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6982 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6983 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6984 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6986 let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6987 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context.holder_dust_limit_satoshis;
6989 let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6990 let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6992 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6993 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6995 // We revoked bs_commitment_tx
6997 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6998 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7001 let mut timeout_tx = Vec::new();
7003 // We fail dust-HTLC 1 by broadcast of local commitment tx
7004 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7005 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7006 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7007 expect_payment_failed!(nodes[0], dust_hash, false);
7009 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7010 check_closed_broadcast!(nodes[0], true);
7011 check_added_monitors!(nodes[0], 1);
7012 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7013 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7014 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7015 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7016 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7017 mine_transaction(&nodes[0], &timeout_tx[0]);
7018 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7019 expect_payment_failed!(nodes[0], non_dust_hash, false);
7021 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7022 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7023 check_closed_broadcast!(nodes[0], true);
7024 check_added_monitors!(nodes[0], 1);
7025 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7026 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7028 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7029 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
7030 .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
7031 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
7032 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
7033 // dust HTLC should have been failed.
7034 expect_payment_failed!(nodes[0], dust_hash, false);
7037 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7039 assert_eq!(timeout_tx[0].lock_time.0, 11);
7041 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
7042 mine_transaction(&nodes[0], &timeout_tx[0]);
7043 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7044 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7045 expect_payment_failed!(nodes[0], non_dust_hash, false);
7050 fn test_sweep_outbound_htlc_failure_update() {
7051 do_test_sweep_outbound_htlc_failure_update(false, true);
7052 do_test_sweep_outbound_htlc_failure_update(false, false);
7053 do_test_sweep_outbound_htlc_failure_update(true, false);
7057 fn test_user_configurable_csv_delay() {
7058 // We test our channel constructors yield errors when we pass them absurd csv delay
7060 let mut low_our_to_self_config = UserConfig::default();
7061 low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
7062 let mut high_their_to_self_config = UserConfig::default();
7063 high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
7064 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7065 let chanmon_cfgs = create_chanmon_cfgs(2);
7066 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7067 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7068 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7070 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in OutboundV1Channel::new()
7071 if let Err(error) = OutboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7072 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[1].node.init_features(), 1000000, 1000000, 0,
7073 &low_our_to_self_config, 0, 42)
7076 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())); },
7077 _ => panic!("Unexpected event"),
7079 } else { assert!(false) }
7081 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in InboundV1Channel::new()
7082 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7083 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7084 open_channel.to_self_delay = 200;
7085 if let Err(error) = InboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7086 &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,
7087 &low_our_to_self_config, 0, &nodes[0].logger, /*is_0conf=*/false)
7090 ChannelError::Close(err) => { assert!(regex::Regex::new(r"Configured with an unreasonable our_to_self_delay \(\d+\) putting user funds at risks").unwrap().is_match(err.as_str())); },
7091 _ => panic!("Unexpected event"),
7093 } else { assert!(false); }
7095 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7096 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7097 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()));
7098 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7099 accept_channel.to_self_delay = 200;
7100 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
7102 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7104 &ErrorAction::SendErrorMessage { ref msg } => {
7105 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()));
7106 reason_msg = msg.data.clone();
7110 } else { panic!(); }
7111 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg }, [nodes[1].node.get_our_node_id()], 1000000);
7113 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in InboundV1Channel::new()
7114 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7115 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7116 open_channel.to_self_delay = 200;
7117 if let Err(error) = InboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7118 &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,
7119 &high_their_to_self_config, 0, &nodes[0].logger, /*is_0conf=*/false)
7122 ChannelError::Close(err) => { assert!(regex::Regex::new(r"They wanted our payments to be delayed by a needlessly long period\. Upper limit: \d+\. Actual: \d+").unwrap().is_match(err.as_str())); },
7123 _ => panic!("Unexpected event"),
7125 } else { assert!(false); }
7129 fn test_check_htlc_underpaying() {
7130 // Send payment through A -> B but A is maliciously
7131 // sending a probe payment (i.e less than expected value0
7132 // to B, B should refuse payment.
7134 let chanmon_cfgs = create_chanmon_cfgs(2);
7135 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7136 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7137 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7139 // Create some initial channels
7140 create_announced_chan_between_nodes(&nodes, 0, 1);
7142 let scorer = test_utils::TestScorer::new();
7143 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7144 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(),
7145 TEST_FINAL_CLTV).with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
7146 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 10_000);
7147 let route = get_route(&nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph.read_only(),
7148 None, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7149 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7150 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, None).unwrap();
7151 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
7152 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
7153 check_added_monitors!(nodes[0], 1);
7155 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7156 assert_eq!(events.len(), 1);
7157 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7158 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7159 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7161 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7162 // and then will wait a second random delay before failing the HTLC back:
7163 expect_pending_htlcs_forwardable!(nodes[1]);
7164 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7166 // Node 3 is expecting payment of 100_000 but received 10_000,
7167 // it should fail htlc like we didn't know the preimage.
7168 nodes[1].node.process_pending_htlc_forwards();
7170 let events = nodes[1].node.get_and_clear_pending_msg_events();
7171 assert_eq!(events.len(), 1);
7172 let (update_fail_htlc, commitment_signed) = match events[0] {
7173 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 } } => {
7174 assert!(update_add_htlcs.is_empty());
7175 assert!(update_fulfill_htlcs.is_empty());
7176 assert_eq!(update_fail_htlcs.len(), 1);
7177 assert!(update_fail_malformed_htlcs.is_empty());
7178 assert!(update_fee.is_none());
7179 (update_fail_htlcs[0].clone(), commitment_signed)
7181 _ => panic!("Unexpected event"),
7183 check_added_monitors!(nodes[1], 1);
7185 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7186 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7188 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7189 let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
7190 expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
7191 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7195 fn test_announce_disable_channels() {
7196 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7197 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7199 let chanmon_cfgs = create_chanmon_cfgs(2);
7200 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7201 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7202 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7204 create_announced_chan_between_nodes(&nodes, 0, 1);
7205 create_announced_chan_between_nodes(&nodes, 1, 0);
7206 create_announced_chan_between_nodes(&nodes, 0, 1);
7209 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
7210 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
7212 for _ in 0..DISABLE_GOSSIP_TICKS + 1 {
7213 nodes[0].node.timer_tick_occurred();
7215 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7216 assert_eq!(msg_events.len(), 3);
7217 let mut chans_disabled = HashMap::new();
7218 for e in msg_events {
7220 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7221 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7222 // Check that each channel gets updated exactly once
7223 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7224 panic!("Generated ChannelUpdate for wrong chan!");
7227 _ => panic!("Unexpected event"),
7231 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
7232 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
7234 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7235 assert_eq!(reestablish_1.len(), 3);
7236 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
7237 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
7239 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7240 assert_eq!(reestablish_2.len(), 3);
7242 // Reestablish chan_1
7243 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7244 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7245 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7246 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7247 // Reestablish chan_2
7248 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7249 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7250 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7251 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7252 // Reestablish chan_3
7253 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7254 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7255 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7256 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7258 for _ in 0..ENABLE_GOSSIP_TICKS {
7259 nodes[0].node.timer_tick_occurred();
7261 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7262 nodes[0].node.timer_tick_occurred();
7263 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7264 assert_eq!(msg_events.len(), 3);
7265 for e in msg_events {
7267 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7268 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7269 match chans_disabled.remove(&msg.contents.short_channel_id) {
7270 // Each update should have a higher timestamp than the previous one, replacing
7272 Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7273 None => panic!("Generated ChannelUpdate for wrong chan!"),
7276 _ => panic!("Unexpected event"),
7279 // Check that each channel gets updated exactly once
7280 assert!(chans_disabled.is_empty());
7284 fn test_bump_penalty_txn_on_revoked_commitment() {
7285 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7286 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7288 let chanmon_cfgs = create_chanmon_cfgs(2);
7289 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7290 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7291 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7293 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7295 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7296 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7297 .with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7298 let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000);
7299 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7301 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7302 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7303 assert_eq!(revoked_txn[0].output.len(), 4);
7304 assert_eq!(revoked_txn[0].input.len(), 1);
7305 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7306 let revoked_txid = revoked_txn[0].txid();
7308 let mut penalty_sum = 0;
7309 for outp in revoked_txn[0].output.iter() {
7310 if outp.script_pubkey.is_v0_p2wsh() {
7311 penalty_sum += outp.value;
7315 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7316 let header_114 = connect_blocks(&nodes[1], 14);
7318 // Actually revoke tx by claiming a HTLC
7319 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7320 connect_block(&nodes[1], &create_dummy_block(header_114, 42, vec![revoked_txn[0].clone()]));
7321 check_added_monitors!(nodes[1], 1);
7323 // One or more justice tx should have been broadcast, check it
7327 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7328 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7329 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7330 assert_eq!(node_txn[0].output.len(), 1);
7331 check_spends!(node_txn[0], revoked_txn[0]);
7332 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7333 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7334 penalty_1 = node_txn[0].txid();
7338 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7339 connect_blocks(&nodes[1], 15);
7340 let mut penalty_2 = penalty_1;
7341 let mut feerate_2 = 0;
7343 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7344 assert_eq!(node_txn.len(), 1);
7345 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7346 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7347 assert_eq!(node_txn[0].output.len(), 1);
7348 check_spends!(node_txn[0], revoked_txn[0]);
7349 penalty_2 = node_txn[0].txid();
7350 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7351 assert_ne!(penalty_2, penalty_1);
7352 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7353 feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7354 // Verify 25% bump heuristic
7355 assert!(feerate_2 * 100 >= feerate_1 * 125);
7359 assert_ne!(feerate_2, 0);
7361 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7362 connect_blocks(&nodes[1], 1);
7364 let mut feerate_3 = 0;
7366 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7367 assert_eq!(node_txn.len(), 1);
7368 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7369 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7370 assert_eq!(node_txn[0].output.len(), 1);
7371 check_spends!(node_txn[0], revoked_txn[0]);
7372 penalty_3 = node_txn[0].txid();
7373 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7374 assert_ne!(penalty_3, penalty_2);
7375 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7376 feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7377 // Verify 25% bump heuristic
7378 assert!(feerate_3 * 100 >= feerate_2 * 125);
7382 assert_ne!(feerate_3, 0);
7384 nodes[1].node.get_and_clear_pending_events();
7385 nodes[1].node.get_and_clear_pending_msg_events();
7389 fn test_bump_penalty_txn_on_revoked_htlcs() {
7390 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7391 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7393 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7394 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7395 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7396 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7397 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7399 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7400 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7401 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 50).with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
7402 let scorer = test_utils::TestScorer::new();
7403 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7404 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 3_000_000);
7405 let route = get_route(&nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph.read_only(), None,
7406 nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7407 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7408 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50).with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7409 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 3_000_000);
7410 let route = get_route(&nodes[1].node.get_our_node_id(), &route_params, &nodes[1].network_graph.read_only(), None,
7411 nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7412 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7414 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7415 assert_eq!(revoked_local_txn[0].input.len(), 1);
7416 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7418 // Revoke local commitment tx
7419 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7421 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7422 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone()]));
7423 check_closed_broadcast!(nodes[1], true);
7424 check_added_monitors!(nodes[1], 1);
7425 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 1000000);
7426 connect_blocks(&nodes[1], 50); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7428 let revoked_htlc_txn = {
7429 let txn = nodes[1].tx_broadcaster.unique_txn_broadcast();
7430 assert_eq!(txn.len(), 2);
7432 assert_eq!(txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7433 assert_eq!(txn[0].input.len(), 1);
7434 check_spends!(txn[0], revoked_local_txn[0]);
7436 assert_eq!(txn[1].input.len(), 1);
7437 assert_eq!(txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7438 assert_eq!(txn[1].output.len(), 1);
7439 check_spends!(txn[1], revoked_local_txn[0]);
7444 // Broadcast set of revoked txn on A
7445 let hash_128 = connect_blocks(&nodes[0], 40);
7446 let block_11 = create_dummy_block(hash_128, 42, vec![revoked_local_txn[0].clone()]);
7447 connect_block(&nodes[0], &block_11);
7448 let block_129 = create_dummy_block(block_11.block_hash(), 42, vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()]);
7449 connect_block(&nodes[0], &block_129);
7450 let events = nodes[0].node.get_and_clear_pending_events();
7451 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7452 match events.last().unwrap() {
7453 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7454 _ => panic!("Unexpected event"),
7460 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7461 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7462 // Verify claim tx are spending revoked HTLC txn
7464 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7465 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7466 // which are included in the same block (they are broadcasted because we scan the
7467 // transactions linearly and generate claims as we go, they likely should be removed in the
7469 assert_eq!(node_txn[0].input.len(), 1);
7470 check_spends!(node_txn[0], revoked_local_txn[0]);
7471 assert_eq!(node_txn[1].input.len(), 1);
7472 check_spends!(node_txn[1], revoked_local_txn[0]);
7473 assert_eq!(node_txn[2].input.len(), 1);
7474 check_spends!(node_txn[2], revoked_local_txn[0]);
7476 // Each of the three justice transactions claim a separate (single) output of the three
7477 // available, which we check here:
7478 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7479 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7480 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7482 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7483 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7485 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7486 // output, checked above).
7487 assert_eq!(node_txn[3].input.len(), 2);
7488 assert_eq!(node_txn[3].output.len(), 1);
7489 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7491 first = node_txn[3].txid();
7492 // Store both feerates for later comparison
7493 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7494 feerate_1 = fee_1 * 1000 / node_txn[3].weight() as u64;
7495 penalty_txn = vec![node_txn[2].clone()];
7499 // Connect one more block to see if bumped penalty are issued for HTLC txn
7500 let block_130 = create_dummy_block(block_129.block_hash(), 42, penalty_txn);
7501 connect_block(&nodes[0], &block_130);
7502 let block_131 = create_dummy_block(block_130.block_hash(), 42, Vec::new());
7503 connect_block(&nodes[0], &block_131);
7505 // Few more blocks to confirm penalty txn
7506 connect_blocks(&nodes[0], 4);
7507 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7508 let header_144 = connect_blocks(&nodes[0], 9);
7510 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7511 assert_eq!(node_txn.len(), 1);
7513 assert_eq!(node_txn[0].input.len(), 2);
7514 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7515 // Verify bumped tx is different and 25% bump heuristic
7516 assert_ne!(first, node_txn[0].txid());
7517 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7518 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7519 assert!(feerate_2 * 100 > feerate_1 * 125);
7520 let txn = vec![node_txn[0].clone()];
7524 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7525 connect_block(&nodes[0], &create_dummy_block(header_144, 42, node_txn));
7526 connect_blocks(&nodes[0], 20);
7528 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7529 // We verify than no new transaction has been broadcast because previously
7530 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7531 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7532 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7533 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7534 // up bumped justice generation.
7535 assert_eq!(node_txn.len(), 0);
7538 check_closed_broadcast!(nodes[0], true);
7539 check_added_monitors!(nodes[0], 1);
7543 fn test_bump_penalty_txn_on_remote_commitment() {
7544 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7545 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7548 // Provide preimage for one
7549 // Check aggregation
7551 let chanmon_cfgs = create_chanmon_cfgs(2);
7552 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7553 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7554 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7556 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7557 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7558 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7560 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7561 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7562 assert_eq!(remote_txn[0].output.len(), 4);
7563 assert_eq!(remote_txn[0].input.len(), 1);
7564 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7566 // Claim a HTLC without revocation (provide B monitor with preimage)
7567 nodes[1].node.claim_funds(payment_preimage);
7568 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7569 mine_transaction(&nodes[1], &remote_txn[0]);
7570 check_added_monitors!(nodes[1], 2);
7571 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7573 // One or more claim tx should have been broadcast, check it
7577 let feerate_timeout;
7578 let feerate_preimage;
7580 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7581 // 3 transactions including:
7582 // preimage and timeout sweeps from remote commitment + preimage sweep bump
7583 assert_eq!(node_txn.len(), 3);
7584 assert_eq!(node_txn[0].input.len(), 1);
7585 assert_eq!(node_txn[1].input.len(), 1);
7586 assert_eq!(node_txn[2].input.len(), 1);
7587 check_spends!(node_txn[0], remote_txn[0]);
7588 check_spends!(node_txn[1], remote_txn[0]);
7589 check_spends!(node_txn[2], remote_txn[0]);
7591 preimage = node_txn[0].txid();
7592 let index = node_txn[0].input[0].previous_output.vout;
7593 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7594 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
7596 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7597 (node_txn[2].clone(), node_txn[1].clone())
7599 (node_txn[1].clone(), node_txn[2].clone())
7602 preimage_bump = preimage_bump_tx;
7603 check_spends!(preimage_bump, remote_txn[0]);
7604 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7606 timeout = timeout_tx.txid();
7607 let index = timeout_tx.input[0].previous_output.vout;
7608 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7609 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
7613 assert_ne!(feerate_timeout, 0);
7614 assert_ne!(feerate_preimage, 0);
7616 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7617 connect_blocks(&nodes[1], 1);
7619 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7620 assert_eq!(node_txn.len(), 1);
7621 assert_eq!(node_txn[0].input.len(), 1);
7622 assert_eq!(preimage_bump.input.len(), 1);
7623 check_spends!(node_txn[0], remote_txn[0]);
7624 check_spends!(preimage_bump, remote_txn[0]);
7626 let index = preimage_bump.input[0].previous_output.vout;
7627 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7628 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
7629 assert!(new_feerate * 100 > feerate_timeout * 125);
7630 assert_ne!(timeout, preimage_bump.txid());
7632 let index = node_txn[0].input[0].previous_output.vout;
7633 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7634 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
7635 assert!(new_feerate * 100 > feerate_preimage * 125);
7636 assert_ne!(preimage, node_txn[0].txid());
7641 nodes[1].node.get_and_clear_pending_events();
7642 nodes[1].node.get_and_clear_pending_msg_events();
7646 fn test_counterparty_raa_skip_no_crash() {
7647 // Previously, if our counterparty sent two RAAs in a row without us having provided a
7648 // commitment transaction, we would have happily carried on and provided them the next
7649 // commitment transaction based on one RAA forward. This would probably eventually have led to
7650 // channel closure, but it would not have resulted in funds loss. Still, our
7651 // TestChannelSigner would have panicked as it doesn't like jumps into the future. Here, we
7652 // check simply that the channel is closed in response to such an RAA, but don't check whether
7653 // we decide to punish our counterparty for revoking their funds (as we don't currently
7655 let chanmon_cfgs = create_chanmon_cfgs(2);
7656 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7657 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7658 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7659 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7661 let per_commitment_secret;
7662 let next_per_commitment_point;
7664 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7665 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7666 let keys = guard.channel_by_id.get_mut(&channel_id).unwrap().get_signer();
7668 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7670 // Make signer believe we got a counterparty signature, so that it allows the revocation
7671 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7672 per_commitment_secret = keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7674 // Must revoke without gaps
7675 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7676 keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7678 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7679 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7680 &SecretKey::from_slice(&keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7683 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7684 &msgs::RevokeAndACK {
7686 per_commitment_secret,
7687 next_per_commitment_point,
7689 next_local_nonce: None,
7691 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7692 check_added_monitors!(nodes[1], 1);
7693 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() }
7694 , [nodes[0].node.get_our_node_id()], 100000);
7698 fn test_bump_txn_sanitize_tracking_maps() {
7699 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7700 // verify we clean then right after expiration of ANTI_REORG_DELAY.
7702 let chanmon_cfgs = create_chanmon_cfgs(2);
7703 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7704 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7705 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7707 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7708 // Lock HTLC in both directions
7709 let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7710 let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7712 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7713 assert_eq!(revoked_local_txn[0].input.len(), 1);
7714 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7716 // Revoke local commitment tx
7717 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7719 // Broadcast set of revoked txn on A
7720 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7721 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7722 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7724 mine_transaction(&nodes[0], &revoked_local_txn[0]);
7725 check_closed_broadcast!(nodes[0], true);
7726 check_added_monitors!(nodes[0], 1);
7727 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 1000000);
7729 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7730 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7731 check_spends!(node_txn[0], revoked_local_txn[0]);
7732 check_spends!(node_txn[1], revoked_local_txn[0]);
7733 check_spends!(node_txn[2], revoked_local_txn[0]);
7734 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7738 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, penalty_txn));
7739 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7741 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7742 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7743 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7748 fn test_channel_conf_timeout() {
7749 // Tests that, for inbound channels, we give up on them if the funding transaction does not
7750 // confirm within 2016 blocks, as recommended by BOLT 2.
7751 let chanmon_cfgs = create_chanmon_cfgs(2);
7752 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7753 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7754 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7756 let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7758 // The outbound node should wait forever for confirmation:
7759 // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7760 // copied here instead of directly referencing the constant.
7761 connect_blocks(&nodes[0], 2016);
7762 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7764 // The inbound node should fail the channel after exactly 2016 blocks
7765 connect_blocks(&nodes[1], 2015);
7766 check_added_monitors!(nodes[1], 0);
7767 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7769 connect_blocks(&nodes[1], 1);
7770 check_added_monitors!(nodes[1], 1);
7771 check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut, [nodes[0].node.get_our_node_id()], 1000000);
7772 let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7773 assert_eq!(close_ev.len(), 1);
7775 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
7776 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7777 assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7779 _ => panic!("Unexpected event"),
7784 fn test_override_channel_config() {
7785 let chanmon_cfgs = create_chanmon_cfgs(2);
7786 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7787 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7788 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7790 // Node0 initiates a channel to node1 using the override config.
7791 let mut override_config = UserConfig::default();
7792 override_config.channel_handshake_config.our_to_self_delay = 200;
7794 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7796 // Assert the channel created by node0 is using the override config.
7797 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7798 assert_eq!(res.channel_flags, 0);
7799 assert_eq!(res.to_self_delay, 200);
7803 fn test_override_0msat_htlc_minimum() {
7804 let mut zero_config = UserConfig::default();
7805 zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7806 let chanmon_cfgs = create_chanmon_cfgs(2);
7807 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7808 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7809 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7811 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7812 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7813 assert_eq!(res.htlc_minimum_msat, 1);
7815 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7816 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7817 assert_eq!(res.htlc_minimum_msat, 1);
7821 fn test_channel_update_has_correct_htlc_maximum_msat() {
7822 // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7823 // Bolt 7 specifies that if present `htlc_maximum_msat`:
7824 // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7825 // 90% of the `channel_value`.
7826 // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7828 let mut config_30_percent = UserConfig::default();
7829 config_30_percent.channel_handshake_config.announced_channel = true;
7830 config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7831 let mut config_50_percent = UserConfig::default();
7832 config_50_percent.channel_handshake_config.announced_channel = true;
7833 config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7834 let mut config_95_percent = UserConfig::default();
7835 config_95_percent.channel_handshake_config.announced_channel = true;
7836 config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7837 let mut config_100_percent = UserConfig::default();
7838 config_100_percent.channel_handshake_config.announced_channel = true;
7839 config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7841 let chanmon_cfgs = create_chanmon_cfgs(4);
7842 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7843 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)]);
7844 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7846 let channel_value_satoshis = 100000;
7847 let channel_value_msat = channel_value_satoshis * 1000;
7848 let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7849 let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7850 let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7852 let (node_0_chan_update, node_1_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
7853 let (node_2_chan_update, node_3_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
7855 // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7856 // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7857 assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7858 // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7859 // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7860 assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7862 // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7863 // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7865 assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7866 // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7867 // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7869 assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7873 fn test_manually_accept_inbound_channel_request() {
7874 let mut manually_accept_conf = UserConfig::default();
7875 manually_accept_conf.manually_accept_inbound_channels = true;
7876 let chanmon_cfgs = create_chanmon_cfgs(2);
7877 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7878 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7879 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7881 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7882 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7884 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7886 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7887 // accepting the inbound channel request.
7888 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7890 let events = nodes[1].node.get_and_clear_pending_events();
7892 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7893 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
7895 _ => panic!("Unexpected event"),
7898 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7899 assert_eq!(accept_msg_ev.len(), 1);
7901 match accept_msg_ev[0] {
7902 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7903 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7905 _ => panic!("Unexpected event"),
7908 nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7910 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7911 assert_eq!(close_msg_ev.len(), 1);
7913 let events = nodes[1].node.get_and_clear_pending_events();
7915 Event::ChannelClosed { user_channel_id, .. } => {
7916 assert_eq!(user_channel_id, 23);
7918 _ => panic!("Unexpected event"),
7923 fn test_manually_reject_inbound_channel_request() {
7924 let mut manually_accept_conf = UserConfig::default();
7925 manually_accept_conf.manually_accept_inbound_channels = true;
7926 let chanmon_cfgs = create_chanmon_cfgs(2);
7927 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7928 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7929 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7931 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7932 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7934 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7936 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7937 // rejecting the inbound channel request.
7938 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7940 let events = nodes[1].node.get_and_clear_pending_events();
7942 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7943 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7945 _ => panic!("Unexpected event"),
7948 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7949 assert_eq!(close_msg_ev.len(), 1);
7951 match close_msg_ev[0] {
7952 MessageSendEvent::HandleError { ref node_id, .. } => {
7953 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7955 _ => panic!("Unexpected event"),
7958 // There should be no more events to process, as the channel was never opened.
7959 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
7963 fn test_can_not_accept_inbound_channel_twice() {
7964 let mut manually_accept_conf = UserConfig::default();
7965 manually_accept_conf.manually_accept_inbound_channels = true;
7966 let chanmon_cfgs = create_chanmon_cfgs(2);
7967 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7968 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7969 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7971 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7972 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7974 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7976 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7977 // accepting the inbound channel request.
7978 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7980 let events = nodes[1].node.get_and_clear_pending_events();
7982 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7983 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
7984 let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
7986 Err(APIError::APIMisuseError { err }) => {
7987 assert_eq!(err, "No such channel awaiting to be accepted.");
7989 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
7990 Err(e) => panic!("Unexpected Error {:?}", e),
7993 _ => panic!("Unexpected event"),
7996 // Ensure that the channel wasn't closed after attempting to accept it twice.
7997 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7998 assert_eq!(accept_msg_ev.len(), 1);
8000 match accept_msg_ev[0] {
8001 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8002 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8004 _ => panic!("Unexpected event"),
8009 fn test_can_not_accept_unknown_inbound_channel() {
8010 let chanmon_cfg = create_chanmon_cfgs(2);
8011 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8012 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8013 let nodes = create_network(2, &node_cfg, &node_chanmgr);
8015 let unknown_channel_id = ChannelId::new_zero();
8016 let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
8018 Err(APIError::APIMisuseError { err }) => {
8019 assert_eq!(err, "No such channel awaiting to be accepted.");
8021 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8022 Err(e) => panic!("Unexpected Error: {:?}", e),
8027 fn test_onion_value_mpp_set_calculation() {
8028 // Test that we use the onion value `amt_to_forward` when
8029 // calculating whether we've reached the `total_msat` of an MPP
8030 // by having a routing node forward more than `amt_to_forward`
8031 // and checking that the receiving node doesn't generate
8032 // a PaymentClaimable event too early
8034 let chanmon_cfgs = create_chanmon_cfgs(node_count);
8035 let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8036 let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8037 let mut nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8039 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8040 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8041 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8042 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8044 let total_msat = 100_000;
8045 let expected_paths: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
8046 let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], total_msat);
8047 let sample_path = route.paths.pop().unwrap();
8049 let mut path_1 = sample_path.clone();
8050 path_1.hops[0].pubkey = nodes[1].node.get_our_node_id();
8051 path_1.hops[0].short_channel_id = chan_1_id;
8052 path_1.hops[1].pubkey = nodes[3].node.get_our_node_id();
8053 path_1.hops[1].short_channel_id = chan_3_id;
8054 path_1.hops[1].fee_msat = 100_000;
8055 route.paths.push(path_1);
8057 let mut path_2 = sample_path.clone();
8058 path_2.hops[0].pubkey = nodes[2].node.get_our_node_id();
8059 path_2.hops[0].short_channel_id = chan_2_id;
8060 path_2.hops[1].pubkey = nodes[3].node.get_our_node_id();
8061 path_2.hops[1].short_channel_id = chan_4_id;
8062 path_2.hops[1].fee_msat = 1_000;
8063 route.paths.push(path_2);
8066 let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
8067 let onion_session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
8068 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8069 nodes[0].node.test_send_payment_internal(&route, our_payment_hash,
8070 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8071 check_added_monitors!(nodes[0], expected_paths.len());
8073 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8074 assert_eq!(events.len(), expected_paths.len());
8077 let ev = remove_first_msg_event_to_node(&expected_paths[0][0].node.get_our_node_id(), &mut events);
8078 let mut payment_event = SendEvent::from_event(ev);
8079 let mut prev_node = &nodes[0];
8081 for (idx, &node) in expected_paths[0].iter().enumerate() {
8082 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
8084 if idx == 0 { // routing node
8085 let session_priv = [3; 32];
8086 let height = nodes[0].best_block_info().1;
8087 let session_priv = SecretKey::from_slice(&session_priv).unwrap();
8088 let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
8089 let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], 100_000,
8090 RecipientOnionFields::secret_only(our_payment_secret), height + 1, &None).unwrap();
8091 // Edit amt_to_forward to simulate the sender having set
8092 // the final amount and the routing node taking less fee
8093 if let msgs::OutboundOnionPayload::Receive { ref mut amt_msat, .. } = onion_payloads[1] {
8096 let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
8097 payment_event.msgs[0].onion_routing_packet = new_onion_packet;
8100 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
8101 check_added_monitors!(node, 0);
8102 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
8103 expect_pending_htlcs_forwardable!(node);
8106 let mut events_2 = node.node.get_and_clear_pending_msg_events();
8107 assert_eq!(events_2.len(), 1);
8108 check_added_monitors!(node, 1);
8109 payment_event = SendEvent::from_event(events_2.remove(0));
8110 assert_eq!(payment_event.msgs.len(), 1);
8112 let events_2 = node.node.get_and_clear_pending_events();
8113 assert!(events_2.is_empty());
8120 let ev = remove_first_msg_event_to_node(&expected_paths[1][0].node.get_our_node_id(), &mut events);
8121 pass_along_path(&nodes[0], expected_paths[1], 101_000, our_payment_hash.clone(), Some(our_payment_secret), ev, true, None);
8123 claim_payment_along_route(&nodes[0], expected_paths, false, our_payment_preimage);
8126 fn do_test_overshoot_mpp(msat_amounts: &[u64], total_msat: u64) {
8128 let routing_node_count = msat_amounts.len();
8129 let node_count = routing_node_count + 2;
8131 let chanmon_cfgs = create_chanmon_cfgs(node_count);
8132 let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8133 let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8134 let nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8139 // Create channels for each amount
8140 let mut expected_paths = Vec::with_capacity(routing_node_count);
8141 let mut src_chan_ids = Vec::with_capacity(routing_node_count);
8142 let mut dst_chan_ids = Vec::with_capacity(routing_node_count);
8143 for i in 0..routing_node_count {
8144 let routing_node = 2 + i;
8145 let src_chan_id = create_announced_chan_between_nodes(&nodes, src_idx, routing_node).0.contents.short_channel_id;
8146 src_chan_ids.push(src_chan_id);
8147 let dst_chan_id = create_announced_chan_between_nodes(&nodes, routing_node, dst_idx).0.contents.short_channel_id;
8148 dst_chan_ids.push(dst_chan_id);
8149 let path = vec![&nodes[routing_node], &nodes[dst_idx]];
8150 expected_paths.push(path);
8152 let expected_paths: Vec<&[&Node]> = expected_paths.iter().map(|route| route.as_slice()).collect();
8154 // Create a route for each amount
8155 let example_amount = 100000;
8156 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);
8157 let sample_path = route.paths.pop().unwrap();
8158 for i in 0..routing_node_count {
8159 let routing_node = 2 + i;
8160 let mut path = sample_path.clone();
8161 path.hops[0].pubkey = nodes[routing_node].node.get_our_node_id();
8162 path.hops[0].short_channel_id = src_chan_ids[i];
8163 path.hops[1].pubkey = nodes[dst_idx].node.get_our_node_id();
8164 path.hops[1].short_channel_id = dst_chan_ids[i];
8165 path.hops[1].fee_msat = msat_amounts[i];
8166 route.paths.push(path);
8169 // Send payment with manually set total_msat
8170 let payment_id = PaymentId(nodes[src_idx].keys_manager.backing.get_secure_random_bytes());
8171 let onion_session_privs = nodes[src_idx].node.test_add_new_pending_payment(our_payment_hash,
8172 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8173 nodes[src_idx].node.test_send_payment_internal(&route, our_payment_hash,
8174 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8175 check_added_monitors!(nodes[src_idx], expected_paths.len());
8177 let mut events = nodes[src_idx].node.get_and_clear_pending_msg_events();
8178 assert_eq!(events.len(), expected_paths.len());
8179 let mut amount_received = 0;
8180 for (path_idx, expected_path) in expected_paths.iter().enumerate() {
8181 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
8183 let current_path_amount = msat_amounts[path_idx];
8184 amount_received += current_path_amount;
8185 let became_claimable_now = amount_received >= total_msat && amount_received - current_path_amount < total_msat;
8186 pass_along_path(&nodes[src_idx], expected_path, amount_received, our_payment_hash.clone(), Some(our_payment_secret), ev, became_claimable_now, None);
8189 claim_payment_along_route(&nodes[src_idx], &expected_paths, false, our_payment_preimage);
8193 fn test_overshoot_mpp() {
8194 do_test_overshoot_mpp(&[100_000, 101_000], 200_000);
8195 do_test_overshoot_mpp(&[100_000, 10_000, 100_000], 200_000);
8199 fn test_simple_mpp() {
8200 // Simple test of sending a multi-path payment.
8201 let chanmon_cfgs = create_chanmon_cfgs(4);
8202 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8203 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8204 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8206 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8207 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8208 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8209 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8211 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8212 let path = route.paths[0].clone();
8213 route.paths.push(path);
8214 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
8215 route.paths[0].hops[0].short_channel_id = chan_1_id;
8216 route.paths[0].hops[1].short_channel_id = chan_3_id;
8217 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
8218 route.paths[1].hops[0].short_channel_id = chan_2_id;
8219 route.paths[1].hops[1].short_channel_id = chan_4_id;
8220 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8221 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8225 fn test_preimage_storage() {
8226 // Simple test of payment preimage storage allowing no client-side storage to claim payments
8227 let chanmon_cfgs = create_chanmon_cfgs(2);
8228 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8229 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8230 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8232 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8235 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
8236 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8237 nodes[0].node.send_payment_with_route(&route, payment_hash,
8238 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8239 check_added_monitors!(nodes[0], 1);
8240 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8241 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8242 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8243 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8245 // Note that after leaving the above scope we have no knowledge of any arguments or return
8246 // values from previous calls.
8247 expect_pending_htlcs_forwardable!(nodes[1]);
8248 let events = nodes[1].node.get_and_clear_pending_events();
8249 assert_eq!(events.len(), 1);
8251 Event::PaymentClaimable { ref purpose, .. } => {
8253 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8254 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8256 _ => panic!("expected PaymentPurpose::InvoicePayment")
8259 _ => panic!("Unexpected event"),
8264 fn test_bad_secret_hash() {
8265 // Simple test of unregistered payment hash/invalid payment secret handling
8266 let chanmon_cfgs = create_chanmon_cfgs(2);
8267 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8268 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8269 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8271 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8273 let random_payment_hash = PaymentHash([42; 32]);
8274 let random_payment_secret = PaymentSecret([43; 32]);
8275 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8276 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8278 // All the below cases should end up being handled exactly identically, so we macro the
8279 // resulting events.
8280 macro_rules! handle_unknown_invalid_payment_data {
8281 ($payment_hash: expr) => {
8282 check_added_monitors!(nodes[0], 1);
8283 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8284 let payment_event = SendEvent::from_event(events.pop().unwrap());
8285 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8286 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8288 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8289 // again to process the pending backwards-failure of the HTLC
8290 expect_pending_htlcs_forwardable!(nodes[1]);
8291 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8292 check_added_monitors!(nodes[1], 1);
8294 // We should fail the payment back
8295 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8296 match events.pop().unwrap() {
8297 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8298 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8299 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8301 _ => panic!("Unexpected event"),
8306 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8307 // Error data is the HTLC value (100,000) and current block height
8308 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8310 // Send a payment with the right payment hash but the wrong payment secret
8311 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
8312 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8313 handle_unknown_invalid_payment_data!(our_payment_hash);
8314 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8316 // Send a payment with a random payment hash, but the right payment secret
8317 nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8318 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8319 handle_unknown_invalid_payment_data!(random_payment_hash);
8320 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8322 // Send a payment with a random payment hash and random payment secret
8323 nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8324 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8325 handle_unknown_invalid_payment_data!(random_payment_hash);
8326 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8330 fn test_update_err_monitor_lockdown() {
8331 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8332 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8333 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8336 // This scenario may happen in a watchtower setup, where watchtower process a block height
8337 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8338 // commitment at same time.
8340 let chanmon_cfgs = create_chanmon_cfgs(2);
8341 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8342 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8343 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8345 // Create some initial channel
8346 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8347 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8349 // Rebalance the network to generate htlc in the two directions
8350 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8352 // Route a HTLC from node 0 to node 1 (but don't settle)
8353 let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8355 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8356 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8357 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8358 let persister = test_utils::TestPersister::new();
8361 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8362 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8363 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8364 assert!(new_monitor == *monitor);
8367 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);
8368 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8371 let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8372 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8373 // transaction lock time requirements here.
8374 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 200));
8375 watchtower.chain_monitor.block_connected(&block, 200);
8377 // Try to update ChannelMonitor
8378 nodes[1].node.claim_funds(preimage);
8379 check_added_monitors!(nodes[1], 1);
8380 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8382 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8383 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8384 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8386 let mut node_0_per_peer_lock;
8387 let mut node_0_peer_state_lock;
8388 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8389 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8390 assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8391 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8392 } else { assert!(false); }
8394 // Our local monitor is in-sync and hasn't processed yet timeout
8395 check_added_monitors!(nodes[0], 1);
8396 let events = nodes[0].node.get_and_clear_pending_events();
8397 assert_eq!(events.len(), 1);
8401 fn test_concurrent_monitor_claim() {
8402 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8403 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8404 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8405 // state N+1 confirms. Alice claims output from state N+1.
8407 let chanmon_cfgs = create_chanmon_cfgs(2);
8408 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8409 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8410 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8412 // Create some initial channel
8413 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8414 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8416 // Rebalance the network to generate htlc in the two directions
8417 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8419 // Route a HTLC from node 0 to node 1 (but don't settle)
8420 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8422 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8423 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8424 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8425 let persister = test_utils::TestPersister::new();
8426 let alice_broadcaster = test_utils::TestBroadcaster::with_blocks(
8427 Arc::new(Mutex::new(nodes[0].blocks.lock().unwrap().clone())),
8429 let watchtower_alice = {
8431 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8432 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8433 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8434 assert!(new_monitor == *monitor);
8437 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &alice_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8438 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8441 let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8442 // Make Alice aware of enough blocks that it doesn't think we're violating transaction lock time
8443 // requirements here.
8444 const HTLC_TIMEOUT_BROADCAST: u32 = CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS;
8445 alice_broadcaster.blocks.lock().unwrap().resize((HTLC_TIMEOUT_BROADCAST) as usize, (block.clone(), HTLC_TIMEOUT_BROADCAST));
8446 watchtower_alice.chain_monitor.block_connected(&block, HTLC_TIMEOUT_BROADCAST);
8448 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8450 let mut txn = alice_broadcaster.txn_broadcast();
8451 assert_eq!(txn.len(), 2);
8455 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8456 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8457 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8458 let persister = test_utils::TestPersister::new();
8459 let bob_broadcaster = test_utils::TestBroadcaster::with_blocks(Arc::clone(&alice_broadcaster.blocks));
8460 let watchtower_bob = {
8462 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8463 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8464 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8465 assert!(new_monitor == *monitor);
8468 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &bob_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8469 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8472 watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST - 1);
8474 // Route another payment to generate another update with still previous HTLC pending
8475 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8476 nodes[1].node.send_payment_with_route(&route, payment_hash,
8477 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8478 check_added_monitors!(nodes[1], 1);
8480 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8481 assert_eq!(updates.update_add_htlcs.len(), 1);
8482 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8484 let mut node_0_per_peer_lock;
8485 let mut node_0_peer_state_lock;
8486 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8487 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8488 // Watchtower Alice should already have seen the block and reject the update
8489 assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8490 assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8491 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8492 } else { assert!(false); }
8494 // Our local monitor is in-sync and hasn't processed yet timeout
8495 check_added_monitors!(nodes[0], 1);
8497 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8498 watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST);
8500 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8503 let mut txn = bob_broadcaster.txn_broadcast();
8504 assert_eq!(txn.len(), 2);
8505 bob_state_y = txn.remove(0);
8508 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8509 let height = HTLC_TIMEOUT_BROADCAST + 1;
8510 connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
8511 check_closed_broadcast(&nodes[0], 1, true);
8512 check_closed_event!(&nodes[0], 1, ClosureReason::CommitmentTxConfirmed, false,
8513 [nodes[1].node.get_our_node_id()], 100000);
8514 watchtower_alice.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, vec![bob_state_y.clone()]), height);
8515 check_added_monitors(&nodes[0], 1);
8517 let htlc_txn = alice_broadcaster.txn_broadcast();
8518 assert_eq!(htlc_txn.len(), 2);
8519 check_spends!(htlc_txn[0], bob_state_y);
8520 // Alice doesn't clean up the old HTLC claim since it hasn't seen a conflicting spend for
8521 // it. However, she should, because it now has an invalid parent.
8522 check_spends!(htlc_txn[1], alice_state);
8527 fn test_pre_lockin_no_chan_closed_update() {
8528 // Test that if a peer closes a channel in response to a funding_created message we don't
8529 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8532 // Doing so would imply a channel monitor update before the initial channel monitor
8533 // registration, violating our API guarantees.
8535 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8536 // then opening a second channel with the same funding output as the first (which is not
8537 // rejected because the first channel does not exist in the ChannelManager) and closing it
8538 // before receiving funding_signed.
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 nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8544 // Create an initial channel
8545 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8546 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8547 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8548 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8549 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8551 // Move the first channel through the funding flow...
8552 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8554 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8555 check_added_monitors!(nodes[0], 0);
8557 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8558 let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8559 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8560 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8561 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("Hi".to_string()) }, true,
8562 [nodes[1].node.get_our_node_id(); 2], 100000);
8566 fn test_htlc_no_detection() {
8567 // This test is a mutation to underscore the detection logic bug we had
8568 // before #653. HTLC value routed is above the remaining balance, thus
8569 // inverting HTLC and `to_remote` output. HTLC will come second and
8570 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8571 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8572 // outputs order detection for correct spending children filtring.
8574 let chanmon_cfgs = create_chanmon_cfgs(2);
8575 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8576 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8577 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8579 // Create some initial channels
8580 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8582 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8583 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8584 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8585 assert_eq!(local_txn[0].input.len(), 1);
8586 assert_eq!(local_txn[0].output.len(), 3);
8587 check_spends!(local_txn[0], chan_1.3);
8589 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8590 let block = create_dummy_block(nodes[0].best_block_hash(), 42, vec![local_txn[0].clone()]);
8591 connect_block(&nodes[0], &block);
8592 // We deliberately connect the local tx twice as this should provoke a failure calling
8593 // this test before #653 fix.
8594 chain::Listen::block_connected(&nodes[0].chain_monitor.chain_monitor, &block, nodes[0].best_block_info().1 + 1);
8595 check_closed_broadcast!(nodes[0], true);
8596 check_added_monitors!(nodes[0], 1);
8597 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
8598 connect_blocks(&nodes[0], TEST_FINAL_CLTV);
8600 let htlc_timeout = {
8601 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8602 assert_eq!(node_txn.len(), 1);
8603 assert_eq!(node_txn[0].input.len(), 1);
8604 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8605 check_spends!(node_txn[0], local_txn[0]);
8609 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![htlc_timeout.clone()]));
8610 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8611 expect_payment_failed!(nodes[0], our_payment_hash, false);
8614 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8615 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8616 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8617 // Carol, Alice would be the upstream node, and Carol the downstream.)
8619 // Steps of the test:
8620 // 1) Alice sends a HTLC to Carol through Bob.
8621 // 2) Carol doesn't settle the HTLC.
8622 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8623 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8624 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8625 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8626 // 5) Carol release the preimage to Bob off-chain.
8627 // 6) Bob claims the offered output on the broadcasted commitment.
8628 let chanmon_cfgs = create_chanmon_cfgs(3);
8629 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8630 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8631 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8633 // Create some initial channels
8634 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8635 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8637 // Steps (1) and (2):
8638 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8639 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8641 // Check that Alice's commitment transaction now contains an output for this HTLC.
8642 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8643 check_spends!(alice_txn[0], chan_ab.3);
8644 assert_eq!(alice_txn[0].output.len(), 2);
8645 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8646 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8647 assert_eq!(alice_txn.len(), 2);
8649 // Steps (3) and (4):
8650 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8651 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8652 let mut force_closing_node = 0; // Alice force-closes
8653 let mut counterparty_node = 1; // Bob if Alice force-closes
8656 if !broadcast_alice {
8657 force_closing_node = 1;
8658 counterparty_node = 0;
8660 nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8661 check_closed_broadcast!(nodes[force_closing_node], true);
8662 check_added_monitors!(nodes[force_closing_node], 1);
8663 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed, [nodes[counterparty_node].node.get_our_node_id()], 100000);
8664 if go_onchain_before_fulfill {
8665 let txn_to_broadcast = match broadcast_alice {
8666 true => alice_txn.clone(),
8667 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8669 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8670 if broadcast_alice {
8671 check_closed_broadcast!(nodes[1], true);
8672 check_added_monitors!(nodes[1], 1);
8673 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
8678 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8679 // process of removing the HTLC from their commitment transactions.
8680 nodes[2].node.claim_funds(payment_preimage);
8681 check_added_monitors!(nodes[2], 1);
8682 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8684 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8685 assert!(carol_updates.update_add_htlcs.is_empty());
8686 assert!(carol_updates.update_fail_htlcs.is_empty());
8687 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8688 assert!(carol_updates.update_fee.is_none());
8689 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8691 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8692 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
8693 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8694 if !go_onchain_before_fulfill && broadcast_alice {
8695 let events = nodes[1].node.get_and_clear_pending_msg_events();
8696 assert_eq!(events.len(), 1);
8698 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8699 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8701 _ => panic!("Unexpected event"),
8704 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8705 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8706 // Carol<->Bob's updated commitment transaction info.
8707 check_added_monitors!(nodes[1], 2);
8709 let events = nodes[1].node.get_and_clear_pending_msg_events();
8710 assert_eq!(events.len(), 2);
8711 let bob_revocation = match events[0] {
8712 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8713 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8716 _ => panic!("Unexpected event"),
8718 let bob_updates = match events[1] {
8719 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8720 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8723 _ => panic!("Unexpected event"),
8726 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8727 check_added_monitors!(nodes[2], 1);
8728 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8729 check_added_monitors!(nodes[2], 1);
8731 let events = nodes[2].node.get_and_clear_pending_msg_events();
8732 assert_eq!(events.len(), 1);
8733 let carol_revocation = match events[0] {
8734 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8735 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8738 _ => panic!("Unexpected event"),
8740 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8741 check_added_monitors!(nodes[1], 1);
8743 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8744 // here's where we put said channel's commitment tx on-chain.
8745 let mut txn_to_broadcast = alice_txn.clone();
8746 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8747 if !go_onchain_before_fulfill {
8748 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8749 // If Bob was the one to force-close, he will have already passed these checks earlier.
8750 if broadcast_alice {
8751 check_closed_broadcast!(nodes[1], true);
8752 check_added_monitors!(nodes[1], 1);
8753 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
8755 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8756 if broadcast_alice {
8757 assert_eq!(bob_txn.len(), 1);
8758 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8760 assert_eq!(bob_txn.len(), 2);
8761 check_spends!(bob_txn[0], chan_ab.3);
8766 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8767 // broadcasted commitment transaction.
8769 let script_weight = match broadcast_alice {
8770 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8771 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8773 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8774 // Bob force-closed and broadcasts the commitment transaction along with a
8775 // HTLC-output-claiming transaction.
8776 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8777 if broadcast_alice {
8778 assert_eq!(bob_txn.len(), 1);
8779 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8780 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8782 assert_eq!(bob_txn.len(), 2);
8783 check_spends!(bob_txn[1], txn_to_broadcast[0]);
8784 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8790 fn test_onchain_htlc_settlement_after_close() {
8791 do_test_onchain_htlc_settlement_after_close(true, true);
8792 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8793 do_test_onchain_htlc_settlement_after_close(true, false);
8794 do_test_onchain_htlc_settlement_after_close(false, false);
8798 fn test_duplicate_temporary_channel_id_from_different_peers() {
8799 // Tests that we can accept two different `OpenChannel` requests with the same
8800 // `temporary_channel_id`, as long as they are from different peers.
8801 let chanmon_cfgs = create_chanmon_cfgs(3);
8802 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8803 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8804 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8806 // Create an first channel channel
8807 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8808 let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8810 // Create an second channel
8811 nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None).unwrap();
8812 let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8814 // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8815 // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8816 open_chan_msg_chan_2_0.temporary_channel_id = open_chan_msg_chan_1_0.temporary_channel_id;
8818 // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8819 // `temporary_channel_id` as they are from different peers.
8820 nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
8822 let events = nodes[0].node.get_and_clear_pending_msg_events();
8823 assert_eq!(events.len(), 1);
8825 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8826 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8827 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8829 _ => panic!("Unexpected event"),
8833 nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
8835 let events = nodes[0].node.get_and_clear_pending_msg_events();
8836 assert_eq!(events.len(), 1);
8838 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8839 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
8840 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8842 _ => panic!("Unexpected event"),
8848 fn test_duplicate_chan_id() {
8849 // Test that if a given peer tries to open a channel with the same channel_id as one that is
8850 // already open we reject it and keep the old channel.
8852 // Previously, full_stack_target managed to figure out that if you tried to open two channels
8853 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8854 // the existing channel when we detect the duplicate new channel, screwing up our monitor
8855 // updating logic for the existing channel.
8856 let chanmon_cfgs = create_chanmon_cfgs(2);
8857 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8858 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8859 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8861 // Create an initial channel
8862 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8863 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8864 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8865 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()));
8867 // Try to create a second channel with the same temporary_channel_id as the first and check
8868 // that it is rejected.
8869 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8871 let events = nodes[1].node.get_and_clear_pending_msg_events();
8872 assert_eq!(events.len(), 1);
8874 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8875 // Technically, at this point, nodes[1] would be justified in thinking both the
8876 // first (valid) and second (invalid) channels are closed, given they both have
8877 // the same non-temporary channel_id. However, currently we do not, so we just
8878 // move forward with it.
8879 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8880 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8882 _ => panic!("Unexpected event"),
8886 // Move the first channel through the funding flow...
8887 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8889 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8890 check_added_monitors!(nodes[0], 0);
8892 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8893 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8895 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8896 assert_eq!(added_monitors.len(), 1);
8897 assert_eq!(added_monitors[0].0, funding_output);
8898 added_monitors.clear();
8900 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
8902 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8904 let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8905 let channel_id = funding_outpoint.to_channel_id();
8907 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8910 // First try to open a second channel with a temporary channel id equal to the txid-based one.
8911 // Technically this is allowed by the spec, but we don't support it and there's little reason
8912 // to. Still, it shouldn't cause any other issues.
8913 open_chan_msg.temporary_channel_id = channel_id;
8914 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8916 let events = nodes[1].node.get_and_clear_pending_msg_events();
8917 assert_eq!(events.len(), 1);
8919 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8920 // Technically, at this point, nodes[1] would be justified in thinking both
8921 // channels are closed, but currently we do not, so we just move forward with it.
8922 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8923 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8925 _ => panic!("Unexpected event"),
8929 // Now try to create a second channel which has a duplicate funding output.
8930 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8931 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8932 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
8933 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()));
8934 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
8936 let (_, funding_created) = {
8937 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
8938 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
8939 // Once we call `get_funding_created` the channel has a duplicate channel_id as
8940 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
8941 // try to create another channel. Instead, we drop the channel entirely here (leaving the
8942 // channelmanager in a possibly nonsense state instead).
8943 let mut as_chan = a_peer_state.outbound_v1_channel_by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
8944 let logger = test_utils::TestLogger::new();
8945 as_chan.get_funding_created(tx.clone(), funding_outpoint, &&logger).map_err(|_| ()).unwrap()
8947 check_added_monitors!(nodes[0], 0);
8948 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8949 // At this point we'll look up if the channel_id is present and immediately fail the channel
8950 // without trying to persist the `ChannelMonitor`.
8951 check_added_monitors!(nodes[1], 0);
8953 // ...still, nodes[1] will reject the duplicate channel.
8955 let events = nodes[1].node.get_and_clear_pending_msg_events();
8956 assert_eq!(events.len(), 1);
8958 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8959 // Technically, at this point, nodes[1] would be justified in thinking both
8960 // channels are closed, but currently we do not, so we just move forward with it.
8961 assert_eq!(msg.channel_id, channel_id);
8962 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8964 _ => panic!("Unexpected event"),
8968 // finally, finish creating the original channel and send a payment over it to make sure
8969 // everything is functional.
8970 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8972 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8973 assert_eq!(added_monitors.len(), 1);
8974 assert_eq!(added_monitors[0].0, funding_output);
8975 added_monitors.clear();
8977 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
8979 let events_4 = nodes[0].node.get_and_clear_pending_events();
8980 assert_eq!(events_4.len(), 0);
8981 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8982 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8984 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8985 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
8986 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8988 send_payment(&nodes[0], &[&nodes[1]], 8000000);
8992 fn test_error_chans_closed() {
8993 // Test that we properly handle error messages, closing appropriate channels.
8995 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8996 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8997 // we can test various edge cases around it to ensure we don't regress.
8998 let chanmon_cfgs = create_chanmon_cfgs(3);
8999 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9000 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9001 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9003 // Create some initial channels
9004 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9005 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9006 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
9008 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9009 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9010 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9012 // Closing a channel from a different peer has no effect
9013 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9014 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9016 // Closing one channel doesn't impact others
9017 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9018 check_added_monitors!(nodes[0], 1);
9019 check_closed_broadcast!(nodes[0], false);
9020 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) },
9021 [nodes[1].node.get_our_node_id()], 100000);
9022 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9023 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9024 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);
9025 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);
9027 // A null channel ID should close all channels
9028 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9029 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: ChannelId::new_zero(), data: "ERR".to_owned() });
9030 check_added_monitors!(nodes[0], 2);
9031 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) },
9032 [nodes[1].node.get_our_node_id(); 2], 100000);
9033 let events = nodes[0].node.get_and_clear_pending_msg_events();
9034 assert_eq!(events.len(), 2);
9036 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9037 assert_eq!(msg.contents.flags & 2, 2);
9039 _ => panic!("Unexpected event"),
9042 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9043 assert_eq!(msg.contents.flags & 2, 2);
9045 _ => panic!("Unexpected event"),
9047 // Note that at this point users of a standard PeerHandler will end up calling
9048 // peer_disconnected.
9049 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9050 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9052 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9053 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9054 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9058 fn test_invalid_funding_tx() {
9059 // Test that we properly handle invalid funding transactions sent to us from a peer.
9061 // Previously, all other major lightning implementations had failed to properly sanitize
9062 // funding transactions from their counterparties, leading to a multi-implementation critical
9063 // security vulnerability (though we always sanitized properly, we've previously had
9064 // un-released crashes in the sanitization process).
9066 // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9067 // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9068 // gave up on it. We test this here by generating such a transaction.
9069 let chanmon_cfgs = create_chanmon_cfgs(2);
9070 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9071 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9072 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9074 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9075 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()));
9076 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()));
9078 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9080 // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9081 // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9082 // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9084 let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9085 let wit_program_script: Script = wit_program.into();
9086 for output in tx.output.iter_mut() {
9087 // Make the confirmed funding transaction have a bogus script_pubkey
9088 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9091 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9092 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()));
9093 check_added_monitors!(nodes[1], 1);
9094 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9096 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()));
9097 check_added_monitors!(nodes[0], 1);
9098 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9100 let events_1 = nodes[0].node.get_and_clear_pending_events();
9101 assert_eq!(events_1.len(), 0);
9103 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9104 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9105 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9107 let expected_err = "funding tx had wrong script/value or output index";
9108 confirm_transaction_at(&nodes[1], &tx, 1);
9109 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() },
9110 [nodes[0].node.get_our_node_id()], 100000);
9111 check_added_monitors!(nodes[1], 1);
9112 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9113 assert_eq!(events_2.len(), 1);
9114 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9115 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9116 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9117 assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9118 } else { panic!(); }
9119 } else { panic!(); }
9120 assert_eq!(nodes[1].node.list_channels().len(), 0);
9122 // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9123 // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9124 // as its not 32 bytes long.
9125 let mut spend_tx = Transaction {
9126 version: 2i32, lock_time: PackedLockTime::ZERO,
9127 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9128 previous_output: BitcoinOutPoint {
9132 script_sig: Script::new(),
9133 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9134 witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9136 output: vec![TxOut {
9138 script_pubkey: Script::new(),
9141 check_spends!(spend_tx, tx);
9142 mine_transaction(&nodes[1], &spend_tx);
9145 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9146 // In the first version of the chain::Confirm interface, after a refactor was made to not
9147 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9148 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9149 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9150 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9151 // spending transaction until height N+1 (or greater). This was due to the way
9152 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9153 // spending transaction at the height the input transaction was confirmed at, not whether we
9154 // should broadcast a spending transaction at the current height.
9155 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9156 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9157 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9158 // until we learned about an additional block.
9160 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9161 // aren't broadcasting transactions too early (ie not broadcasting them at all).
9162 let chanmon_cfgs = create_chanmon_cfgs(3);
9163 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9164 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9165 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9166 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9168 create_announced_chan_between_nodes(&nodes, 0, 1);
9169 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
9170 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9171 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
9172 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9174 nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9175 check_closed_broadcast!(nodes[1], true);
9176 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[2].node.get_our_node_id()], 100000);
9177 check_added_monitors!(nodes[1], 1);
9178 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9179 assert_eq!(node_txn.len(), 1);
9181 let conf_height = nodes[1].best_block_info().1;
9182 if !test_height_before_timelock {
9183 connect_blocks(&nodes[1], 24 * 6);
9185 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9186 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9187 if test_height_before_timelock {
9188 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9189 // generate any events or broadcast any transactions
9190 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9191 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9193 // We should broadcast an HTLC transaction spending our funding transaction first
9194 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9195 assert_eq!(spending_txn.len(), 2);
9196 assert_eq!(spending_txn[0].txid(), node_txn[0].txid());
9197 check_spends!(spending_txn[1], node_txn[0]);
9198 // We should also generate a SpendableOutputs event with the to_self output (as its
9200 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9201 assert_eq!(descriptor_spend_txn.len(), 1);
9203 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9204 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9205 // additional block built on top of the current chain.
9206 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9207 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9208 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 }]);
9209 check_added_monitors!(nodes[1], 1);
9211 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9212 assert!(updates.update_add_htlcs.is_empty());
9213 assert!(updates.update_fulfill_htlcs.is_empty());
9214 assert_eq!(updates.update_fail_htlcs.len(), 1);
9215 assert!(updates.update_fail_malformed_htlcs.is_empty());
9216 assert!(updates.update_fee.is_none());
9217 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9218 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9219 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9224 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9225 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9226 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9229 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9230 let chanmon_cfgs = create_chanmon_cfgs(2);
9231 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9232 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9233 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9235 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9237 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9238 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
9239 let route = get_route!(nodes[0], payment_params, 10_000).unwrap();
9241 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9244 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9245 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9246 check_added_monitors!(nodes[0], 1);
9247 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9248 assert_eq!(events.len(), 1);
9249 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9250 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9251 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9253 expect_pending_htlcs_forwardable!(nodes[1]);
9254 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9257 // Note that we use a different PaymentId here to allow us to duplicativly pay
9258 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9259 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9260 check_added_monitors!(nodes[0], 1);
9261 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9262 assert_eq!(events.len(), 1);
9263 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9264 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9265 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9266 // At this point, nodes[1] would notice it has too much value for the payment. It will
9267 // assume the second is a privacy attack (no longer particularly relevant
9268 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9269 // the first HTLC delivered above.
9272 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9273 nodes[1].node.process_pending_htlc_forwards();
9275 if test_for_second_fail_panic {
9276 // Now we go fail back the first HTLC from the user end.
9277 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9279 let expected_destinations = vec![
9280 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9281 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9283 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], expected_destinations);
9284 nodes[1].node.process_pending_htlc_forwards();
9286 check_added_monitors!(nodes[1], 1);
9287 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9288 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9290 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9291 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9292 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9294 let failure_events = nodes[0].node.get_and_clear_pending_events();
9295 assert_eq!(failure_events.len(), 4);
9296 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9297 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9298 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9299 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9301 // Let the second HTLC fail and claim the first
9302 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9303 nodes[1].node.process_pending_htlc_forwards();
9305 check_added_monitors!(nodes[1], 1);
9306 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9307 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9308 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9310 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9312 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9317 fn test_dup_htlc_second_fail_panic() {
9318 // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9319 // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9320 // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9321 // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9322 do_test_dup_htlc_second_rejected(true);
9326 fn test_dup_htlc_second_rejected() {
9327 // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9328 // simply reject the second HTLC but are still able to claim the first HTLC.
9329 do_test_dup_htlc_second_rejected(false);
9333 fn test_inconsistent_mpp_params() {
9334 // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9335 // such HTLC and allow the second to stay.
9336 let chanmon_cfgs = create_chanmon_cfgs(4);
9337 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9338 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9339 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9341 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9342 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9343 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9344 let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9346 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9347 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
9348 let mut route = get_route!(nodes[0], payment_params, 15_000_000).unwrap();
9349 assert_eq!(route.paths.len(), 2);
9350 route.paths.sort_by(|path_a, _| {
9351 // Sort the path so that the path through nodes[1] comes first
9352 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9353 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9356 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9358 let cur_height = nodes[0].best_block_info().1;
9359 let payment_id = PaymentId([42; 32]);
9361 let session_privs = {
9362 // We create a fake route here so that we start with three pending HTLCs, which we'll
9363 // ultimately have, just not right away.
9364 let mut dup_route = route.clone();
9365 dup_route.paths.push(route.paths[1].clone());
9366 nodes[0].node.test_add_new_pending_payment(our_payment_hash,
9367 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &dup_route).unwrap()
9369 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
9370 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9371 &None, session_privs[0]).unwrap();
9372 check_added_monitors!(nodes[0], 1);
9375 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9376 assert_eq!(events.len(), 1);
9377 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9379 assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9381 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9382 RecipientOnionFields::secret_only(our_payment_secret), 14_000_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9383 check_added_monitors!(nodes[0], 1);
9386 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9387 assert_eq!(events.len(), 1);
9388 let payment_event = SendEvent::from_event(events.pop().unwrap());
9390 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9391 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9393 expect_pending_htlcs_forwardable!(nodes[2]);
9394 check_added_monitors!(nodes[2], 1);
9396 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9397 assert_eq!(events.len(), 1);
9398 let payment_event = SendEvent::from_event(events.pop().unwrap());
9400 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9401 check_added_monitors!(nodes[3], 0);
9402 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9404 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9405 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9406 // post-payment_secrets) and fail back the new HTLC.
9408 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9409 nodes[3].node.process_pending_htlc_forwards();
9410 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9411 nodes[3].node.process_pending_htlc_forwards();
9413 check_added_monitors!(nodes[3], 1);
9415 let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9416 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9417 commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9419 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 }]);
9420 check_added_monitors!(nodes[2], 1);
9422 let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9423 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9424 commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9426 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9428 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9429 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9430 &None, session_privs[2]).unwrap();
9431 check_added_monitors!(nodes[0], 1);
9433 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9434 assert_eq!(events.len(), 1);
9435 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9437 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9438 expect_payment_sent(&nodes[0], our_payment_preimage, Some(None), true, true);
9442 fn test_double_partial_claim() {
9443 // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9444 // time out, the sender resends only some of the MPP parts, then the user processes the
9445 // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9447 let chanmon_cfgs = create_chanmon_cfgs(4);
9448 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9449 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9450 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9452 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9453 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9454 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9455 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9457 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9458 assert_eq!(route.paths.len(), 2);
9459 route.paths.sort_by(|path_a, _| {
9460 // Sort the path so that the path through nodes[1] comes first
9461 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9462 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9465 send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9466 // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9467 // amount of time to respond to.
9469 // Connect some blocks to time out the payment
9470 connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9471 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9473 let failed_destinations = vec![
9474 HTLCDestination::FailedPayment { payment_hash },
9475 HTLCDestination::FailedPayment { payment_hash },
9477 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9479 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
9481 // nodes[1] now retries one of the two paths...
9482 nodes[0].node.send_payment_with_route(&route, payment_hash,
9483 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9484 check_added_monitors!(nodes[0], 2);
9486 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9487 assert_eq!(events.len(), 2);
9488 let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
9489 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9491 // At this point nodes[3] has received one half of the payment, and the user goes to handle
9492 // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9493 nodes[3].node.claim_funds(payment_preimage);
9494 check_added_monitors!(nodes[3], 0);
9495 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9498 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9499 #[derive(Clone, Copy, PartialEq)]
9500 enum ExposureEvent {
9501 /// Breach occurs at HTLC forwarding (see `send_htlc`)
9503 /// Breach occurs at HTLC reception (see `update_add_htlc`)
9505 /// Breach occurs at outbound update_fee (see `send_update_fee`)
9506 AtUpdateFeeOutbound,
9509 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool, multiplier_dust_limit: bool) {
9510 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9513 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9514 // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9515 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9516 // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9517 // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9518 // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9519 // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9520 // might be available again for HTLC processing once the dust bandwidth has cleared up.
9522 let chanmon_cfgs = create_chanmon_cfgs(2);
9523 let mut config = test_default_channel_config();
9524 config.channel_config.max_dust_htlc_exposure = if multiplier_dust_limit {
9525 // Default test fee estimator rate is 253 sat/kw, so we set the multiplier to 5_000_000 / 253
9526 // to get roughly the same initial value as the default setting when this test was
9527 // originally written.
9528 MaxDustHTLCExposure::FeeRateMultiplier(5_000_000 / 253)
9529 } else { MaxDustHTLCExposure::FixedLimitMsat(5_000_000) }; // initial default setting value
9530 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9531 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9532 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9534 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9535 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9536 open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9537 open_channel.max_accepted_htlcs = 60;
9539 open_channel.dust_limit_satoshis = 546;
9541 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9542 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9543 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9545 let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
9547 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9550 let mut node_0_per_peer_lock;
9551 let mut node_0_peer_state_lock;
9552 let mut chan = get_outbound_v1_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, temporary_channel_id);
9553 chan.context.holder_dust_limit_satoshis = 546;
9556 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9557 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()));
9558 check_added_monitors!(nodes[1], 1);
9559 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9561 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()));
9562 check_added_monitors!(nodes[0], 1);
9563 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9565 let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9566 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9567 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9569 // Fetch a route in advance as we will be unable to once we're unable to send.
9570 let (mut route, payment_hash, _, payment_secret) =
9571 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
9573 let (dust_buffer_feerate, max_dust_htlc_exposure_msat) = {
9574 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9575 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9576 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
9577 (chan.context.get_dust_buffer_feerate(None) as u64,
9578 chan.context.get_max_dust_htlc_exposure_msat(&LowerBoundedFeeEstimator(nodes[0].fee_estimator)))
9580 let dust_outbound_htlc_on_holder_tx_msat: u64 = (dust_buffer_feerate * htlc_timeout_tx_weight(&channel_type_features) / 1000 + open_channel.dust_limit_satoshis - 1) * 1000;
9581 let dust_outbound_htlc_on_holder_tx: u64 = max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9583 let dust_inbound_htlc_on_holder_tx_msat: u64 = (dust_buffer_feerate * htlc_success_tx_weight(&channel_type_features) / 1000 + open_channel.dust_limit_satoshis - 1) * 1000;
9584 let dust_inbound_htlc_on_holder_tx: u64 = max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9586 let dust_htlc_on_counterparty_tx: u64 = 4;
9587 let dust_htlc_on_counterparty_tx_msat: u64 = max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9590 if dust_outbound_balance {
9591 // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9592 // Outbound dust balance: 4372 sats
9593 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9594 for _ in 0..dust_outbound_htlc_on_holder_tx {
9595 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9596 nodes[0].node.send_payment_with_route(&route, payment_hash,
9597 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9600 // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9601 // Inbound dust balance: 4372 sats
9602 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9603 for _ in 0..dust_inbound_htlc_on_holder_tx {
9604 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9608 if dust_outbound_balance {
9609 // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9610 // Outbound dust balance: 5000 sats
9611 for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9612 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9613 nodes[0].node.send_payment_with_route(&route, payment_hash,
9614 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9617 // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9618 // Inbound dust balance: 5000 sats
9619 for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9620 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9625 if exposure_breach_event == ExposureEvent::AtHTLCForward {
9626 route.paths[0].hops.last_mut().unwrap().fee_msat =
9627 if on_holder_tx { dust_outbound_htlc_on_holder_tx_msat } else { dust_htlc_on_counterparty_tx_msat + 1 };
9628 // With default dust exposure: 5000 sats
9630 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9631 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9632 ), true, APIError::ChannelUnavailable { .. }, {});
9634 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9635 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9636 ), true, APIError::ChannelUnavailable { .. }, {});
9638 } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9639 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 });
9640 nodes[1].node.send_payment_with_route(&route, payment_hash,
9641 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9642 check_added_monitors!(nodes[1], 1);
9643 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9644 assert_eq!(events.len(), 1);
9645 let payment_event = SendEvent::from_event(events.remove(0));
9646 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9647 // With default dust exposure: 5000 sats
9649 // Outbound dust balance: 6399 sats
9650 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9651 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9652 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on holder commitment tx", if dust_outbound_balance { dust_outbound_overflow } else { dust_inbound_overflow }, max_dust_htlc_exposure_msat), 1);
9654 // Outbound dust balance: 5200 sats
9655 nodes[0].logger.assert_log("lightning::ln::channel".to_string(),
9656 format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx",
9657 dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx - 1) + dust_htlc_on_counterparty_tx_msat + 4,
9658 max_dust_htlc_exposure_msat), 1);
9660 } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9661 route.paths[0].hops.last_mut().unwrap().fee_msat = 2_500_000;
9662 // For the multiplier dust exposure limit, since it scales with feerate,
9663 // we need to add a lot of HTLCs that will become dust at the new feerate
9664 // to cross the threshold.
9666 let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[1], Some(1_000), None);
9667 nodes[0].node.send_payment_with_route(&route, payment_hash,
9668 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9671 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9672 *feerate_lock = *feerate_lock * 10;
9674 nodes[0].node.timer_tick_occurred();
9675 check_added_monitors!(nodes[0], 1);
9676 nodes[0].logger.assert_log_contains("lightning::ln::channel", "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure", 1);
9679 let _ = nodes[0].node.get_and_clear_pending_msg_events();
9680 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9681 added_monitors.clear();
9684 fn do_test_max_dust_htlc_exposure_by_threshold_type(multiplier_dust_limit: bool) {
9685 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true, multiplier_dust_limit);
9686 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true, multiplier_dust_limit);
9687 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true, multiplier_dust_limit);
9688 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false, multiplier_dust_limit);
9689 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false, multiplier_dust_limit);
9690 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false, multiplier_dust_limit);
9691 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true, multiplier_dust_limit);
9692 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false, multiplier_dust_limit);
9693 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true, multiplier_dust_limit);
9694 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false, multiplier_dust_limit);
9695 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false, multiplier_dust_limit);
9696 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true, multiplier_dust_limit);
9700 fn test_max_dust_htlc_exposure() {
9701 do_test_max_dust_htlc_exposure_by_threshold_type(false);
9702 do_test_max_dust_htlc_exposure_by_threshold_type(true);
9706 fn test_non_final_funding_tx() {
9707 let chanmon_cfgs = create_chanmon_cfgs(2);
9708 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9709 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9710 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9712 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9713 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9714 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9715 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9716 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
9718 let best_height = nodes[0].node.best_block.read().unwrap().height();
9720 let chan_id = *nodes[0].network_chan_count.borrow();
9721 let events = nodes[0].node.get_and_clear_pending_events();
9722 let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
9723 assert_eq!(events.len(), 1);
9724 let mut tx = match events[0] {
9725 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9726 // Timelock the transaction _beyond_ the best client height + 1.
9727 Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 2), input: vec![input], output: vec![TxOut {
9728 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9731 _ => panic!("Unexpected event"),
9733 // Transaction should fail as it's evaluated as non-final for propagation.
9734 match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
9735 Err(APIError::APIMisuseError { err }) => {
9736 assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
9741 // However, transaction should be accepted if it's in a +1 headroom from best block.
9742 tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
9743 assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
9744 get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9748 fn accept_busted_but_better_fee() {
9749 // If a peer sends us a fee update that is too low, but higher than our previous channel
9750 // feerate, we should accept it. In the future we may want to consider closing the channel
9751 // later, but for now we only accept the update.
9752 let mut chanmon_cfgs = create_chanmon_cfgs(2);
9753 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9754 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9755 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9757 create_chan_between_nodes(&nodes[0], &nodes[1]);
9759 // Set nodes[1] to expect 5,000 sat/kW.
9761 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
9762 *feerate_lock = 5000;
9765 // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
9767 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9768 *feerate_lock = 1000;
9770 nodes[0].node.timer_tick_occurred();
9771 check_added_monitors!(nodes[0], 1);
9773 let events = nodes[0].node.get_and_clear_pending_msg_events();
9774 assert_eq!(events.len(), 1);
9776 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9777 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9778 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9780 _ => panic!("Unexpected event"),
9783 // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
9786 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9787 *feerate_lock = 2000;
9789 nodes[0].node.timer_tick_occurred();
9790 check_added_monitors!(nodes[0], 1);
9792 let events = nodes[0].node.get_and_clear_pending_msg_events();
9793 assert_eq!(events.len(), 1);
9795 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9796 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9797 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9799 _ => panic!("Unexpected event"),
9802 // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
9805 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9806 *feerate_lock = 1000;
9808 nodes[0].node.timer_tick_occurred();
9809 check_added_monitors!(nodes[0], 1);
9811 let events = nodes[0].node.get_and_clear_pending_msg_events();
9812 assert_eq!(events.len(), 1);
9814 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
9815 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9816 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
9817 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000 (- 250)".to_owned() },
9818 [nodes[0].node.get_our_node_id()], 100000);
9819 check_closed_broadcast!(nodes[1], true);
9820 check_added_monitors!(nodes[1], 1);
9822 _ => panic!("Unexpected event"),
9826 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
9827 let mut chanmon_cfgs = create_chanmon_cfgs(2);
9828 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9829 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9830 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9831 let min_final_cltv_expiry_delta = 120;
9832 let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
9833 min_final_cltv_expiry_delta - 2 };
9834 let recv_value = 100_000;
9836 create_chan_between_nodes(&nodes[0], &nodes[1]);
9838 let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), final_cltv_expiry_delta as u32);
9839 let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
9840 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
9841 Some(recv_value), Some(min_final_cltv_expiry_delta));
9842 (payment_hash, payment_preimage, payment_secret)
9844 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
9845 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
9847 let route = get_route!(nodes[0], payment_parameters, recv_value).unwrap();
9848 nodes[0].node.send_payment_with_route(&route, payment_hash,
9849 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9850 check_added_monitors!(nodes[0], 1);
9851 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9852 assert_eq!(events.len(), 1);
9853 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9854 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9855 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9856 expect_pending_htlcs_forwardable!(nodes[1]);
9859 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
9860 None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
9862 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9864 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
9866 check_added_monitors!(nodes[1], 1);
9868 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9869 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
9870 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
9872 expect_payment_failed!(nodes[0], payment_hash, true);
9877 fn test_payment_with_custom_min_cltv_expiry_delta() {
9878 do_payment_with_custom_min_final_cltv_expiry(false, false);
9879 do_payment_with_custom_min_final_cltv_expiry(false, true);
9880 do_payment_with_custom_min_final_cltv_expiry(true, false);
9881 do_payment_with_custom_min_final_cltv_expiry(true, true);
9885 fn test_disconnects_peer_awaiting_response_ticks() {
9886 // Tests that nodes which are awaiting on a response critical for channel responsiveness
9887 // disconnect their counterparty after `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
9888 let mut chanmon_cfgs = create_chanmon_cfgs(2);
9889 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9890 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9891 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9893 // Asserts a disconnect event is queued to the user.
9894 let check_disconnect_event = |node: &Node, should_disconnect: bool| {
9895 let disconnect_event = node.node.get_and_clear_pending_msg_events().iter().find_map(|event|
9896 if let MessageSendEvent::HandleError { action, .. } = event {
9897 if let msgs::ErrorAction::DisconnectPeerWithWarning { .. } = action {
9906 assert_eq!(disconnect_event.is_some(), should_disconnect);
9909 // Fires timer ticks ensuring we only attempt to disconnect peers after reaching
9910 // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
9911 let check_disconnect = |node: &Node| {
9912 // No disconnect without any timer ticks.
9913 check_disconnect_event(node, false);
9915 // No disconnect with 1 timer tick less than required.
9916 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS - 1 {
9917 node.node.timer_tick_occurred();
9918 check_disconnect_event(node, false);
9921 // Disconnect after reaching the required ticks.
9922 node.node.timer_tick_occurred();
9923 check_disconnect_event(node, true);
9925 // Disconnect again on the next tick if the peer hasn't been disconnected yet.
9926 node.node.timer_tick_occurred();
9927 check_disconnect_event(node, true);
9930 create_chan_between_nodes(&nodes[0], &nodes[1]);
9932 // We'll start by performing a fee update with Alice (nodes[0]) on the channel.
9933 *nodes[0].fee_estimator.sat_per_kw.lock().unwrap() *= 2;
9934 nodes[0].node.timer_tick_occurred();
9935 check_added_monitors!(&nodes[0], 1);
9936 let alice_fee_update = get_htlc_update_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
9937 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), alice_fee_update.update_fee.as_ref().unwrap());
9938 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &alice_fee_update.commitment_signed);
9939 check_added_monitors!(&nodes[1], 1);
9941 // This will prompt Bob (nodes[1]) to respond with his `CommitmentSigned` and `RevokeAndACK`.
9942 let (bob_revoke_and_ack, bob_commitment_signed) = get_revoke_commit_msgs!(&nodes[1], nodes[0].node.get_our_node_id());
9943 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revoke_and_ack);
9944 check_added_monitors!(&nodes[0], 1);
9945 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_commitment_signed);
9946 check_added_monitors(&nodes[0], 1);
9948 // Alice then needs to send her final `RevokeAndACK` to complete the commitment dance. We
9949 // pretend Bob hasn't received the message and check whether he'll disconnect Alice after
9950 // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
9951 let alice_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
9952 check_disconnect(&nodes[1]);
9954 // Now, we'll reconnect them to test awaiting a `ChannelReestablish` message.
9956 // Note that since the commitment dance didn't complete above, Alice is expected to resend her
9957 // final `RevokeAndACK` to Bob to complete it.
9958 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9959 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
9960 let bob_init = msgs::Init {
9961 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
9963 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &bob_init, true).unwrap();
9964 let alice_init = msgs::Init {
9965 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
9967 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &alice_init, true).unwrap();
9969 // Upon reconnection, Alice sends her `ChannelReestablish` to Bob. Alice, however, hasn't
9970 // received Bob's yet, so she should disconnect him after reaching
9971 // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
9972 let alice_channel_reestablish = get_event_msg!(
9973 nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id()
9975 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &alice_channel_reestablish);
9976 check_disconnect(&nodes[0]);
9978 // Bob now sends his `ChannelReestablish` to Alice to resume the channel and consider it "live".
9979 let bob_channel_reestablish = nodes[1].node.get_and_clear_pending_msg_events().iter().find_map(|event|
9980 if let MessageSendEvent::SendChannelReestablish { node_id, msg } = event {
9981 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9987 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bob_channel_reestablish);
9989 // Sanity check that Alice won't disconnect Bob since she's no longer waiting for any messages.
9990 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
9991 nodes[0].node.timer_tick_occurred();
9992 check_disconnect_event(&nodes[0], false);
9995 // However, Bob is still waiting on Alice's `RevokeAndACK`, so he should disconnect her after
9996 // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
9997 check_disconnect(&nodes[1]);
9999 // Finally, have Bob process the last message.
10000 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &alice_revoke_and_ack);
10001 check_added_monitors(&nodes[1], 1);
10003 // At this point, neither node should attempt to disconnect each other, since they aren't
10004 // waiting on any messages.
10005 for node in &nodes {
10006 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
10007 node.node.timer_tick_occurred();
10008 check_disconnect_event(node, false);
10014 fn test_remove_expired_outbound_unfunded_channels() {
10015 let chanmon_cfgs = create_chanmon_cfgs(2);
10016 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10017 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10018 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10020 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10021 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10022 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10023 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10024 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10026 let events = nodes[0].node.get_and_clear_pending_events();
10027 assert_eq!(events.len(), 1);
10029 Event::FundingGenerationReady { .. } => (),
10030 _ => panic!("Unexpected event"),
10033 // Asserts the outbound channel has been removed from a nodes[0]'s peer state map.
10034 let check_outbound_channel_existence = |should_exist: bool| {
10035 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
10036 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
10037 assert_eq!(chan_lock.outbound_v1_channel_by_id.contains_key(&temp_channel_id), should_exist);
10040 // Channel should exist without any timer ticks.
10041 check_outbound_channel_existence(true);
10043 // Channel should exist with 1 timer tick less than required.
10044 for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS - 1 {
10045 nodes[0].node.timer_tick_occurred();
10046 check_outbound_channel_existence(true)
10049 // Remove channel after reaching the required ticks.
10050 nodes[0].node.timer_tick_occurred();
10051 check_outbound_channel_existence(false);
10053 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
10054 assert_eq!(msg_events.len(), 1);
10055 match msg_events[0] {
10056 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
10057 assert_eq!(msg.data, "Force-closing pending channel due to timeout awaiting establishment handshake");
10059 _ => panic!("Unexpected event"),
10061 check_closed_event(&nodes[0], 1, ClosureReason::HolderForceClosed, false, &[nodes[1].node.get_our_node_id()], 100000);
10065 fn test_remove_expired_inbound_unfunded_channels() {
10066 let chanmon_cfgs = create_chanmon_cfgs(2);
10067 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10068 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10069 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10071 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10072 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10073 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10074 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10075 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10077 let events = nodes[0].node.get_and_clear_pending_events();
10078 assert_eq!(events.len(), 1);
10080 Event::FundingGenerationReady { .. } => (),
10081 _ => panic!("Unexpected event"),
10084 // Asserts the inbound channel has been removed from a nodes[1]'s peer state map.
10085 let check_inbound_channel_existence = |should_exist: bool| {
10086 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
10087 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
10088 assert_eq!(chan_lock.inbound_v1_channel_by_id.contains_key(&temp_channel_id), should_exist);
10091 // Channel should exist without any timer ticks.
10092 check_inbound_channel_existence(true);
10094 // Channel should exist with 1 timer tick less than required.
10095 for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS - 1 {
10096 nodes[1].node.timer_tick_occurred();
10097 check_inbound_channel_existence(true)
10100 // Remove channel after reaching the required ticks.
10101 nodes[1].node.timer_tick_occurred();
10102 check_inbound_channel_existence(false);
10104 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
10105 assert_eq!(msg_events.len(), 1);
10106 match msg_events[0] {
10107 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
10108 assert_eq!(msg.data, "Force-closing pending channel due to timeout awaiting establishment handshake");
10110 _ => panic!("Unexpected event"),
10112 check_closed_event(&nodes[1], 1, ClosureReason::HolderForceClosed, false, &[nodes[0].node.get_our_node_id()], 100000);
10115 fn do_test_multi_post_event_actions(do_reload: bool) {
10116 // Tests handling multiple post-Event actions at once.
10117 // There is specific code in ChannelManager to handle channels where multiple post-Event
10118 // `ChannelMonitorUpdates` are pending at once. This test exercises that code.
10120 // Specifically, we test calling `get_and_clear_pending_events` while there are two
10121 // PaymentSents from different channels and one channel has two pending `ChannelMonitorUpdate`s
10122 // - one from an RAA and one from an inbound commitment_signed.
10123 let chanmon_cfgs = create_chanmon_cfgs(3);
10124 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10125 let (persister, chain_monitor);
10126 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10127 let nodes_0_deserialized;
10128 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10130 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
10131 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 0, 2).2;
10133 send_payment(&nodes[0], &[&nodes[1]], 1_000_000);
10134 send_payment(&nodes[0], &[&nodes[2]], 1_000_000);
10136 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
10137 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[2]], 1_000_000);
10139 nodes[1].node.claim_funds(our_payment_preimage);
10140 check_added_monitors!(nodes[1], 1);
10141 expect_payment_claimed!(nodes[1], our_payment_hash, 1_000_000);
10143 nodes[2].node.claim_funds(payment_preimage_2);
10144 check_added_monitors!(nodes[2], 1);
10145 expect_payment_claimed!(nodes[2], payment_hash_2, 1_000_000);
10147 for dest in &[1, 2] {
10148 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[*dest], nodes[0].node.get_our_node_id());
10149 nodes[0].node.handle_update_fulfill_htlc(&nodes[*dest].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
10150 commitment_signed_dance!(nodes[0], nodes[*dest], htlc_fulfill_updates.commitment_signed, false);
10151 check_added_monitors(&nodes[0], 0);
10154 let (route, payment_hash_3, _, payment_secret_3) =
10155 get_route_and_payment_hash!(nodes[1], nodes[0], 100_000);
10156 let payment_id = PaymentId(payment_hash_3.0);
10157 nodes[1].node.send_payment_with_route(&route, payment_hash_3,
10158 RecipientOnionFields::secret_only(payment_secret_3), payment_id).unwrap();
10159 check_added_monitors(&nodes[1], 1);
10161 let send_event = SendEvent::from_node(&nodes[1]);
10162 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event.msgs[0]);
10163 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_event.commitment_msg);
10164 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
10167 let nodes_0_serialized = nodes[0].node.encode();
10168 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
10169 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_2).encode();
10170 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);
10172 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10173 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10175 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
10176 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[2]));
10179 let events = nodes[0].node.get_and_clear_pending_events();
10180 assert_eq!(events.len(), 4);
10181 if let Event::PaymentSent { payment_preimage, .. } = events[0] {
10182 assert!(payment_preimage == our_payment_preimage || payment_preimage == payment_preimage_2);
10183 } else { panic!(); }
10184 if let Event::PaymentSent { payment_preimage, .. } = events[1] {
10185 assert!(payment_preimage == our_payment_preimage || payment_preimage == payment_preimage_2);
10186 } else { panic!(); }
10187 if let Event::PaymentPathSuccessful { .. } = events[2] {} else { panic!(); }
10188 if let Event::PaymentPathSuccessful { .. } = events[3] {} else { panic!(); }
10190 // After the events are processed, the ChannelMonitorUpdates will be released and, upon their
10191 // completion, we'll respond to nodes[1] with an RAA + CS.
10192 get_revoke_commit_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
10193 check_added_monitors(&nodes[0], 3);
10197 fn test_multi_post_event_actions() {
10198 do_test_multi_post_event_actions(true);
10199 do_test_multi_post_event_actions(false);