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};
21 use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentPurpose, ClosureReason, HTLCDestination, PaymentFailureReason};
22 use crate::ln::{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};
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::{Channel, 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, RouteParameters, find_route, get_route};
30 use crate::ln::features::{ChannelFeatures, NodeFeatures};
32 use crate::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction};
33 use crate::util::enforcing_trait_impls::EnforcingSigner;
34 use crate::util::test_utils;
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;
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};
61 use crate::ln::functional_test_utils::*;
62 use crate::ln::chan_utils::CommitmentTransaction;
65 fn test_insane_channel_opens() {
66 // Stand up a network of 2 nodes
67 use crate::ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
68 let mut cfg = UserConfig::default();
69 cfg.channel_handshake_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
70 let chanmon_cfgs = create_chanmon_cfgs(2);
71 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
72 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
73 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
75 // Instantiate channel parameters where we push the maximum msats given our
77 let channel_value_sat = 31337; // same as funding satoshis
78 let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat, &cfg);
79 let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
81 // Have node0 initiate a channel to node1 with aforementioned parameters
82 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
84 // Extract the channel open message from node0 to node1
85 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
87 // Test helper that asserts we get the correct error string given a mutator
88 // that supposedly makes the channel open message insane
89 let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
90 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &message_mutator(open_channel_message.clone()));
91 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
92 assert_eq!(msg_events.len(), 1);
93 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
94 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
96 &ErrorAction::SendErrorMessage { .. } => {
97 nodes[1].logger.assert_log_regex("lightning::ln::channelmanager", expected_regex, 1);
99 _ => panic!("unexpected event!"),
101 } else { assert!(false); }
104 use crate::ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
106 // Test all mutations that would make the channel open message insane
107 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 });
108 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 });
110 insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
112 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 });
114 insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
116 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 });
118 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 });
120 insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
122 insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
126 fn test_funding_exceeds_no_wumbo_limit() {
127 // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
129 use crate::ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
130 let chanmon_cfgs = create_chanmon_cfgs(2);
131 let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
132 *node_cfgs[1].override_init_features.borrow_mut() = Some(channelmanager::provided_init_features(&test_default_channel_config()).clear_wumbo());
133 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
134 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
136 match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None) {
137 Err(APIError::APIMisuseError { err }) => {
138 assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
144 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
145 // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
146 // but only for them. Because some LSPs do it with some level of trust of the clients (for a
147 // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
148 // in normal testing, we test it explicitly here.
149 let chanmon_cfgs = create_chanmon_cfgs(2);
150 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
151 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
152 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
153 let default_config = UserConfig::default();
155 // Have node0 initiate a channel to node1 with aforementioned parameters
156 let mut push_amt = 100_000_000;
157 let feerate_per_kw = 253;
158 let opt_anchors = false;
159 push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(opt_anchors) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
160 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
162 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();
163 let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
164 if !send_from_initiator {
165 open_channel_message.channel_reserve_satoshis = 0;
166 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
168 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
170 // Extract the channel accept message from node1 to node0
171 let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
172 if send_from_initiator {
173 accept_channel_message.channel_reserve_satoshis = 0;
174 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
176 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
178 let sender_node = if send_from_initiator { &nodes[1] } else { &nodes[0] };
179 let counterparty_node = if send_from_initiator { &nodes[0] } else { &nodes[1] };
180 let mut sender_node_per_peer_lock;
181 let mut sender_node_peer_state_lock;
182 let mut chan = get_channel_ref!(sender_node, counterparty_node, sender_node_per_peer_lock, sender_node_peer_state_lock, temp_channel_id);
183 chan.holder_selected_channel_reserve_satoshis = 0;
184 chan.holder_max_htlc_value_in_flight_msat = 100_000_000;
187 let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
188 let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
189 create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
191 // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
192 // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
193 if send_from_initiator {
194 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
195 // Note that for outbound channels we have to consider the commitment tx fee and the
196 // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
197 // well as an additional HTLC.
198 - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, opt_anchors));
200 send_payment(&nodes[1], &[&nodes[0]], push_amt);
205 fn test_counterparty_no_reserve() {
206 do_test_counterparty_no_reserve(true);
207 do_test_counterparty_no_reserve(false);
211 fn test_async_inbound_update_fee() {
212 let chanmon_cfgs = create_chanmon_cfgs(2);
213 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
214 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
215 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
216 create_announced_chan_between_nodes(&nodes, 0, 1);
219 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
223 // send (1) commitment_signed -.
224 // <- update_add_htlc/commitment_signed
225 // send (2) RAA (awaiting remote revoke) -.
226 // (1) commitment_signed is delivered ->
227 // .- send (3) RAA (awaiting remote revoke)
228 // (2) RAA is delivered ->
229 // .- send (4) commitment_signed
230 // <- (3) RAA is delivered
231 // send (5) commitment_signed -.
232 // <- (4) commitment_signed is delivered
234 // (5) commitment_signed is delivered ->
236 // (6) RAA is delivered ->
238 // First nodes[0] generates an update_fee
240 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
243 nodes[0].node.timer_tick_occurred();
244 check_added_monitors!(nodes[0], 1);
246 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
247 assert_eq!(events_0.len(), 1);
248 let (update_msg, commitment_signed) = match events_0[0] { // (1)
249 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
250 (update_fee.as_ref(), commitment_signed)
252 _ => panic!("Unexpected event"),
255 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
257 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
258 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
259 nodes[1].node.send_payment_with_route(&route, our_payment_hash,
260 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
261 check_added_monitors!(nodes[1], 1);
263 let payment_event = {
264 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
265 assert_eq!(events_1.len(), 1);
266 SendEvent::from_event(events_1.remove(0))
268 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
269 assert_eq!(payment_event.msgs.len(), 1);
271 // ...now when the messages get delivered everyone should be happy
272 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
273 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
274 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
275 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
276 check_added_monitors!(nodes[0], 1);
278 // deliver(1), generate (3):
279 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
280 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
281 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
282 check_added_monitors!(nodes[1], 1);
284 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
285 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
286 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
287 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
288 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
289 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
290 assert!(bs_update.update_fee.is_none()); // (4)
291 check_added_monitors!(nodes[1], 1);
293 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
294 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
295 assert!(as_update.update_add_htlcs.is_empty()); // (5)
296 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
297 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
298 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
299 assert!(as_update.update_fee.is_none()); // (5)
300 check_added_monitors!(nodes[0], 1);
302 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
303 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
304 // only (6) so get_event_msg's assert(len == 1) passes
305 check_added_monitors!(nodes[0], 1);
307 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
308 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
309 check_added_monitors!(nodes[1], 1);
311 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
312 check_added_monitors!(nodes[0], 1);
314 let events_2 = nodes[0].node.get_and_clear_pending_events();
315 assert_eq!(events_2.len(), 1);
317 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
318 _ => panic!("Unexpected event"),
321 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
322 check_added_monitors!(nodes[1], 1);
326 fn test_update_fee_unordered_raa() {
327 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
328 // crash in an earlier version of the update_fee patch)
329 let chanmon_cfgs = create_chanmon_cfgs(2);
330 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
331 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
332 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
333 create_announced_chan_between_nodes(&nodes, 0, 1);
336 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
338 // First nodes[0] generates an update_fee
340 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
343 nodes[0].node.timer_tick_occurred();
344 check_added_monitors!(nodes[0], 1);
346 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
347 assert_eq!(events_0.len(), 1);
348 let update_msg = match events_0[0] { // (1)
349 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
352 _ => panic!("Unexpected event"),
355 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
357 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
358 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
359 nodes[1].node.send_payment_with_route(&route, our_payment_hash,
360 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
361 check_added_monitors!(nodes[1], 1);
363 let payment_event = {
364 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
365 assert_eq!(events_1.len(), 1);
366 SendEvent::from_event(events_1.remove(0))
368 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
369 assert_eq!(payment_event.msgs.len(), 1);
371 // ...now when the messages get delivered everyone should be happy
372 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
373 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
374 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
375 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
376 check_added_monitors!(nodes[0], 1);
378 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
379 check_added_monitors!(nodes[1], 1);
381 // We can't continue, sadly, because our (1) now has a bogus signature
385 fn test_multi_flight_update_fee() {
386 let chanmon_cfgs = create_chanmon_cfgs(2);
387 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
388 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
389 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
390 create_announced_chan_between_nodes(&nodes, 0, 1);
393 // update_fee/commitment_signed ->
394 // .- send (1) RAA and (2) commitment_signed
395 // update_fee (never committed) ->
397 // We have to manually generate the above update_fee, it is allowed by the protocol but we
398 // don't track which updates correspond to which revoke_and_ack responses so we're in
399 // AwaitingRAA mode and will not generate the update_fee yet.
400 // <- (1) RAA delivered
401 // (3) is generated and send (4) CS -.
402 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
403 // know the per_commitment_point to use for it.
404 // <- (2) commitment_signed delivered
406 // B should send no response here
407 // (4) commitment_signed delivered ->
408 // <- RAA/commitment_signed delivered
411 // First nodes[0] generates an update_fee
414 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
415 initial_feerate = *feerate_lock;
416 *feerate_lock = initial_feerate + 20;
418 nodes[0].node.timer_tick_occurred();
419 check_added_monitors!(nodes[0], 1);
421 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
422 assert_eq!(events_0.len(), 1);
423 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
424 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
425 (update_fee.as_ref().unwrap(), commitment_signed)
427 _ => panic!("Unexpected event"),
430 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
431 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
432 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
433 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
434 check_added_monitors!(nodes[1], 1);
436 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
439 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
440 *feerate_lock = initial_feerate + 40;
442 nodes[0].node.timer_tick_occurred();
443 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
444 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
446 // Create the (3) update_fee message that nodes[0] will generate before it does...
447 let mut update_msg_2 = msgs::UpdateFee {
448 channel_id: update_msg_1.channel_id.clone(),
449 feerate_per_kw: (initial_feerate + 30) as u32,
452 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
454 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
456 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
458 // Deliver (1), generating (3) and (4)
459 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
460 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
461 check_added_monitors!(nodes[0], 1);
462 assert!(as_second_update.update_add_htlcs.is_empty());
463 assert!(as_second_update.update_fulfill_htlcs.is_empty());
464 assert!(as_second_update.update_fail_htlcs.is_empty());
465 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
466 // Check that the update_fee newly generated matches what we delivered:
467 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
468 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
470 // Deliver (2) commitment_signed
471 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
472 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
473 check_added_monitors!(nodes[0], 1);
474 // No commitment_signed so get_event_msg's assert(len == 1) passes
476 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
477 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
478 check_added_monitors!(nodes[1], 1);
481 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
482 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
483 check_added_monitors!(nodes[1], 1);
485 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
486 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
487 check_added_monitors!(nodes[0], 1);
489 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
490 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
491 // No commitment_signed so get_event_msg's assert(len == 1) passes
492 check_added_monitors!(nodes[0], 1);
494 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
495 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
496 check_added_monitors!(nodes[1], 1);
499 fn do_test_sanity_on_in_flight_opens(steps: u8) {
500 // Previously, we had issues deserializing channels when we hadn't connected the first block
501 // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
502 // serialization round-trips and simply do steps towards opening a channel and then drop the
505 let chanmon_cfgs = create_chanmon_cfgs(2);
506 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
507 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
508 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
510 if steps & 0b1000_0000 != 0{
511 let block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
512 connect_block(&nodes[0], &block);
513 connect_block(&nodes[1], &block);
516 if steps & 0x0f == 0 { return; }
517 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
518 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
520 if steps & 0x0f == 1 { return; }
521 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
522 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
524 if steps & 0x0f == 2 { return; }
525 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
527 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
529 if steps & 0x0f == 3 { return; }
530 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
531 check_added_monitors!(nodes[0], 0);
532 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
534 if steps & 0x0f == 4 { return; }
535 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
537 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
538 assert_eq!(added_monitors.len(), 1);
539 assert_eq!(added_monitors[0].0, funding_output);
540 added_monitors.clear();
542 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
544 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
546 if steps & 0x0f == 5 { return; }
547 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
549 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
550 assert_eq!(added_monitors.len(), 1);
551 assert_eq!(added_monitors[0].0, funding_output);
552 added_monitors.clear();
555 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
556 let events_4 = nodes[0].node.get_and_clear_pending_events();
557 assert_eq!(events_4.len(), 0);
559 if steps & 0x0f == 6 { return; }
560 create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
562 if steps & 0x0f == 7 { return; }
563 confirm_transaction_at(&nodes[0], &tx, 2);
564 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
565 create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
566 expect_channel_ready_event(&nodes[0], &nodes[1].node.get_our_node_id());
570 fn test_sanity_on_in_flight_opens() {
571 do_test_sanity_on_in_flight_opens(0);
572 do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
573 do_test_sanity_on_in_flight_opens(1);
574 do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
575 do_test_sanity_on_in_flight_opens(2);
576 do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
577 do_test_sanity_on_in_flight_opens(3);
578 do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
579 do_test_sanity_on_in_flight_opens(4);
580 do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
581 do_test_sanity_on_in_flight_opens(5);
582 do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
583 do_test_sanity_on_in_flight_opens(6);
584 do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
585 do_test_sanity_on_in_flight_opens(7);
586 do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
587 do_test_sanity_on_in_flight_opens(8);
588 do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
592 fn test_update_fee_vanilla() {
593 let chanmon_cfgs = create_chanmon_cfgs(2);
594 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
595 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
596 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
597 create_announced_chan_between_nodes(&nodes, 0, 1);
600 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
603 nodes[0].node.timer_tick_occurred();
604 check_added_monitors!(nodes[0], 1);
606 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
607 assert_eq!(events_0.len(), 1);
608 let (update_msg, commitment_signed) = match events_0[0] {
609 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 } } => {
610 (update_fee.as_ref(), commitment_signed)
612 _ => panic!("Unexpected event"),
614 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
616 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
617 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
618 check_added_monitors!(nodes[1], 1);
620 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
621 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
622 check_added_monitors!(nodes[0], 1);
624 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
625 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
626 // No commitment_signed so get_event_msg's assert(len == 1) passes
627 check_added_monitors!(nodes[0], 1);
629 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
630 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
631 check_added_monitors!(nodes[1], 1);
635 fn test_update_fee_that_funder_cannot_afford() {
636 let chanmon_cfgs = create_chanmon_cfgs(2);
637 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
638 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
639 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
640 let channel_value = 5000;
642 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000);
643 let channel_id = chan.2;
644 let secp_ctx = Secp256k1::new();
645 let default_config = UserConfig::default();
646 let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value, &default_config);
648 let opt_anchors = false;
650 // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
651 // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
652 // calculate two different feerates here - the expected local limit as well as the expected
654 let feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / (commitment_tx_base_weight(opt_anchors) + CONCURRENT_INBOUND_HTLC_FEE_BUFFER as u64 * COMMITMENT_TX_WEIGHT_PER_HTLC)) as u32;
655 let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
657 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
658 *feerate_lock = feerate;
660 nodes[0].node.timer_tick_occurred();
661 check_added_monitors!(nodes[0], 1);
662 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
664 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
666 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
668 // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
670 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
672 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
673 assert_eq!(commitment_tx.output.len(), 2);
674 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
675 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
676 actual_fee = channel_value - actual_fee;
677 assert_eq!(total_fee, actual_fee);
681 // Increment the feerate by a small constant, accounting for rounding errors
682 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
685 nodes[0].node.timer_tick_occurred();
686 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
687 check_added_monitors!(nodes[0], 0);
689 const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
691 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
692 // needed to sign the new commitment tx and (2) sign the new commitment tx.
693 let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
694 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
695 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
696 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
697 let chan_signer = local_chan.get_signer();
698 let pubkeys = chan_signer.pubkeys();
699 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
700 pubkeys.funding_pubkey)
702 let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
703 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
704 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
705 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
706 let chan_signer = remote_chan.get_signer();
707 let pubkeys = chan_signer.pubkeys();
708 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
709 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
710 pubkeys.funding_pubkey)
713 // Assemble the set of keys we can use for signatures for our commitment_signed message.
714 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
715 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
718 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
719 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
720 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
721 let local_chan_signer = local_chan.get_signer();
722 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
723 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
724 INITIAL_COMMITMENT_NUMBER - 1,
726 channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
727 opt_anchors, local_funding, remote_funding,
728 commit_tx_keys.clone(),
729 non_buffer_feerate + 4,
731 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
733 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
736 let commit_signed_msg = msgs::CommitmentSigned {
739 htlc_signatures: res.1,
741 partial_signature_with_nonce: None,
744 let update_fee = msgs::UpdateFee {
746 feerate_per_kw: non_buffer_feerate + 4,
749 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
751 //While producing the commitment_signed response after handling a received update_fee request the
752 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
753 //Should produce and error.
754 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
755 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
756 check_added_monitors!(nodes[1], 1);
757 check_closed_broadcast!(nodes[1], true);
758 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
762 fn test_update_fee_with_fundee_update_add_htlc() {
763 let chanmon_cfgs = create_chanmon_cfgs(2);
764 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
765 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
766 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
767 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
770 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
773 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
776 nodes[0].node.timer_tick_occurred();
777 check_added_monitors!(nodes[0], 1);
779 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
780 assert_eq!(events_0.len(), 1);
781 let (update_msg, commitment_signed) = match events_0[0] {
782 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 } } => {
783 (update_fee.as_ref(), commitment_signed)
785 _ => panic!("Unexpected event"),
787 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
788 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
789 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
790 check_added_monitors!(nodes[1], 1);
792 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
794 // nothing happens since node[1] is in AwaitingRemoteRevoke
795 nodes[1].node.send_payment_with_route(&route, our_payment_hash,
796 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
798 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
799 assert_eq!(added_monitors.len(), 0);
800 added_monitors.clear();
802 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
803 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
804 // node[1] has nothing to do
806 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
807 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
808 check_added_monitors!(nodes[0], 1);
810 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
811 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
812 // No commitment_signed so get_event_msg's assert(len == 1) passes
813 check_added_monitors!(nodes[0], 1);
814 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
815 check_added_monitors!(nodes[1], 1);
816 // AwaitingRemoteRevoke ends here
818 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
819 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
820 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
821 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
822 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
823 assert_eq!(commitment_update.update_fee.is_none(), true);
825 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
826 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
827 check_added_monitors!(nodes[0], 1);
828 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
830 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
831 check_added_monitors!(nodes[1], 1);
832 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
834 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
835 check_added_monitors!(nodes[1], 1);
836 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
837 // No commitment_signed so get_event_msg's assert(len == 1) passes
839 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
840 check_added_monitors!(nodes[0], 1);
841 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
843 expect_pending_htlcs_forwardable!(nodes[0]);
845 let events = nodes[0].node.get_and_clear_pending_events();
846 assert_eq!(events.len(), 1);
848 Event::PaymentClaimable { .. } => { },
849 _ => panic!("Unexpected event"),
852 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
854 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
855 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
856 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
857 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
858 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
862 fn test_update_fee() {
863 let chanmon_cfgs = create_chanmon_cfgs(2);
864 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
865 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
866 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
867 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
868 let channel_id = chan.2;
871 // (1) update_fee/commitment_signed ->
872 // <- (2) revoke_and_ack
873 // .- send (3) commitment_signed
874 // (4) update_fee/commitment_signed ->
875 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
876 // <- (3) commitment_signed delivered
877 // send (6) revoke_and_ack -.
878 // <- (5) deliver revoke_and_ack
879 // (6) deliver revoke_and_ack ->
880 // .- send (7) commitment_signed in response to (4)
881 // <- (7) deliver commitment_signed
884 // Create and deliver (1)...
887 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
888 feerate = *feerate_lock;
889 *feerate_lock = feerate + 20;
891 nodes[0].node.timer_tick_occurred();
892 check_added_monitors!(nodes[0], 1);
894 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
895 assert_eq!(events_0.len(), 1);
896 let (update_msg, commitment_signed) = match events_0[0] {
897 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 } } => {
898 (update_fee.as_ref(), commitment_signed)
900 _ => panic!("Unexpected event"),
902 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
904 // Generate (2) and (3):
905 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
906 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
907 check_added_monitors!(nodes[1], 1);
910 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
911 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
912 check_added_monitors!(nodes[0], 1);
914 // Create and deliver (4)...
916 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
917 *feerate_lock = feerate + 30;
919 nodes[0].node.timer_tick_occurred();
920 check_added_monitors!(nodes[0], 1);
921 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
922 assert_eq!(events_0.len(), 1);
923 let (update_msg, commitment_signed) = match events_0[0] {
924 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 } } => {
925 (update_fee.as_ref(), commitment_signed)
927 _ => panic!("Unexpected event"),
930 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
931 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
932 check_added_monitors!(nodes[1], 1);
934 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
935 // No commitment_signed so get_event_msg's assert(len == 1) passes
937 // Handle (3), creating (6):
938 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
939 check_added_monitors!(nodes[0], 1);
940 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
941 // No commitment_signed so get_event_msg's assert(len == 1) passes
944 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
945 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
946 check_added_monitors!(nodes[0], 1);
948 // Deliver (6), creating (7):
949 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
950 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
951 assert!(commitment_update.update_add_htlcs.is_empty());
952 assert!(commitment_update.update_fulfill_htlcs.is_empty());
953 assert!(commitment_update.update_fail_htlcs.is_empty());
954 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
955 assert!(commitment_update.update_fee.is_none());
956 check_added_monitors!(nodes[1], 1);
959 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
960 check_added_monitors!(nodes[0], 1);
961 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
962 // No commitment_signed so get_event_msg's assert(len == 1) passes
964 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
965 check_added_monitors!(nodes[1], 1);
966 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
968 assert_eq!(get_feerate!(nodes[0], nodes[1], channel_id), feerate + 30);
969 assert_eq!(get_feerate!(nodes[1], nodes[0], channel_id), feerate + 30);
970 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
971 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
972 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
976 fn fake_network_test() {
977 // Simple test which builds a network of ChannelManagers, connects them to each other, and
978 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
979 let chanmon_cfgs = create_chanmon_cfgs(4);
980 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
981 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
982 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
984 // Create some initial channels
985 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
986 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
987 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
989 // Rebalance the network a bit by relaying one payment through all the channels...
990 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
991 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
992 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
993 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
995 // Send some more payments
996 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
997 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
998 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
1000 // Test failure packets
1001 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1002 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1004 // Add a new channel that skips 3
1005 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
1007 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
1008 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
1009 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1010 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1011 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1012 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1013 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1015 // Do some rebalance loop payments, simultaneously
1016 let mut hops = Vec::with_capacity(3);
1017 hops.push(RouteHop {
1018 pubkey: nodes[2].node.get_our_node_id(),
1019 node_features: NodeFeatures::empty(),
1020 short_channel_id: chan_2.0.contents.short_channel_id,
1021 channel_features: ChannelFeatures::empty(),
1023 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1025 hops.push(RouteHop {
1026 pubkey: nodes[3].node.get_our_node_id(),
1027 node_features: NodeFeatures::empty(),
1028 short_channel_id: chan_3.0.contents.short_channel_id,
1029 channel_features: ChannelFeatures::empty(),
1031 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1033 hops.push(RouteHop {
1034 pubkey: nodes[1].node.get_our_node_id(),
1035 node_features: nodes[1].node.node_features(),
1036 short_channel_id: chan_4.0.contents.short_channel_id,
1037 channel_features: nodes[1].node.channel_features(),
1039 cltv_expiry_delta: TEST_FINAL_CLTV,
1041 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;
1042 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;
1043 let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![Path { hops, blinded_tail: None }], payment_params: None }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1045 let mut hops = Vec::with_capacity(3);
1046 hops.push(RouteHop {
1047 pubkey: nodes[3].node.get_our_node_id(),
1048 node_features: NodeFeatures::empty(),
1049 short_channel_id: chan_4.0.contents.short_channel_id,
1050 channel_features: ChannelFeatures::empty(),
1052 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1054 hops.push(RouteHop {
1055 pubkey: nodes[2].node.get_our_node_id(),
1056 node_features: NodeFeatures::empty(),
1057 short_channel_id: chan_3.0.contents.short_channel_id,
1058 channel_features: ChannelFeatures::empty(),
1060 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1062 hops.push(RouteHop {
1063 pubkey: nodes[1].node.get_our_node_id(),
1064 node_features: nodes[1].node.node_features(),
1065 short_channel_id: chan_2.0.contents.short_channel_id,
1066 channel_features: nodes[1].node.channel_features(),
1068 cltv_expiry_delta: TEST_FINAL_CLTV,
1070 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;
1071 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;
1072 let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![Path { hops, blinded_tail: None }], payment_params: None }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1074 // Claim the rebalances...
1075 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1076 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1078 // Close down the channels...
1079 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1080 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1081 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1082 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1083 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1084 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1085 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1086 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1087 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1088 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1089 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1090 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1094 fn holding_cell_htlc_counting() {
1095 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1096 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1097 // commitment dance rounds.
1098 let chanmon_cfgs = create_chanmon_cfgs(3);
1099 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1100 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1101 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1102 create_announced_chan_between_nodes(&nodes, 0, 1);
1103 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1105 let mut payments = Vec::new();
1107 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1108 nodes[1].node.send_payment_with_route(&route, payment_hash,
1109 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1110 payments.push((payment_preimage, payment_hash));
1112 check_added_monitors!(nodes[1], 1);
1114 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1115 assert_eq!(events.len(), 1);
1116 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1117 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1119 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1120 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1122 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1124 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, payment_hash_1,
1125 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)
1126 ), true, APIError::ChannelUnavailable { ref err },
1127 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1128 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1129 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot push more than their max accepted HTLCs", 1);
1132 // This should also be true if we try to forward a payment.
1133 let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1135 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1136 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1137 check_added_monitors!(nodes[0], 1);
1140 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1141 assert_eq!(events.len(), 1);
1142 let payment_event = SendEvent::from_event(events.pop().unwrap());
1143 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1145 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1146 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1147 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1148 // fails), the second will process the resulting failure and fail the HTLC backward.
1149 expect_pending_htlcs_forwardable!(nodes[1]);
1150 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 }]);
1151 check_added_monitors!(nodes[1], 1);
1153 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1154 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1155 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1157 expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1159 // Now forward all the pending HTLCs and claim them back
1160 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1161 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1162 check_added_monitors!(nodes[2], 1);
1164 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1165 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1166 check_added_monitors!(nodes[1], 1);
1167 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1169 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1170 check_added_monitors!(nodes[1], 1);
1171 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1173 for ref update in as_updates.update_add_htlcs.iter() {
1174 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1176 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1177 check_added_monitors!(nodes[2], 1);
1178 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1179 check_added_monitors!(nodes[2], 1);
1180 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1182 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1183 check_added_monitors!(nodes[1], 1);
1184 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1185 check_added_monitors!(nodes[1], 1);
1186 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1188 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1189 check_added_monitors!(nodes[2], 1);
1191 expect_pending_htlcs_forwardable!(nodes[2]);
1193 let events = nodes[2].node.get_and_clear_pending_events();
1194 assert_eq!(events.len(), payments.len());
1195 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1197 &Event::PaymentClaimable { ref payment_hash, .. } => {
1198 assert_eq!(*payment_hash, *hash);
1200 _ => panic!("Unexpected event"),
1204 for (preimage, _) in payments.drain(..) {
1205 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1208 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1212 fn duplicate_htlc_test() {
1213 // Test that we accept duplicate payment_hash HTLCs across the network and that
1214 // claiming/failing them are all separate and don't affect each other
1215 let chanmon_cfgs = create_chanmon_cfgs(6);
1216 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1217 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1218 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1220 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1221 create_announced_chan_between_nodes(&nodes, 0, 3);
1222 create_announced_chan_between_nodes(&nodes, 1, 3);
1223 create_announced_chan_between_nodes(&nodes, 2, 3);
1224 create_announced_chan_between_nodes(&nodes, 3, 4);
1225 create_announced_chan_between_nodes(&nodes, 3, 5);
1227 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1229 *nodes[0].network_payment_count.borrow_mut() -= 1;
1230 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1232 *nodes[0].network_payment_count.borrow_mut() -= 1;
1233 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1235 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1236 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1237 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1241 fn test_duplicate_htlc_different_direction_onchain() {
1242 // Test that ChannelMonitor doesn't generate 2 preimage txn
1243 // when we have 2 HTLCs with same preimage that go across a node
1244 // in opposite directions, even with the same payment secret.
1245 let chanmon_cfgs = create_chanmon_cfgs(2);
1246 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1247 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1248 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1250 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1253 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1255 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1257 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1258 let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
1259 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1261 // Provide preimage to node 0 by claiming payment
1262 nodes[0].node.claim_funds(payment_preimage);
1263 expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1264 check_added_monitors!(nodes[0], 1);
1266 // Broadcast node 1 commitment txn
1267 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1269 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1270 let mut has_both_htlcs = 0; // check htlcs match ones committed
1271 for outp in remote_txn[0].output.iter() {
1272 if outp.value == 800_000 / 1000 {
1273 has_both_htlcs += 1;
1274 } else if outp.value == 900_000 / 1000 {
1275 has_both_htlcs += 1;
1278 assert_eq!(has_both_htlcs, 2);
1280 mine_transaction(&nodes[0], &remote_txn[0]);
1281 check_added_monitors!(nodes[0], 1);
1282 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1283 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
1285 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1286 assert_eq!(claim_txn.len(), 3);
1288 check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1289 check_spends!(claim_txn[1], remote_txn[0]);
1290 check_spends!(claim_txn[2], remote_txn[0]);
1291 let preimage_tx = &claim_txn[0];
1292 let (preimage_bump_tx, timeout_tx) = if claim_txn[1].input[0].previous_output == preimage_tx.input[0].previous_output {
1293 (&claim_txn[1], &claim_txn[2])
1295 (&claim_txn[2], &claim_txn[1])
1298 assert_eq!(preimage_tx.input.len(), 1);
1299 assert_eq!(preimage_bump_tx.input.len(), 1);
1301 assert_eq!(preimage_tx.input.len(), 1);
1302 assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1303 assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1305 assert_eq!(timeout_tx.input.len(), 1);
1306 assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1307 check_spends!(timeout_tx, remote_txn[0]);
1308 assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1310 let events = nodes[0].node.get_and_clear_pending_msg_events();
1311 assert_eq!(events.len(), 3);
1314 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1315 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1316 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1317 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1319 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, .. } } => {
1320 assert!(update_add_htlcs.is_empty());
1321 assert!(update_fail_htlcs.is_empty());
1322 assert_eq!(update_fulfill_htlcs.len(), 1);
1323 assert!(update_fail_malformed_htlcs.is_empty());
1324 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1326 _ => panic!("Unexpected event"),
1332 fn test_basic_channel_reserve() {
1333 let chanmon_cfgs = create_chanmon_cfgs(2);
1334 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1335 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1336 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1337 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1339 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1340 let channel_reserve = chan_stat.channel_reserve_msat;
1342 // The 2* and +1 are for the fee spike reserve.
1343 let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], nodes[1], chan.2), 1 + 1, get_opt_anchors!(nodes[0], nodes[1], chan.2));
1344 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1345 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1346 let err = nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1347 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1349 PaymentSendFailure::AllFailedResendSafe(ref fails) => {
1351 &APIError::ChannelUnavailable{ref err} =>
1352 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1353 _ => panic!("Unexpected error variant"),
1356 _ => panic!("Unexpected error variant"),
1358 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1359 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put our balance under counterparty-announced channel reserve value", 1);
1361 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1365 fn test_fee_spike_violation_fails_htlc() {
1366 let chanmon_cfgs = create_chanmon_cfgs(2);
1367 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1368 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1369 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1370 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1372 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1373 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1374 let secp_ctx = Secp256k1::new();
1375 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1377 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1379 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1380 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1381 3460001, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1382 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1383 let msg = msgs::UpdateAddHTLC {
1386 amount_msat: htlc_msat,
1387 payment_hash: payment_hash,
1388 cltv_expiry: htlc_cltv,
1389 onion_routing_packet: onion_packet,
1392 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1394 // Now manually create the commitment_signed message corresponding to the update_add
1395 // nodes[0] just sent. In the code for construction of this message, "local" refers
1396 // to the sender of the message, and "remote" refers to the receiver.
1398 let feerate_per_kw = get_feerate!(nodes[0], nodes[1], chan.2);
1400 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1402 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1403 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1404 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1405 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1406 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1407 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1408 let chan_signer = local_chan.get_signer();
1409 // Make the signer believe we validated another commitment, so we can release the secret
1410 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1412 let pubkeys = chan_signer.pubkeys();
1413 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1414 chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1415 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1416 chan_signer.pubkeys().funding_pubkey)
1418 let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1419 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
1420 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
1421 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1422 let chan_signer = remote_chan.get_signer();
1423 let pubkeys = chan_signer.pubkeys();
1424 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1425 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1426 chan_signer.pubkeys().funding_pubkey)
1429 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1430 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1431 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
1433 // Build the remote commitment transaction so we can sign it, and then later use the
1434 // signature for the commitment_signed message.
1435 let local_chan_balance = 1313;
1437 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1439 amount_msat: 3460001,
1440 cltv_expiry: htlc_cltv,
1442 transaction_output_index: Some(1),
1445 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1448 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1449 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1450 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
1451 let local_chan_signer = local_chan.get_signer();
1452 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1456 local_chan.opt_anchors(), local_funding, remote_funding,
1457 commit_tx_keys.clone(),
1459 &mut vec![(accepted_htlc_info, ())],
1460 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1462 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1465 let commit_signed_msg = msgs::CommitmentSigned {
1468 htlc_signatures: res.1,
1470 partial_signature_with_nonce: None,
1473 // Send the commitment_signed message to the nodes[1].
1474 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1475 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1477 // Send the RAA to nodes[1].
1478 let raa_msg = msgs::RevokeAndACK {
1480 per_commitment_secret: local_secret,
1481 next_per_commitment_point: next_local_point,
1483 next_local_nonce: None,
1485 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1487 let events = nodes[1].node.get_and_clear_pending_msg_events();
1488 assert_eq!(events.len(), 1);
1489 // Make sure the HTLC failed in the way we expect.
1491 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1492 assert_eq!(update_fail_htlcs.len(), 1);
1493 update_fail_htlcs[0].clone()
1495 _ => panic!("Unexpected event"),
1497 nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1498 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1500 check_added_monitors!(nodes[1], 2);
1504 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1505 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1506 // Set the fee rate for the channel very high, to the point where the fundee
1507 // sending any above-dust amount would result in a channel reserve violation.
1508 // In this test we check that we would be prevented from sending an HTLC in
1510 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1511 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1512 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1513 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1514 let default_config = UserConfig::default();
1515 let opt_anchors = false;
1517 let mut push_amt = 100_000_000;
1518 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1520 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1522 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1524 // Sending exactly enough to hit the reserve amount should be accepted
1525 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1526 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1529 // However one more HTLC should be significantly over the reserve amount and fail.
1530 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1531 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1532 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1533 ), true, APIError::ChannelUnavailable { ref err },
1534 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1535 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1536 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put counterparty balance under holder-announced channel reserve value".to_string(), 1);
1540 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1541 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1542 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1543 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1544 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1545 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1546 let default_config = UserConfig::default();
1547 let opt_anchors = false;
1549 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1550 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1551 // transaction fee with 0 HTLCs (183 sats)).
1552 let mut push_amt = 100_000_000;
1553 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1554 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1555 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1557 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1558 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1559 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1562 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1563 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1564 let secp_ctx = Secp256k1::new();
1565 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1566 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1567 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1568 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1569 700_000, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1570 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1571 let msg = msgs::UpdateAddHTLC {
1573 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1574 amount_msat: htlc_msat,
1575 payment_hash: payment_hash,
1576 cltv_expiry: htlc_cltv,
1577 onion_routing_packet: onion_packet,
1580 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1581 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1582 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);
1583 assert_eq!(nodes[0].node.list_channels().len(), 0);
1584 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1585 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1586 check_added_monitors!(nodes[0], 1);
1587 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() });
1591 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1592 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1593 // calculating our commitment transaction fee (this was previously broken).
1594 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1595 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1597 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1598 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1599 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1600 let default_config = UserConfig::default();
1601 let opt_anchors = false;
1603 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1604 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1605 // transaction fee with 0 HTLCs (183 sats)).
1606 let mut push_amt = 100_000_000;
1607 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1608 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1609 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt);
1611 let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1612 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1613 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1614 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1615 // commitment transaction fee.
1616 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1618 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1619 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1620 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1623 // One more than the dust amt should fail, however.
1624 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1625 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1626 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1627 ), true, APIError::ChannelUnavailable { ref err },
1628 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1632 fn test_chan_init_feerate_unaffordability() {
1633 // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1634 // channel reserve and feerate requirements.
1635 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1636 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1637 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1638 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1639 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1640 let default_config = UserConfig::default();
1641 let opt_anchors = false;
1643 // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1645 let mut push_amt = 100_000_000;
1646 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1647 assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1648 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1650 // During open, we don't have a "counterparty channel reserve" to check against, so that
1651 // requirement only comes into play on the open_channel handling side.
1652 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1653 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1654 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1655 open_channel_msg.push_msat += 1;
1656 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
1658 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1659 assert_eq!(msg_events.len(), 1);
1660 match msg_events[0] {
1661 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1662 assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1664 _ => panic!("Unexpected event"),
1669 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1670 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1671 // calculating our counterparty's commitment transaction fee (this was previously broken).
1672 let chanmon_cfgs = create_chanmon_cfgs(2);
1673 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1674 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1675 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1676 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000);
1678 let payment_amt = 46000; // Dust amount
1679 // In the previous code, these first four payments would succeed.
1680 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1681 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1682 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1683 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1685 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1686 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1687 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1688 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1689 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1690 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1692 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1693 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1694 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1695 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1699 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1700 let chanmon_cfgs = create_chanmon_cfgs(3);
1701 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1702 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1703 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1704 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1705 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
1708 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1709 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1710 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
1711 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
1713 // Add a 2* and +1 for the fee spike reserve.
1714 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1715 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;
1716 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1718 // Add a pending HTLC.
1719 let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1720 let payment_event_1 = {
1721 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1722 RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1723 check_added_monitors!(nodes[0], 1);
1725 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1726 assert_eq!(events.len(), 1);
1727 SendEvent::from_event(events.remove(0))
1729 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1731 // Attempt to trigger a channel reserve violation --> payment failure.
1732 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1733 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;
1734 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1735 let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1737 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1738 let secp_ctx = Secp256k1::new();
1739 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1740 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1741 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1742 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
1743 &route_2.paths[0], recv_value_2, RecipientOnionFields::spontaneous_empty(), cur_height, &None).unwrap();
1744 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1).unwrap();
1745 let msg = msgs::UpdateAddHTLC {
1748 amount_msat: htlc_msat + 1,
1749 payment_hash: our_payment_hash_1,
1750 cltv_expiry: htlc_cltv,
1751 onion_routing_packet: onion_packet,
1754 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1755 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1756 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1757 assert_eq!(nodes[1].node.list_channels().len(), 1);
1758 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1759 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1760 check_added_monitors!(nodes[1], 1);
1761 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1765 fn test_inbound_outbound_capacity_is_not_zero() {
1766 let chanmon_cfgs = create_chanmon_cfgs(2);
1767 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1768 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1769 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1770 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1771 let channels0 = node_chanmgrs[0].list_channels();
1772 let channels1 = node_chanmgrs[1].list_channels();
1773 let default_config = UserConfig::default();
1774 assert_eq!(channels0.len(), 1);
1775 assert_eq!(channels1.len(), 1);
1777 let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1778 assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1779 assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1781 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1782 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1785 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1786 (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1790 fn test_channel_reserve_holding_cell_htlcs() {
1791 let chanmon_cfgs = create_chanmon_cfgs(3);
1792 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1793 // When this test was written, the default base fee floated based on the HTLC count.
1794 // It is now fixed, so we simply set the fee to the expected value here.
1795 let mut config = test_default_channel_config();
1796 config.channel_config.forwarding_fee_base_msat = 239;
1797 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1798 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1799 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001);
1800 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001);
1802 let mut stat01 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1803 let mut stat11 = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
1805 let mut stat12 = get_channel_value_stat!(nodes[1], nodes[2], chan_2.2);
1806 let mut stat22 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
1808 macro_rules! expect_forward {
1810 let mut events = $node.node.get_and_clear_pending_msg_events();
1811 assert_eq!(events.len(), 1);
1812 check_added_monitors!($node, 1);
1813 let payment_event = SendEvent::from_event(events.remove(0));
1818 let feemsat = 239; // set above
1819 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1820 let feerate = get_feerate!(nodes[0], nodes[1], chan_1.2);
1821 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_1.2);
1823 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1825 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1827 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1828 .with_bolt11_features(nodes[2].node.invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1829 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, recv_value_0);
1830 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1831 assert!(route.paths[0].hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1833 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1834 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1835 ), true, APIError::ChannelUnavailable { ref err },
1836 assert!(regex::Regex::new(r"Cannot send value that would put us over the max HTLC value in flight our peer will accept \(\d+\)").unwrap().is_match(err)));
1837 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1838 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put us over the max HTLC value in flight our peer will accept", 1);
1841 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1842 // nodes[0]'s wealth
1844 let amt_msat = recv_value_0 + total_fee_msat;
1845 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1846 // Also, ensure that each payment has enough to be over the dust limit to
1847 // ensure it'll be included in each commit tx fee calculation.
1848 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1849 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1850 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1854 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1855 .with_bolt11_features(nodes[2].node.invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1856 let route = get_route!(nodes[0], payment_params, recv_value_0).unwrap();
1857 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1858 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1860 let (stat01_, stat11_, stat12_, stat22_) = (
1861 get_channel_value_stat!(nodes[0], nodes[1], chan_1.2),
1862 get_channel_value_stat!(nodes[1], nodes[0], chan_1.2),
1863 get_channel_value_stat!(nodes[1], nodes[2], chan_2.2),
1864 get_channel_value_stat!(nodes[2], nodes[1], chan_2.2),
1867 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1868 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1869 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1870 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1871 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1874 // adding pending output.
1875 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1876 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1877 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1878 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1879 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1880 // cases where 1 msat over X amount will cause a payment failure, but anything less than
1881 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1882 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1883 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1885 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1886 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1887 let amt_msat_1 = recv_value_1 + total_fee_msat;
1889 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);
1890 let payment_event_1 = {
1891 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1892 RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1893 check_added_monitors!(nodes[0], 1);
1895 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1896 assert_eq!(events.len(), 1);
1897 SendEvent::from_event(events.remove(0))
1899 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1901 // channel reserve test with htlc pending output > 0
1902 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1904 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1905 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1906 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1907 ), true, APIError::ChannelUnavailable { ref err },
1908 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1909 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1912 // split the rest to test holding cell
1913 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1914 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1915 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1916 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1918 let stat = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1919 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);
1922 // now see if they go through on both sides
1923 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);
1924 // but this will stuck in the holding cell
1925 nodes[0].node.send_payment_with_route(&route_21, our_payment_hash_21,
1926 RecipientOnionFields::secret_only(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
1927 check_added_monitors!(nodes[0], 0);
1928 let events = nodes[0].node.get_and_clear_pending_events();
1929 assert_eq!(events.len(), 0);
1931 // test with outbound holding cell amount > 0
1933 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1934 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1935 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1936 ), true, APIError::ChannelUnavailable { ref err },
1937 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1938 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1939 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put our balance under counterparty-announced channel reserve value", 2);
1942 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);
1943 // this will also stuck in the holding cell
1944 nodes[0].node.send_payment_with_route(&route_22, our_payment_hash_22,
1945 RecipientOnionFields::secret_only(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
1946 check_added_monitors!(nodes[0], 0);
1947 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1948 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1950 // flush the pending htlc
1951 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1952 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1953 check_added_monitors!(nodes[1], 1);
1955 // the pending htlc should be promoted to committed
1956 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1957 check_added_monitors!(nodes[0], 1);
1958 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1960 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1961 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1962 // No commitment_signed so get_event_msg's assert(len == 1) passes
1963 check_added_monitors!(nodes[0], 1);
1965 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1966 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1967 check_added_monitors!(nodes[1], 1);
1969 expect_pending_htlcs_forwardable!(nodes[1]);
1971 let ref payment_event_11 = expect_forward!(nodes[1]);
1972 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1973 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1975 expect_pending_htlcs_forwardable!(nodes[2]);
1976 expect_payment_claimable!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1978 // flush the htlcs in the holding cell
1979 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1980 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1981 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1982 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1983 expect_pending_htlcs_forwardable!(nodes[1]);
1985 let ref payment_event_3 = expect_forward!(nodes[1]);
1986 assert_eq!(payment_event_3.msgs.len(), 2);
1987 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1988 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1990 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1991 expect_pending_htlcs_forwardable!(nodes[2]);
1993 let events = nodes[2].node.get_and_clear_pending_events();
1994 assert_eq!(events.len(), 2);
1996 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
1997 assert_eq!(our_payment_hash_21, *payment_hash);
1998 assert_eq!(recv_value_21, amount_msat);
1999 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2000 assert_eq!(via_channel_id, Some(chan_2.2));
2002 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2003 assert!(payment_preimage.is_none());
2004 assert_eq!(our_payment_secret_21, *payment_secret);
2006 _ => panic!("expected PaymentPurpose::InvoicePayment")
2009 _ => panic!("Unexpected event"),
2012 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2013 assert_eq!(our_payment_hash_22, *payment_hash);
2014 assert_eq!(recv_value_22, amount_msat);
2015 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2016 assert_eq!(via_channel_id, Some(chan_2.2));
2018 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2019 assert!(payment_preimage.is_none());
2020 assert_eq!(our_payment_secret_22, *payment_secret);
2022 _ => panic!("expected PaymentPurpose::InvoicePayment")
2025 _ => panic!("Unexpected event"),
2028 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2029 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2030 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2032 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
2033 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2034 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2036 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
2037 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);
2038 let stat0 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
2039 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2040 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2042 let stat2 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
2043 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2047 fn channel_reserve_in_flight_removes() {
2048 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2049 // can send to its counterparty, but due to update ordering, the other side may not yet have
2050 // considered those HTLCs fully removed.
2051 // This tests that we don't count HTLCs which will not be included in the next remote
2052 // commitment transaction towards the reserve value (as it implies no commitment transaction
2053 // will be generated which violates the remote reserve value).
2054 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2056 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2057 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2058 // you only consider the value of the first HTLC, it may not),
2059 // * start routing a third HTLC from A to B,
2060 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2061 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2062 // * deliver the first fulfill from B
2063 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2065 // * deliver A's response CS and RAA.
2066 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2067 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
2068 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2069 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2070 let chanmon_cfgs = create_chanmon_cfgs(2);
2071 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2072 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2073 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2074 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2076 let b_chan_values = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
2077 // Route the first two HTLCs.
2078 let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2079 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2080 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2082 // Start routing the third HTLC (this is just used to get everyone in the right state).
2083 let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2085 nodes[0].node.send_payment_with_route(&route, payment_hash_3,
2086 RecipientOnionFields::secret_only(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2087 check_added_monitors!(nodes[0], 1);
2088 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2089 assert_eq!(events.len(), 1);
2090 SendEvent::from_event(events.remove(0))
2093 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2094 // initial fulfill/CS.
2095 nodes[1].node.claim_funds(payment_preimage_1);
2096 expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2097 check_added_monitors!(nodes[1], 1);
2098 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2100 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2101 // remove the second HTLC when we send the HTLC back from B to A.
2102 nodes[1].node.claim_funds(payment_preimage_2);
2103 expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2104 check_added_monitors!(nodes[1], 1);
2105 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2107 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2108 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2109 check_added_monitors!(nodes[0], 1);
2110 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2111 expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2113 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2114 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2115 check_added_monitors!(nodes[1], 1);
2116 // B is already AwaitingRAA, so cant generate a CS here
2117 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2119 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2120 check_added_monitors!(nodes[1], 1);
2121 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2123 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2124 check_added_monitors!(nodes[0], 1);
2125 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2127 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2128 check_added_monitors!(nodes[1], 1);
2129 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2131 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2132 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2133 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2134 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2135 // on-chain as necessary).
2136 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2137 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2138 check_added_monitors!(nodes[0], 1);
2139 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2140 expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2142 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2143 check_added_monitors!(nodes[1], 1);
2144 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2146 expect_pending_htlcs_forwardable!(nodes[1]);
2147 expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2149 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2150 // resolve the second HTLC from A's point of view.
2151 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2152 check_added_monitors!(nodes[0], 1);
2153 expect_payment_path_successful!(nodes[0]);
2154 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2156 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2157 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2158 let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2160 nodes[1].node.send_payment_with_route(&route, payment_hash_4,
2161 RecipientOnionFields::secret_only(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2162 check_added_monitors!(nodes[1], 1);
2163 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2164 assert_eq!(events.len(), 1);
2165 SendEvent::from_event(events.remove(0))
2168 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2169 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2170 check_added_monitors!(nodes[0], 1);
2171 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2173 // Now just resolve all the outstanding messages/HTLCs for completeness...
2175 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2176 check_added_monitors!(nodes[1], 1);
2177 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2179 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2180 check_added_monitors!(nodes[1], 1);
2182 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2183 check_added_monitors!(nodes[0], 1);
2184 expect_payment_path_successful!(nodes[0]);
2185 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2187 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2188 check_added_monitors!(nodes[1], 1);
2189 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2191 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2192 check_added_monitors!(nodes[0], 1);
2194 expect_pending_htlcs_forwardable!(nodes[0]);
2195 expect_payment_claimable!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2197 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2198 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2202 fn channel_monitor_network_test() {
2203 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2204 // tests that ChannelMonitor is able to recover from various states.
2205 let chanmon_cfgs = create_chanmon_cfgs(5);
2206 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2207 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2208 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2210 // Create some initial channels
2211 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2212 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2213 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2214 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
2216 // Make sure all nodes are at the same starting height
2217 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2218 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2219 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2220 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2221 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2223 // Rebalance the network a bit by relaying one payment through all the channels...
2224 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2225 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2226 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2227 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2229 // Simple case with no pending HTLCs:
2230 nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2231 check_added_monitors!(nodes[1], 1);
2232 check_closed_broadcast!(nodes[1], true);
2234 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2235 assert_eq!(node_txn.len(), 1);
2236 mine_transaction(&nodes[0], &node_txn[0]);
2237 check_added_monitors!(nodes[0], 1);
2238 test_txn_broadcast(&nodes[0], &chan_1, Some(node_txn[0].clone()), HTLCType::NONE);
2240 check_closed_broadcast!(nodes[0], true);
2241 assert_eq!(nodes[0].node.list_channels().len(), 0);
2242 assert_eq!(nodes[1].node.list_channels().len(), 1);
2243 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2244 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2246 // One pending HTLC is discarded by the force-close:
2247 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2249 // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2250 // broadcasted until we reach the timelock time).
2251 nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2252 check_closed_broadcast!(nodes[1], true);
2253 check_added_monitors!(nodes[1], 1);
2255 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2256 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2257 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2258 mine_transaction(&nodes[2], &node_txn[0]);
2259 check_added_monitors!(nodes[2], 1);
2260 test_txn_broadcast(&nodes[2], &chan_2, Some(node_txn[0].clone()), HTLCType::NONE);
2262 check_closed_broadcast!(nodes[2], true);
2263 assert_eq!(nodes[1].node.list_channels().len(), 0);
2264 assert_eq!(nodes[2].node.list_channels().len(), 1);
2265 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2266 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2268 macro_rules! claim_funds {
2269 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2271 $node.node.claim_funds($preimage);
2272 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2273 check_added_monitors!($node, 1);
2275 let events = $node.node.get_and_clear_pending_msg_events();
2276 assert_eq!(events.len(), 1);
2278 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2279 assert!(update_add_htlcs.is_empty());
2280 assert!(update_fail_htlcs.is_empty());
2281 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2283 _ => panic!("Unexpected event"),
2289 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2290 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2291 nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2292 check_added_monitors!(nodes[2], 1);
2293 check_closed_broadcast!(nodes[2], true);
2294 let node2_commitment_txid;
2296 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2297 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2298 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2299 node2_commitment_txid = node_txn[0].txid();
2301 // Claim the payment on nodes[3], giving it knowledge of the preimage
2302 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2303 mine_transaction(&nodes[3], &node_txn[0]);
2304 check_added_monitors!(nodes[3], 1);
2305 check_preimage_claim(&nodes[3], &node_txn);
2307 check_closed_broadcast!(nodes[3], true);
2308 assert_eq!(nodes[2].node.list_channels().len(), 0);
2309 assert_eq!(nodes[3].node.list_channels().len(), 1);
2310 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2311 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2313 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2314 // confusing us in the following tests.
2315 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2317 // One pending HTLC to time out:
2318 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2319 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2322 let (close_chan_update_1, close_chan_update_2) = {
2323 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2324 let events = nodes[3].node.get_and_clear_pending_msg_events();
2325 assert_eq!(events.len(), 2);
2326 let close_chan_update_1 = match events[0] {
2327 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2330 _ => panic!("Unexpected event"),
2333 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2334 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2336 _ => panic!("Unexpected event"),
2338 check_added_monitors!(nodes[3], 1);
2340 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2342 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2343 node_txn.retain(|tx| {
2344 if tx.input[0].previous_output.txid == node2_commitment_txid {
2350 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2352 // Claim the payment on nodes[4], giving it knowledge of the preimage
2353 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2355 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2356 let events = nodes[4].node.get_and_clear_pending_msg_events();
2357 assert_eq!(events.len(), 2);
2358 let close_chan_update_2 = match events[0] {
2359 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2362 _ => panic!("Unexpected event"),
2365 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2366 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2368 _ => panic!("Unexpected event"),
2370 check_added_monitors!(nodes[4], 1);
2371 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2373 mine_transaction(&nodes[4], &node_txn[0]);
2374 check_preimage_claim(&nodes[4], &node_txn);
2375 (close_chan_update_1, close_chan_update_2)
2377 nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2378 nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2379 assert_eq!(nodes[3].node.list_channels().len(), 0);
2380 assert_eq!(nodes[4].node.list_channels().len(), 0);
2382 assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2383 ChannelMonitorUpdateStatus::Completed);
2384 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2385 check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2389 fn test_justice_tx_htlc_timeout() {
2390 // Test justice txn built on revoked HTLC-Timeout tx, against both sides
2391 let mut alice_config = UserConfig::default();
2392 alice_config.channel_handshake_config.announced_channel = true;
2393 alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2394 alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2395 let mut bob_config = UserConfig::default();
2396 bob_config.channel_handshake_config.announced_channel = true;
2397 bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2398 bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2399 let user_cfgs = [Some(alice_config), Some(bob_config)];
2400 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2401 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2402 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2403 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2404 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2405 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2406 // Create some new channels:
2407 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
2409 // A pending HTLC which will be revoked:
2410 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2411 // Get the will-be-revoked local txn from nodes[0]
2412 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2413 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2414 assert_eq!(revoked_local_txn[0].input.len(), 1);
2415 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2416 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2417 assert_eq!(revoked_local_txn[1].input.len(), 1);
2418 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2419 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2420 // Revoke the old state
2421 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2424 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2426 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2427 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2428 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2429 check_spends!(node_txn[0], revoked_local_txn[0]);
2430 node_txn.swap_remove(0);
2432 check_added_monitors!(nodes[1], 1);
2433 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2434 test_txn_broadcast(&nodes[1], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2436 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2437 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2438 // Verify broadcast of revoked HTLC-timeout
2439 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2440 check_added_monitors!(nodes[0], 1);
2441 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2442 // Broadcast revoked HTLC-timeout on node 1
2443 mine_transaction(&nodes[1], &node_txn[1]);
2444 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2446 get_announce_close_broadcast_events(&nodes, 0, 1);
2447 assert_eq!(nodes[0].node.list_channels().len(), 0);
2448 assert_eq!(nodes[1].node.list_channels().len(), 0);
2452 fn test_justice_tx_htlc_success() {
2453 // Test justice txn built on revoked HTLC-Success tx, against both sides
2454 let mut alice_config = UserConfig::default();
2455 alice_config.channel_handshake_config.announced_channel = true;
2456 alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2457 alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2458 let mut bob_config = UserConfig::default();
2459 bob_config.channel_handshake_config.announced_channel = true;
2460 bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2461 bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2462 let user_cfgs = [Some(alice_config), Some(bob_config)];
2463 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2464 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2465 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2466 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2467 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2468 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2469 // Create some new channels:
2470 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
2472 // A pending HTLC which will be revoked:
2473 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2474 // Get the will-be-revoked local txn from B
2475 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2476 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2477 assert_eq!(revoked_local_txn[0].input.len(), 1);
2478 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2479 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2480 // Revoke the old state
2481 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2483 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2485 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2486 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2487 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2489 check_spends!(node_txn[0], revoked_local_txn[0]);
2490 node_txn.swap_remove(0);
2492 check_added_monitors!(nodes[0], 1);
2493 test_txn_broadcast(&nodes[0], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2495 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2496 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2497 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2498 check_added_monitors!(nodes[1], 1);
2499 mine_transaction(&nodes[0], &node_txn[1]);
2500 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2501 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2503 get_announce_close_broadcast_events(&nodes, 0, 1);
2504 assert_eq!(nodes[0].node.list_channels().len(), 0);
2505 assert_eq!(nodes[1].node.list_channels().len(), 0);
2509 fn revoked_output_claim() {
2510 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2511 // transaction is broadcast by its counterparty
2512 let chanmon_cfgs = create_chanmon_cfgs(2);
2513 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2514 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2515 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2516 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2517 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2518 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2519 assert_eq!(revoked_local_txn.len(), 1);
2520 // Only output is the full channel value back to nodes[0]:
2521 assert_eq!(revoked_local_txn[0].output.len(), 1);
2522 // Send a payment through, updating everyone's latest commitment txn
2523 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2525 // Inform nodes[1] that nodes[0] broadcast a stale tx
2526 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2527 check_added_monitors!(nodes[1], 1);
2528 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2529 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2530 assert_eq!(node_txn.len(), 1); // ChannelMonitor: justice tx against revoked to_local output
2532 check_spends!(node_txn[0], revoked_local_txn[0]);
2534 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2535 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2536 get_announce_close_broadcast_events(&nodes, 0, 1);
2537 check_added_monitors!(nodes[0], 1);
2538 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2542 fn claim_htlc_outputs_shared_tx() {
2543 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2544 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2545 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2546 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2547 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2548 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2550 // Create some new channel:
2551 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2553 // Rebalance the network to generate htlc in the two directions
2554 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2555 // 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
2556 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2557 let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2559 // Get the will-be-revoked local txn from node[0]
2560 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2561 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2562 assert_eq!(revoked_local_txn[0].input.len(), 1);
2563 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2564 assert_eq!(revoked_local_txn[1].input.len(), 1);
2565 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2566 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2567 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2569 //Revoke the old state
2570 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2573 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2574 check_added_monitors!(nodes[0], 1);
2575 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2576 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2577 check_added_monitors!(nodes[1], 1);
2578 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2579 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2580 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2582 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2583 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2585 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2586 check_spends!(node_txn[0], revoked_local_txn[0]);
2588 let mut witness_lens = BTreeSet::new();
2589 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2590 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2591 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2592 assert_eq!(witness_lens.len(), 3);
2593 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2594 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2595 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2597 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2598 // ANTI_REORG_DELAY confirmations.
2599 mine_transaction(&nodes[1], &node_txn[0]);
2600 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2601 expect_payment_failed!(nodes[1], payment_hash_2, false);
2603 get_announce_close_broadcast_events(&nodes, 0, 1);
2604 assert_eq!(nodes[0].node.list_channels().len(), 0);
2605 assert_eq!(nodes[1].node.list_channels().len(), 0);
2609 fn claim_htlc_outputs_single_tx() {
2610 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2611 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2612 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2613 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2614 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2615 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2617 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2619 // Rebalance the network to generate htlc in the two directions
2620 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2621 // 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
2622 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2623 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2624 let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2626 // Get the will-be-revoked local txn from node[0]
2627 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2629 //Revoke the old state
2630 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2633 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2634 check_added_monitors!(nodes[0], 1);
2635 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2636 check_added_monitors!(nodes[1], 1);
2637 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2638 let mut events = nodes[0].node.get_and_clear_pending_events();
2639 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2640 match events.last().unwrap() {
2641 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2642 _ => panic!("Unexpected event"),
2645 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2646 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2648 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcast();
2650 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2651 assert_eq!(node_txn[0].input.len(), 1);
2652 check_spends!(node_txn[0], chan_1.3);
2653 assert_eq!(node_txn[1].input.len(), 1);
2654 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2655 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2656 check_spends!(node_txn[1], node_txn[0]);
2658 // Filter out any non justice transactions.
2659 node_txn.retain(|tx| tx.input[0].previous_output.txid == revoked_local_txn[0].txid());
2660 assert!(node_txn.len() > 3);
2662 assert_eq!(node_txn[0].input.len(), 1);
2663 assert_eq!(node_txn[1].input.len(), 1);
2664 assert_eq!(node_txn[2].input.len(), 1);
2666 check_spends!(node_txn[0], revoked_local_txn[0]);
2667 check_spends!(node_txn[1], revoked_local_txn[0]);
2668 check_spends!(node_txn[2], revoked_local_txn[0]);
2670 let mut witness_lens = BTreeSet::new();
2671 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2672 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2673 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2674 assert_eq!(witness_lens.len(), 3);
2675 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2676 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2677 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2679 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2680 // ANTI_REORG_DELAY confirmations.
2681 mine_transaction(&nodes[1], &node_txn[0]);
2682 mine_transaction(&nodes[1], &node_txn[1]);
2683 mine_transaction(&nodes[1], &node_txn[2]);
2684 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2685 expect_payment_failed!(nodes[1], payment_hash_2, false);
2687 get_announce_close_broadcast_events(&nodes, 0, 1);
2688 assert_eq!(nodes[0].node.list_channels().len(), 0);
2689 assert_eq!(nodes[1].node.list_channels().len(), 0);
2693 fn test_htlc_on_chain_success() {
2694 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2695 // the preimage backward accordingly. So here we test that ChannelManager is
2696 // broadcasting the right event to other nodes in payment path.
2697 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2698 // A --------------------> B ----------------------> C (preimage)
2699 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2700 // commitment transaction was broadcast.
2701 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2703 // B should be able to claim via preimage if A then broadcasts its local tx.
2704 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2705 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2706 // PaymentSent event).
2708 let chanmon_cfgs = create_chanmon_cfgs(3);
2709 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2710 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2711 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2713 // Create some initial channels
2714 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2715 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2717 // Ensure all nodes are at the same height
2718 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2719 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2720 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2721 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2723 // Rebalance the network a bit by relaying one payment through all the channels...
2724 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2725 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2727 let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2728 let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2730 // Broadcast legit commitment tx from C on B's chain
2731 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2732 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2733 assert_eq!(commitment_tx.len(), 1);
2734 check_spends!(commitment_tx[0], chan_2.3);
2735 nodes[2].node.claim_funds(our_payment_preimage);
2736 expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2737 nodes[2].node.claim_funds(our_payment_preimage_2);
2738 expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2739 check_added_monitors!(nodes[2], 2);
2740 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2741 assert!(updates.update_add_htlcs.is_empty());
2742 assert!(updates.update_fail_htlcs.is_empty());
2743 assert!(updates.update_fail_malformed_htlcs.is_empty());
2744 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2746 mine_transaction(&nodes[2], &commitment_tx[0]);
2747 check_closed_broadcast!(nodes[2], true);
2748 check_added_monitors!(nodes[2], 1);
2749 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2750 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 2 (2 * HTLC-Success tx)
2751 assert_eq!(node_txn.len(), 2);
2752 check_spends!(node_txn[0], commitment_tx[0]);
2753 check_spends!(node_txn[1], commitment_tx[0]);
2754 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2755 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2756 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2757 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2758 assert_eq!(node_txn[0].lock_time.0, 0);
2759 assert_eq!(node_txn[1].lock_time.0, 0);
2761 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2762 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()]));
2763 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2765 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2766 assert_eq!(added_monitors.len(), 1);
2767 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2768 added_monitors.clear();
2770 let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2771 assert_eq!(forwarded_events.len(), 3);
2772 match forwarded_events[0] {
2773 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2774 _ => panic!("Unexpected event"),
2776 let chan_id = Some(chan_1.2);
2777 match forwarded_events[1] {
2778 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2779 assert_eq!(fee_earned_msat, Some(1000));
2780 assert_eq!(prev_channel_id, chan_id);
2781 assert_eq!(claim_from_onchain_tx, true);
2782 assert_eq!(next_channel_id, Some(chan_2.2));
2783 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2787 match forwarded_events[2] {
2788 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2789 assert_eq!(fee_earned_msat, Some(1000));
2790 assert_eq!(prev_channel_id, chan_id);
2791 assert_eq!(claim_from_onchain_tx, true);
2792 assert_eq!(next_channel_id, Some(chan_2.2));
2793 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2797 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2799 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2800 assert_eq!(added_monitors.len(), 2);
2801 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2802 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2803 added_monitors.clear();
2805 assert_eq!(events.len(), 3);
2807 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
2808 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
2810 match nodes_2_event {
2811 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2812 _ => panic!("Unexpected event"),
2815 match nodes_0_event {
2816 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, .. } } => {
2817 assert!(update_add_htlcs.is_empty());
2818 assert!(update_fail_htlcs.is_empty());
2819 assert_eq!(update_fulfill_htlcs.len(), 1);
2820 assert!(update_fail_malformed_htlcs.is_empty());
2821 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2823 _ => panic!("Unexpected event"),
2826 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
2828 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2829 _ => panic!("Unexpected event"),
2832 macro_rules! check_tx_local_broadcast {
2833 ($node: expr, $htlc_offered: expr, $commitment_tx: expr) => { {
2834 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2835 assert_eq!(node_txn.len(), 2);
2836 // Node[1]: 2 * HTLC-timeout tx
2837 // Node[0]: 2 * HTLC-timeout tx
2838 check_spends!(node_txn[0], $commitment_tx);
2839 check_spends!(node_txn[1], $commitment_tx);
2840 assert_ne!(node_txn[0].lock_time.0, 0);
2841 assert_ne!(node_txn[1].lock_time.0, 0);
2843 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2844 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2845 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2846 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2848 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2849 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2850 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2851 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2856 // nodes[1] now broadcasts its own timeout-claim of the output that nodes[2] just claimed via success.
2857 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0]);
2859 // Broadcast legit commitment tx from A on B's chain
2860 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2861 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2862 check_spends!(node_a_commitment_tx[0], chan_1.3);
2863 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2864 check_closed_broadcast!(nodes[1], true);
2865 check_added_monitors!(nodes[1], 1);
2866 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2867 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2868 assert!(node_txn.len() == 1 || node_txn.len() == 3); // HTLC-Success, 2* RBF bumps of above HTLC txn
2869 let commitment_spend =
2870 if node_txn.len() == 1 {
2873 // Certain `ConnectStyle`s will cause RBF bumps of the previous HTLC transaction to be broadcast.
2874 // FullBlockViaListen
2875 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2876 check_spends!(node_txn[1], commitment_tx[0]);
2877 check_spends!(node_txn[2], commitment_tx[0]);
2878 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2881 check_spends!(node_txn[0], commitment_tx[0]);
2882 check_spends!(node_txn[1], commitment_tx[0]);
2883 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2888 check_spends!(commitment_spend, node_a_commitment_tx[0]);
2889 assert_eq!(commitment_spend.input.len(), 2);
2890 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2891 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2892 assert_eq!(commitment_spend.lock_time.0, nodes[1].best_block_info().1);
2893 assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2894 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2895 // we already checked the same situation with A.
2897 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2898 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()]));
2899 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
2900 check_closed_broadcast!(nodes[0], true);
2901 check_added_monitors!(nodes[0], 1);
2902 let events = nodes[0].node.get_and_clear_pending_events();
2903 assert_eq!(events.len(), 5);
2904 let mut first_claimed = false;
2905 for event in events {
2907 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2908 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2909 assert!(!first_claimed);
2910 first_claimed = true;
2912 assert_eq!(payment_preimage, our_payment_preimage_2);
2913 assert_eq!(payment_hash, payment_hash_2);
2916 Event::PaymentPathSuccessful { .. } => {},
2917 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2918 _ => panic!("Unexpected event"),
2921 check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0]);
2924 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2925 // Test that in case of a unilateral close onchain, we detect the state of output and
2926 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2927 // broadcasting the right event to other nodes in payment path.
2928 // A ------------------> B ----------------------> C (timeout)
2929 // B's commitment tx C's commitment tx
2931 // B's HTLC timeout tx B's timeout tx
2933 let chanmon_cfgs = create_chanmon_cfgs(3);
2934 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2935 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2936 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2937 *nodes[0].connect_style.borrow_mut() = connect_style;
2938 *nodes[1].connect_style.borrow_mut() = connect_style;
2939 *nodes[2].connect_style.borrow_mut() = connect_style;
2941 // Create some intial channels
2942 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2943 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2945 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2946 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2947 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2949 let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2951 // Broadcast legit commitment tx from C on B's chain
2952 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2953 check_spends!(commitment_tx[0], chan_2.3);
2954 nodes[2].node.fail_htlc_backwards(&payment_hash);
2955 check_added_monitors!(nodes[2], 0);
2956 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
2957 check_added_monitors!(nodes[2], 1);
2959 let events = nodes[2].node.get_and_clear_pending_msg_events();
2960 assert_eq!(events.len(), 1);
2962 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, .. } } => {
2963 assert!(update_add_htlcs.is_empty());
2964 assert!(!update_fail_htlcs.is_empty());
2965 assert!(update_fulfill_htlcs.is_empty());
2966 assert!(update_fail_malformed_htlcs.is_empty());
2967 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2969 _ => panic!("Unexpected event"),
2971 mine_transaction(&nodes[2], &commitment_tx[0]);
2972 check_closed_broadcast!(nodes[2], true);
2973 check_added_monitors!(nodes[2], 1);
2974 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2975 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2976 assert_eq!(node_txn.len(), 0);
2978 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2979 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2980 mine_transaction(&nodes[1], &commitment_tx[0]);
2981 check_closed_event(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false);
2982 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2984 let mut txn = nodes[1].tx_broadcaster.txn_broadcast();
2985 if nodes[1].connect_style.borrow().skips_blocks() {
2986 assert_eq!(txn.len(), 1);
2988 assert_eq!(txn.len(), 3); // Two extra fee bumps for timeout transaction
2990 txn.iter().for_each(|tx| check_spends!(tx, commitment_tx[0]));
2991 assert_eq!(txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2995 mine_transaction(&nodes[1], &timeout_tx);
2996 check_added_monitors!(nodes[1], 1);
2997 check_closed_broadcast!(nodes[1], true);
2999 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3001 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 }]);
3002 check_added_monitors!(nodes[1], 1);
3003 let events = nodes[1].node.get_and_clear_pending_msg_events();
3004 assert_eq!(events.len(), 1);
3006 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, .. } } => {
3007 assert!(update_add_htlcs.is_empty());
3008 assert!(!update_fail_htlcs.is_empty());
3009 assert!(update_fulfill_htlcs.is_empty());
3010 assert!(update_fail_malformed_htlcs.is_empty());
3011 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3013 _ => panic!("Unexpected event"),
3016 // Broadcast legit commitment tx from B on A's chain
3017 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3018 check_spends!(commitment_tx[0], chan_1.3);
3020 mine_transaction(&nodes[0], &commitment_tx[0]);
3021 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
3023 check_closed_broadcast!(nodes[0], true);
3024 check_added_monitors!(nodes[0], 1);
3025 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
3026 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // 1 timeout tx
3027 assert_eq!(node_txn.len(), 1);
3028 check_spends!(node_txn[0], commitment_tx[0]);
3029 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3033 fn test_htlc_on_chain_timeout() {
3034 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3035 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3036 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3040 fn test_simple_commitment_revoked_fail_backward() {
3041 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3042 // and fail backward accordingly.
3044 let chanmon_cfgs = create_chanmon_cfgs(3);
3045 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3046 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3047 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3049 // Create some initial channels
3050 create_announced_chan_between_nodes(&nodes, 0, 1);
3051 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3053 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3054 // Get the will-be-revoked local txn from nodes[2]
3055 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3056 // Revoke the old state
3057 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3059 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3061 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3062 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3063 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3064 check_added_monitors!(nodes[1], 1);
3065 check_closed_broadcast!(nodes[1], true);
3067 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 }]);
3068 check_added_monitors!(nodes[1], 1);
3069 let events = nodes[1].node.get_and_clear_pending_msg_events();
3070 assert_eq!(events.len(), 1);
3072 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, .. } } => {
3073 assert!(update_add_htlcs.is_empty());
3074 assert_eq!(update_fail_htlcs.len(), 1);
3075 assert!(update_fulfill_htlcs.is_empty());
3076 assert!(update_fail_malformed_htlcs.is_empty());
3077 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3079 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3080 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3081 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3083 _ => panic!("Unexpected event"),
3087 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3088 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3089 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3090 // commitment transaction anymore.
3091 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3092 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3093 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3094 // technically disallowed and we should probably handle it reasonably.
3095 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3096 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3098 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3099 // commitment_signed (implying it will be in the latest remote commitment transaction).
3100 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3101 // and once they revoke the previous commitment transaction (allowing us to send a new
3102 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3103 let chanmon_cfgs = create_chanmon_cfgs(3);
3104 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3105 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3106 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3108 // Create some initial channels
3109 create_announced_chan_between_nodes(&nodes, 0, 1);
3110 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3112 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 });
3113 // Get the will-be-revoked local txn from nodes[2]
3114 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3115 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3116 // Revoke the old state
3117 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3119 let value = if use_dust {
3120 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3121 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3122 nodes[2].node.per_peer_state.read().unwrap().get(&nodes[1].node.get_our_node_id())
3123 .unwrap().lock().unwrap().channel_by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3126 let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3127 let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3128 let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3130 nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3131 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3132 check_added_monitors!(nodes[2], 1);
3133 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3134 assert!(updates.update_add_htlcs.is_empty());
3135 assert!(updates.update_fulfill_htlcs.is_empty());
3136 assert!(updates.update_fail_malformed_htlcs.is_empty());
3137 assert_eq!(updates.update_fail_htlcs.len(), 1);
3138 assert!(updates.update_fee.is_none());
3139 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3140 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3141 // Drop the last RAA from 3 -> 2
3143 nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3144 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3145 check_added_monitors!(nodes[2], 1);
3146 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3147 assert!(updates.update_add_htlcs.is_empty());
3148 assert!(updates.update_fulfill_htlcs.is_empty());
3149 assert!(updates.update_fail_malformed_htlcs.is_empty());
3150 assert_eq!(updates.update_fail_htlcs.len(), 1);
3151 assert!(updates.update_fee.is_none());
3152 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3153 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3154 check_added_monitors!(nodes[1], 1);
3155 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3156 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3157 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3158 check_added_monitors!(nodes[2], 1);
3160 nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3161 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3162 check_added_monitors!(nodes[2], 1);
3163 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3164 assert!(updates.update_add_htlcs.is_empty());
3165 assert!(updates.update_fulfill_htlcs.is_empty());
3166 assert!(updates.update_fail_malformed_htlcs.is_empty());
3167 assert_eq!(updates.update_fail_htlcs.len(), 1);
3168 assert!(updates.update_fee.is_none());
3169 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3170 // At this point first_payment_hash has dropped out of the latest two commitment
3171 // transactions that nodes[1] is tracking...
3172 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3173 check_added_monitors!(nodes[1], 1);
3174 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3175 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3176 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3177 check_added_monitors!(nodes[2], 1);
3179 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3180 // on nodes[2]'s RAA.
3181 let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3182 nodes[1].node.send_payment_with_route(&route, fourth_payment_hash,
3183 RecipientOnionFields::secret_only(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3184 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3185 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3186 check_added_monitors!(nodes[1], 0);
3189 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3190 // One monitor for the new revocation preimage, no second on as we won't generate a new
3191 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3192 check_added_monitors!(nodes[1], 1);
3193 let events = nodes[1].node.get_and_clear_pending_events();
3194 assert_eq!(events.len(), 2);
3196 Event::PendingHTLCsForwardable { .. } => { },
3197 _ => panic!("Unexpected event"),
3200 Event::HTLCHandlingFailed { .. } => { },
3201 _ => panic!("Unexpected event"),
3203 // Deliberately don't process the pending fail-back so they all fail back at once after
3204 // block connection just like the !deliver_bs_raa case
3207 let mut failed_htlcs = HashSet::new();
3208 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3210 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3211 check_added_monitors!(nodes[1], 1);
3212 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3214 let events = nodes[1].node.get_and_clear_pending_events();
3215 assert_eq!(events.len(), if deliver_bs_raa { 3 + nodes.len() - 1 } else { 4 + nodes.len() });
3217 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3218 _ => panic!("Unexepected event"),
3221 Event::PaymentPathFailed { ref payment_hash, .. } => {
3222 assert_eq!(*payment_hash, fourth_payment_hash);
3224 _ => panic!("Unexpected event"),
3227 Event::PaymentFailed { ref payment_hash, .. } => {
3228 assert_eq!(*payment_hash, fourth_payment_hash);
3230 _ => panic!("Unexpected event"),
3233 nodes[1].node.process_pending_htlc_forwards();
3234 check_added_monitors!(nodes[1], 1);
3236 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
3237 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3240 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3241 match nodes_2_event {
3242 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, .. } } => {
3243 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3244 assert_eq!(update_add_htlcs.len(), 1);
3245 assert!(update_fulfill_htlcs.is_empty());
3246 assert!(update_fail_htlcs.is_empty());
3247 assert!(update_fail_malformed_htlcs.is_empty());
3249 _ => panic!("Unexpected event"),
3253 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3254 match nodes_2_event {
3255 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3256 assert_eq!(channel_id, chan_2.2);
3257 assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3259 _ => panic!("Unexpected event"),
3262 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
3263 match nodes_0_event {
3264 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, .. } } => {
3265 assert!(update_add_htlcs.is_empty());
3266 assert_eq!(update_fail_htlcs.len(), 3);
3267 assert!(update_fulfill_htlcs.is_empty());
3268 assert!(update_fail_malformed_htlcs.is_empty());
3269 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3271 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3272 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3273 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3275 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3277 let events = nodes[0].node.get_and_clear_pending_events();
3278 assert_eq!(events.len(), 6);
3280 Event::PaymentPathFailed { ref payment_hash, ref failure, .. } => {
3281 assert!(failed_htlcs.insert(payment_hash.0));
3282 // If we delivered B's RAA we got an unknown preimage error, not something
3283 // that we should update our routing table for.
3284 if !deliver_bs_raa {
3285 if let PathFailure::OnPath { network_update: Some(_) } = failure { } else { panic!("Unexpected path failure") }
3288 _ => panic!("Unexpected event"),
3291 Event::PaymentFailed { ref payment_hash, .. } => {
3292 assert_eq!(*payment_hash, first_payment_hash);
3294 _ => panic!("Unexpected event"),
3297 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3298 assert!(failed_htlcs.insert(payment_hash.0));
3300 _ => panic!("Unexpected event"),
3303 Event::PaymentFailed { ref payment_hash, .. } => {
3304 assert_eq!(*payment_hash, second_payment_hash);
3306 _ => panic!("Unexpected event"),
3309 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3310 assert!(failed_htlcs.insert(payment_hash.0));
3312 _ => panic!("Unexpected event"),
3315 Event::PaymentFailed { ref payment_hash, .. } => {
3316 assert_eq!(*payment_hash, third_payment_hash);
3318 _ => panic!("Unexpected event"),
3321 _ => panic!("Unexpected event"),
3324 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
3326 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3327 _ => panic!("Unexpected event"),
3330 assert!(failed_htlcs.contains(&first_payment_hash.0));
3331 assert!(failed_htlcs.contains(&second_payment_hash.0));
3332 assert!(failed_htlcs.contains(&third_payment_hash.0));
3336 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3337 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3338 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3339 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3340 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3344 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3345 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3346 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3347 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3348 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3352 fn fail_backward_pending_htlc_upon_channel_failure() {
3353 let chanmon_cfgs = create_chanmon_cfgs(2);
3354 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3355 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3356 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3357 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
3359 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3361 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3362 nodes[0].node.send_payment_with_route(&route, payment_hash, RecipientOnionFields::secret_only(payment_secret),
3363 PaymentId(payment_hash.0)).unwrap();
3364 check_added_monitors!(nodes[0], 1);
3366 let payment_event = {
3367 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3368 assert_eq!(events.len(), 1);
3369 SendEvent::from_event(events.remove(0))
3371 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3372 assert_eq!(payment_event.msgs.len(), 1);
3375 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3376 let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3378 nodes[0].node.send_payment_with_route(&route, failed_payment_hash,
3379 RecipientOnionFields::secret_only(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3380 check_added_monitors!(nodes[0], 0);
3382 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3385 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3387 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3389 let secp_ctx = Secp256k1::new();
3390 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3391 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3392 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(
3393 &route.paths[0], 50_000, RecipientOnionFields::secret_only(payment_secret), current_height, &None).unwrap();
3394 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3395 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
3397 // Send a 0-msat update_add_htlc to fail the channel.
3398 let update_add_htlc = msgs::UpdateAddHTLC {
3404 onion_routing_packet,
3406 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3408 let events = nodes[0].node.get_and_clear_pending_events();
3409 assert_eq!(events.len(), 3);
3410 // Check that Alice fails backward the pending HTLC from the second payment.
3412 Event::PaymentPathFailed { payment_hash, .. } => {
3413 assert_eq!(payment_hash, failed_payment_hash);
3415 _ => panic!("Unexpected event"),
3418 Event::PaymentFailed { payment_hash, .. } => {
3419 assert_eq!(payment_hash, failed_payment_hash);
3421 _ => panic!("Unexpected event"),
3424 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3425 assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3427 _ => panic!("Unexpected event {:?}", events[1]),
3429 check_closed_broadcast!(nodes[0], true);
3430 check_added_monitors!(nodes[0], 1);
3434 fn test_htlc_ignore_latest_remote_commitment() {
3435 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3436 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3437 let chanmon_cfgs = create_chanmon_cfgs(2);
3438 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3439 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3440 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3441 if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3442 // We rely on the ability to connect a block redundantly, which isn't allowed via
3443 // `chain::Listen`, so we never run the test if we randomly get assigned that
3447 create_announced_chan_between_nodes(&nodes, 0, 1);
3449 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3450 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3451 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3452 check_closed_broadcast!(nodes[0], true);
3453 check_added_monitors!(nodes[0], 1);
3454 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3456 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3457 assert_eq!(node_txn.len(), 3);
3458 assert_eq!(node_txn[0].txid(), node_txn[1].txid());
3460 let block = create_dummy_block(nodes[1].best_block_hash(), 42, vec![node_txn[0].clone(), node_txn[1].clone()]);
3461 connect_block(&nodes[1], &block);
3462 check_closed_broadcast!(nodes[1], true);
3463 check_added_monitors!(nodes[1], 1);
3464 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3466 // Duplicate the connect_block call since this may happen due to other listeners
3467 // registering new transactions
3468 connect_block(&nodes[1], &block);
3472 fn test_force_close_fail_back() {
3473 // Check which HTLCs are failed-backwards on channel force-closure
3474 let chanmon_cfgs = create_chanmon_cfgs(3);
3475 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3476 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3477 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3478 create_announced_chan_between_nodes(&nodes, 0, 1);
3479 create_announced_chan_between_nodes(&nodes, 1, 2);
3481 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3483 let mut payment_event = {
3484 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
3485 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3486 check_added_monitors!(nodes[0], 1);
3488 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3489 assert_eq!(events.len(), 1);
3490 SendEvent::from_event(events.remove(0))
3493 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3494 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3496 expect_pending_htlcs_forwardable!(nodes[1]);
3498 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3499 assert_eq!(events_2.len(), 1);
3500 payment_event = SendEvent::from_event(events_2.remove(0));
3501 assert_eq!(payment_event.msgs.len(), 1);
3503 check_added_monitors!(nodes[1], 1);
3504 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3505 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3506 check_added_monitors!(nodes[2], 1);
3507 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3509 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3510 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3511 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3513 nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3514 check_closed_broadcast!(nodes[2], true);
3515 check_added_monitors!(nodes[2], 1);
3516 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3518 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3519 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3520 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3521 // back to nodes[1] upon timeout otherwise.
3522 assert_eq!(node_txn.len(), 1);
3526 mine_transaction(&nodes[1], &tx);
3528 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3529 check_closed_broadcast!(nodes[1], true);
3530 check_added_monitors!(nodes[1], 1);
3531 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3533 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3535 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3536 .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);
3538 mine_transaction(&nodes[2], &tx);
3539 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3540 assert_eq!(node_txn.len(), 1);
3541 assert_eq!(node_txn[0].input.len(), 1);
3542 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3543 assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3544 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3546 check_spends!(node_txn[0], tx);
3550 fn test_dup_events_on_peer_disconnect() {
3551 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3552 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3553 // as we used to generate the event immediately upon receipt of the payment preimage in the
3554 // update_fulfill_htlc message.
3556 let chanmon_cfgs = create_chanmon_cfgs(2);
3557 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3558 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3559 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3560 create_announced_chan_between_nodes(&nodes, 0, 1);
3562 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3564 nodes[1].node.claim_funds(payment_preimage);
3565 expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3566 check_added_monitors!(nodes[1], 1);
3567 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3568 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3569 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3571 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3572 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3574 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3575 expect_payment_path_successful!(nodes[0]);
3579 fn test_peer_disconnected_before_funding_broadcasted() {
3580 // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3581 // before the funding transaction has been broadcasted.
3582 let chanmon_cfgs = create_chanmon_cfgs(2);
3583 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3584 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3585 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3587 // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3588 // broadcasted, even though it's created by `nodes[0]`.
3589 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();
3590 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3591 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
3592 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3593 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
3595 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3596 assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3598 assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3600 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3601 assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3603 // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3604 // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3607 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3610 // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3611 // disconnected before the funding transaction was broadcasted.
3612 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3613 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3615 check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3616 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3620 fn test_simple_peer_disconnect() {
3621 // Test that we can reconnect when there are no lost messages
3622 let chanmon_cfgs = create_chanmon_cfgs(3);
3623 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3624 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3625 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3626 create_announced_chan_between_nodes(&nodes, 0, 1);
3627 create_announced_chan_between_nodes(&nodes, 1, 2);
3629 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3630 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3631 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3633 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3634 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3635 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3636 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3638 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3639 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3640 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3642 let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3643 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3644 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3645 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3647 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3648 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3650 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3651 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3653 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3655 let events = nodes[0].node.get_and_clear_pending_events();
3656 assert_eq!(events.len(), 4);
3658 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3659 assert_eq!(payment_preimage, payment_preimage_3);
3660 assert_eq!(payment_hash, payment_hash_3);
3662 _ => panic!("Unexpected event"),
3665 Event::PaymentPathSuccessful { .. } => {},
3666 _ => panic!("Unexpected event"),
3669 Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3670 assert_eq!(payment_hash, payment_hash_5);
3671 assert!(payment_failed_permanently);
3673 _ => panic!("Unexpected event"),
3676 Event::PaymentFailed { payment_hash, .. } => {
3677 assert_eq!(payment_hash, payment_hash_5);
3679 _ => panic!("Unexpected event"),
3683 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3684 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3687 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3688 // Test that we can reconnect when in-flight HTLC updates get dropped
3689 let chanmon_cfgs = create_chanmon_cfgs(2);
3690 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3691 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3692 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3694 let mut as_channel_ready = None;
3695 let channel_id = if messages_delivered == 0 {
3696 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3697 as_channel_ready = Some(channel_ready);
3698 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3699 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3700 // it before the channel_reestablish message.
3703 create_announced_chan_between_nodes(&nodes, 0, 1).2
3706 let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3708 let payment_event = {
3709 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
3710 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3711 check_added_monitors!(nodes[0], 1);
3713 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3714 assert_eq!(events.len(), 1);
3715 SendEvent::from_event(events.remove(0))
3717 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3719 if messages_delivered < 2 {
3720 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3722 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3723 if messages_delivered >= 3 {
3724 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3725 check_added_monitors!(nodes[1], 1);
3726 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3728 if messages_delivered >= 4 {
3729 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3730 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3731 check_added_monitors!(nodes[0], 1);
3733 if messages_delivered >= 5 {
3734 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3735 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3736 // No commitment_signed so get_event_msg's assert(len == 1) passes
3737 check_added_monitors!(nodes[0], 1);
3739 if messages_delivered >= 6 {
3740 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3741 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3742 check_added_monitors!(nodes[1], 1);
3749 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3750 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3751 if messages_delivered < 3 {
3752 if simulate_broken_lnd {
3753 // lnd has a long-standing bug where they send a channel_ready prior to a
3754 // channel_reestablish if you reconnect prior to channel_ready time.
3756 // Here we simulate that behavior, delivering a channel_ready immediately on
3757 // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3758 // in `reconnect_nodes` but we currently don't fail based on that.
3760 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3761 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3763 // Even if the channel_ready messages get exchanged, as long as nothing further was
3764 // received on either side, both sides will need to resend them.
3765 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3766 } else if messages_delivered == 3 {
3767 // nodes[0] still wants its RAA + commitment_signed
3768 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3769 } else if messages_delivered == 4 {
3770 // nodes[0] still wants its commitment_signed
3771 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3772 } else if messages_delivered == 5 {
3773 // nodes[1] still wants its final RAA
3774 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3775 } else if messages_delivered == 6 {
3776 // Everything was delivered...
3777 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3780 let events_1 = nodes[1].node.get_and_clear_pending_events();
3781 if messages_delivered == 0 {
3782 assert_eq!(events_1.len(), 2);
3784 Event::ChannelReady { .. } => { },
3785 _ => panic!("Unexpected event"),
3788 Event::PendingHTLCsForwardable { .. } => { },
3789 _ => panic!("Unexpected event"),
3792 assert_eq!(events_1.len(), 1);
3794 Event::PendingHTLCsForwardable { .. } => { },
3795 _ => panic!("Unexpected event"),
3799 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3800 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3801 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3803 nodes[1].node.process_pending_htlc_forwards();
3805 let events_2 = nodes[1].node.get_and_clear_pending_events();
3806 assert_eq!(events_2.len(), 1);
3808 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
3809 assert_eq!(payment_hash_1, *payment_hash);
3810 assert_eq!(amount_msat, 1_000_000);
3811 assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3812 assert_eq!(via_channel_id, Some(channel_id));
3814 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3815 assert!(payment_preimage.is_none());
3816 assert_eq!(payment_secret_1, *payment_secret);
3818 _ => panic!("expected PaymentPurpose::InvoicePayment")
3821 _ => panic!("Unexpected event"),
3824 nodes[1].node.claim_funds(payment_preimage_1);
3825 check_added_monitors!(nodes[1], 1);
3826 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3828 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3829 assert_eq!(events_3.len(), 1);
3830 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3831 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3832 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3833 assert!(updates.update_add_htlcs.is_empty());
3834 assert!(updates.update_fail_htlcs.is_empty());
3835 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3836 assert!(updates.update_fail_malformed_htlcs.is_empty());
3837 assert!(updates.update_fee.is_none());
3838 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3840 _ => panic!("Unexpected event"),
3843 if messages_delivered >= 1 {
3844 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3846 let events_4 = nodes[0].node.get_and_clear_pending_events();
3847 assert_eq!(events_4.len(), 1);
3849 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3850 assert_eq!(payment_preimage_1, *payment_preimage);
3851 assert_eq!(payment_hash_1, *payment_hash);
3853 _ => panic!("Unexpected event"),
3856 if messages_delivered >= 2 {
3857 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3858 check_added_monitors!(nodes[0], 1);
3859 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3861 if messages_delivered >= 3 {
3862 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3863 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3864 check_added_monitors!(nodes[1], 1);
3866 if messages_delivered >= 4 {
3867 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3868 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3869 // No commitment_signed so get_event_msg's assert(len == 1) passes
3870 check_added_monitors!(nodes[1], 1);
3872 if messages_delivered >= 5 {
3873 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3874 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3875 check_added_monitors!(nodes[0], 1);
3882 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3883 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3884 if messages_delivered < 2 {
3885 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3886 if messages_delivered < 1 {
3887 expect_payment_sent!(nodes[0], payment_preimage_1);
3889 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3891 } else if messages_delivered == 2 {
3892 // nodes[0] still wants its RAA + commitment_signed
3893 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3894 } else if messages_delivered == 3 {
3895 // nodes[0] still wants its commitment_signed
3896 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3897 } else if messages_delivered == 4 {
3898 // nodes[1] still wants its final RAA
3899 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3900 } else if messages_delivered == 5 {
3901 // Everything was delivered...
3902 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3905 if messages_delivered == 1 || messages_delivered == 2 {
3906 expect_payment_path_successful!(nodes[0]);
3908 if messages_delivered <= 5 {
3909 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3910 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3912 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3914 if messages_delivered > 2 {
3915 expect_payment_path_successful!(nodes[0]);
3918 // Channel should still work fine...
3919 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3920 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3921 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3925 fn test_drop_messages_peer_disconnect_a() {
3926 do_test_drop_messages_peer_disconnect(0, true);
3927 do_test_drop_messages_peer_disconnect(0, false);
3928 do_test_drop_messages_peer_disconnect(1, false);
3929 do_test_drop_messages_peer_disconnect(2, false);
3933 fn test_drop_messages_peer_disconnect_b() {
3934 do_test_drop_messages_peer_disconnect(3, false);
3935 do_test_drop_messages_peer_disconnect(4, false);
3936 do_test_drop_messages_peer_disconnect(5, false);
3937 do_test_drop_messages_peer_disconnect(6, false);
3941 fn test_channel_ready_without_best_block_updated() {
3942 // Previously, if we were offline when a funding transaction was locked in, and then we came
3943 // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
3944 // generate a channel_ready until a later best_block_updated. This tests that we generate the
3945 // channel_ready immediately instead.
3946 let chanmon_cfgs = create_chanmon_cfgs(2);
3947 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3948 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3949 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3950 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
3952 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
3954 let conf_height = nodes[0].best_block_info().1 + 1;
3955 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
3956 let block_txn = [funding_tx];
3957 let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
3958 let conf_block_header = nodes[0].get_block_header(conf_height);
3959 nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
3961 // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
3962 let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
3963 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3967 fn test_drop_messages_peer_disconnect_dual_htlc() {
3968 // Test that we can handle reconnecting when both sides of a channel have pending
3969 // commitment_updates when we disconnect.
3970 let chanmon_cfgs = create_chanmon_cfgs(2);
3971 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3972 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3973 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3974 create_announced_chan_between_nodes(&nodes, 0, 1);
3976 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3978 // Now try to send a second payment which will fail to send
3979 let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3980 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
3981 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
3982 check_added_monitors!(nodes[0], 1);
3984 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3985 assert_eq!(events_1.len(), 1);
3987 MessageSendEvent::UpdateHTLCs { .. } => {},
3988 _ => panic!("Unexpected event"),
3991 nodes[1].node.claim_funds(payment_preimage_1);
3992 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3993 check_added_monitors!(nodes[1], 1);
3995 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3996 assert_eq!(events_2.len(), 1);
3998 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 } } => {
3999 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4000 assert!(update_add_htlcs.is_empty());
4001 assert_eq!(update_fulfill_htlcs.len(), 1);
4002 assert!(update_fail_htlcs.is_empty());
4003 assert!(update_fail_malformed_htlcs.is_empty());
4004 assert!(update_fee.is_none());
4006 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4007 let events_3 = nodes[0].node.get_and_clear_pending_events();
4008 assert_eq!(events_3.len(), 1);
4010 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4011 assert_eq!(*payment_preimage, payment_preimage_1);
4012 assert_eq!(*payment_hash, payment_hash_1);
4014 _ => panic!("Unexpected event"),
4017 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4018 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4019 // No commitment_signed so get_event_msg's assert(len == 1) passes
4020 check_added_monitors!(nodes[0], 1);
4022 _ => panic!("Unexpected event"),
4025 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4026 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4028 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: nodes[1].node.init_features(), remote_network_address: None }, true).unwrap();
4029 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4030 assert_eq!(reestablish_1.len(), 1);
4031 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: nodes[0].node.init_features(), remote_network_address: None }, false).unwrap();
4032 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4033 assert_eq!(reestablish_2.len(), 1);
4035 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4036 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4037 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4038 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4040 assert!(as_resp.0.is_none());
4041 assert!(bs_resp.0.is_none());
4043 assert!(bs_resp.1.is_none());
4044 assert!(bs_resp.2.is_none());
4046 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4048 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4049 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4050 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4051 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4052 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4053 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4054 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4055 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4056 // No commitment_signed so get_event_msg's assert(len == 1) passes
4057 check_added_monitors!(nodes[1], 1);
4059 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4060 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4061 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4062 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4063 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4064 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4065 assert!(bs_second_commitment_signed.update_fee.is_none());
4066 check_added_monitors!(nodes[1], 1);
4068 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4069 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4070 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4071 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4072 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4073 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4074 assert!(as_commitment_signed.update_fee.is_none());
4075 check_added_monitors!(nodes[0], 1);
4077 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4078 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4079 // No commitment_signed so get_event_msg's assert(len == 1) passes
4080 check_added_monitors!(nodes[0], 1);
4082 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4083 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4084 // No commitment_signed so get_event_msg's assert(len == 1) passes
4085 check_added_monitors!(nodes[1], 1);
4087 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4088 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4089 check_added_monitors!(nodes[1], 1);
4091 expect_pending_htlcs_forwardable!(nodes[1]);
4093 let events_5 = nodes[1].node.get_and_clear_pending_events();
4094 assert_eq!(events_5.len(), 1);
4096 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4097 assert_eq!(payment_hash_2, *payment_hash);
4099 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4100 assert!(payment_preimage.is_none());
4101 assert_eq!(payment_secret_2, *payment_secret);
4103 _ => panic!("expected PaymentPurpose::InvoicePayment")
4106 _ => panic!("Unexpected event"),
4109 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4110 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4111 check_added_monitors!(nodes[0], 1);
4113 expect_payment_path_successful!(nodes[0]);
4114 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4117 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4118 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4119 // to avoid our counterparty failing the channel.
4120 let chanmon_cfgs = create_chanmon_cfgs(2);
4121 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4122 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4123 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4125 create_announced_chan_between_nodes(&nodes, 0, 1);
4127 let our_payment_hash = if send_partial_mpp {
4128 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4129 // Use the utility function send_payment_along_path to send the payment with MPP data which
4130 // indicates there are more HTLCs coming.
4131 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.
4132 let payment_id = PaymentId([42; 32]);
4133 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
4134 RecipientOnionFields::secret_only(payment_secret), payment_id, &route).unwrap();
4135 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
4136 RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id,
4137 &None, session_privs[0]).unwrap();
4138 check_added_monitors!(nodes[0], 1);
4139 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4140 assert_eq!(events.len(), 1);
4141 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4142 // hop should *not* yet generate any PaymentClaimable event(s).
4143 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4146 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4149 let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
4150 connect_block(&nodes[0], &block);
4151 connect_block(&nodes[1], &block);
4152 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4153 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4154 block.header.prev_blockhash = block.block_hash();
4155 connect_block(&nodes[0], &block);
4156 connect_block(&nodes[1], &block);
4159 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4161 check_added_monitors!(nodes[1], 1);
4162 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4163 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4164 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4165 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4166 assert!(htlc_timeout_updates.update_fee.is_none());
4168 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4169 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4170 // 100_000 msat as u64, followed by the height at which we failed back above
4171 let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4172 expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4173 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4177 fn test_htlc_timeout() {
4178 do_test_htlc_timeout(true);
4179 do_test_htlc_timeout(false);
4182 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4183 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4184 let chanmon_cfgs = create_chanmon_cfgs(3);
4185 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4186 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4187 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4188 create_announced_chan_between_nodes(&nodes, 0, 1);
4189 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4191 // Make sure all nodes are at the same starting height
4192 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4193 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4194 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4196 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4197 let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4198 nodes[1].node.send_payment_with_route(&route, first_payment_hash,
4199 RecipientOnionFields::secret_only(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4200 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4201 check_added_monitors!(nodes[1], 1);
4203 // Now attempt to route a second payment, which should be placed in the holding cell
4204 let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4205 let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4206 sending_node.node.send_payment_with_route(&route, second_payment_hash,
4207 RecipientOnionFields::secret_only(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4209 check_added_monitors!(nodes[0], 1);
4210 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4211 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4212 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4213 expect_pending_htlcs_forwardable!(nodes[1]);
4215 check_added_monitors!(nodes[1], 0);
4217 connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4218 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4219 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4220 connect_blocks(&nodes[1], 1);
4223 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 }]);
4224 check_added_monitors!(nodes[1], 1);
4225 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4226 assert_eq!(fail_commit.len(), 1);
4227 match fail_commit[0] {
4228 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4229 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4230 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4232 _ => unreachable!(),
4234 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4236 expect_payment_failed!(nodes[1], second_payment_hash, false);
4241 fn test_holding_cell_htlc_add_timeouts() {
4242 do_test_holding_cell_htlc_add_timeouts(false);
4243 do_test_holding_cell_htlc_add_timeouts(true);
4246 macro_rules! check_spendable_outputs {
4247 ($node: expr, $keysinterface: expr) => {
4249 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4250 let mut txn = Vec::new();
4251 let mut all_outputs = Vec::new();
4252 let secp_ctx = Secp256k1::new();
4253 for event in events.drain(..) {
4255 Event::SpendableOutputs { mut outputs } => {
4256 for outp in outputs.drain(..) {
4257 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());
4258 all_outputs.push(outp);
4261 _ => panic!("Unexpected event"),
4264 if all_outputs.len() > 1 {
4265 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) {
4275 fn test_claim_sizeable_push_msat() {
4276 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4277 let chanmon_cfgs = create_chanmon_cfgs(2);
4278 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4279 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4280 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4282 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4283 nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4284 check_closed_broadcast!(nodes[1], true);
4285 check_added_monitors!(nodes[1], 1);
4286 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4287 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4288 assert_eq!(node_txn.len(), 1);
4289 check_spends!(node_txn[0], chan.3);
4290 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
4292 mine_transaction(&nodes[1], &node_txn[0]);
4293 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4295 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4296 assert_eq!(spend_txn.len(), 1);
4297 assert_eq!(spend_txn[0].input.len(), 1);
4298 check_spends!(spend_txn[0], node_txn[0]);
4299 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4303 fn test_claim_on_remote_sizeable_push_msat() {
4304 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4305 // to_remote output is encumbered by a P2WPKH
4306 let chanmon_cfgs = create_chanmon_cfgs(2);
4307 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4308 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4309 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4311 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4312 nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4313 check_closed_broadcast!(nodes[0], true);
4314 check_added_monitors!(nodes[0], 1);
4315 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4317 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4318 assert_eq!(node_txn.len(), 1);
4319 check_spends!(node_txn[0], chan.3);
4320 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
4322 mine_transaction(&nodes[1], &node_txn[0]);
4323 check_closed_broadcast!(nodes[1], true);
4324 check_added_monitors!(nodes[1], 1);
4325 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4326 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4328 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4329 assert_eq!(spend_txn.len(), 1);
4330 check_spends!(spend_txn[0], node_txn[0]);
4334 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4335 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4336 // to_remote output is encumbered by a P2WPKH
4338 let chanmon_cfgs = create_chanmon_cfgs(2);
4339 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4340 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4341 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4343 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4344 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4345 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4346 assert_eq!(revoked_local_txn[0].input.len(), 1);
4347 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4349 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4350 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4351 check_closed_broadcast!(nodes[1], true);
4352 check_added_monitors!(nodes[1], 1);
4353 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4355 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4356 mine_transaction(&nodes[1], &node_txn[0]);
4357 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4359 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4360 assert_eq!(spend_txn.len(), 3);
4361 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4362 check_spends!(spend_txn[1], node_txn[0]);
4363 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4367 fn test_static_spendable_outputs_preimage_tx() {
4368 let chanmon_cfgs = create_chanmon_cfgs(2);
4369 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4370 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4371 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4373 // Create some initial channels
4374 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4376 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4378 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4379 assert_eq!(commitment_tx[0].input.len(), 1);
4380 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4382 // Settle A's commitment tx on B's chain
4383 nodes[1].node.claim_funds(payment_preimage);
4384 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4385 check_added_monitors!(nodes[1], 1);
4386 mine_transaction(&nodes[1], &commitment_tx[0]);
4387 check_added_monitors!(nodes[1], 1);
4388 let events = nodes[1].node.get_and_clear_pending_msg_events();
4390 MessageSendEvent::UpdateHTLCs { .. } => {},
4391 _ => panic!("Unexpected event"),
4394 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4395 _ => panic!("Unexepected event"),
4398 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4399 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4400 assert_eq!(node_txn.len(), 1);
4401 check_spends!(node_txn[0], commitment_tx[0]);
4402 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4404 mine_transaction(&nodes[1], &node_txn[0]);
4405 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4406 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4408 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4409 assert_eq!(spend_txn.len(), 1);
4410 check_spends!(spend_txn[0], node_txn[0]);
4414 fn test_static_spendable_outputs_timeout_tx() {
4415 let chanmon_cfgs = create_chanmon_cfgs(2);
4416 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4417 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4418 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4420 // Create some initial channels
4421 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4423 // Rebalance the network a bit by relaying one payment through all the channels ...
4424 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4426 let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4428 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4429 assert_eq!(commitment_tx[0].input.len(), 1);
4430 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4432 // Settle A's commitment tx on B' chain
4433 mine_transaction(&nodes[1], &commitment_tx[0]);
4434 check_added_monitors!(nodes[1], 1);
4435 let events = nodes[1].node.get_and_clear_pending_msg_events();
4437 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4438 _ => panic!("Unexpected event"),
4440 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4442 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4443 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4444 assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4445 check_spends!(node_txn[0], commitment_tx[0].clone());
4446 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4448 mine_transaction(&nodes[1], &node_txn[0]);
4449 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4450 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4451 expect_payment_failed!(nodes[1], our_payment_hash, false);
4453 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4454 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4455 check_spends!(spend_txn[0], commitment_tx[0]);
4456 check_spends!(spend_txn[1], node_txn[0]);
4457 check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4461 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4462 let chanmon_cfgs = create_chanmon_cfgs(2);
4463 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4464 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4465 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4467 // Create some initial channels
4468 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4470 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4471 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4472 assert_eq!(revoked_local_txn[0].input.len(), 1);
4473 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4475 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4477 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4478 check_closed_broadcast!(nodes[1], true);
4479 check_added_monitors!(nodes[1], 1);
4480 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4482 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4483 assert_eq!(node_txn.len(), 1);
4484 assert_eq!(node_txn[0].input.len(), 2);
4485 check_spends!(node_txn[0], revoked_local_txn[0]);
4487 mine_transaction(&nodes[1], &node_txn[0]);
4488 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4490 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4491 assert_eq!(spend_txn.len(), 1);
4492 check_spends!(spend_txn[0], node_txn[0]);
4496 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4497 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4498 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4499 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4500 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4501 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4503 // Create some initial channels
4504 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4506 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4507 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4508 assert_eq!(revoked_local_txn[0].input.len(), 1);
4509 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4511 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4513 // A will generate HTLC-Timeout from revoked commitment tx
4514 mine_transaction(&nodes[0], &revoked_local_txn[0]);
4515 check_closed_broadcast!(nodes[0], true);
4516 check_added_monitors!(nodes[0], 1);
4517 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4518 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4520 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4521 assert_eq!(revoked_htlc_txn.len(), 1);
4522 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4523 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4524 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4525 assert_ne!(revoked_htlc_txn[0].lock_time.0, 0); // HTLC-Timeout
4527 // B will generate justice tx from A's revoked commitment/HTLC tx
4528 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4529 check_closed_broadcast!(nodes[1], true);
4530 check_added_monitors!(nodes[1], 1);
4531 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4533 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4534 assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4535 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4536 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4537 // transactions next...
4538 assert_eq!(node_txn[0].input.len(), 3);
4539 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4541 assert_eq!(node_txn[1].input.len(), 2);
4542 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4543 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4544 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4546 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4547 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4550 mine_transaction(&nodes[1], &node_txn[1]);
4551 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4553 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4554 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4555 assert_eq!(spend_txn.len(), 1);
4556 assert_eq!(spend_txn[0].input.len(), 1);
4557 check_spends!(spend_txn[0], node_txn[1]);
4561 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4562 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4563 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4564 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4565 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4566 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4568 // Create some initial channels
4569 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4571 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4572 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4573 assert_eq!(revoked_local_txn[0].input.len(), 1);
4574 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4576 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4577 assert_eq!(revoked_local_txn[0].output.len(), 2);
4579 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4581 // B will generate HTLC-Success from revoked commitment tx
4582 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4583 check_closed_broadcast!(nodes[1], true);
4584 check_added_monitors!(nodes[1], 1);
4585 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4586 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4588 assert_eq!(revoked_htlc_txn.len(), 1);
4589 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4590 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4591 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4593 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4594 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4595 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4597 // A will generate justice tx from B's revoked commitment/HTLC tx
4598 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4599 check_closed_broadcast!(nodes[0], true);
4600 check_added_monitors!(nodes[0], 1);
4601 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4603 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4604 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4606 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4607 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4608 // transactions next...
4609 assert_eq!(node_txn[0].input.len(), 2);
4610 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4611 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4612 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4614 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4615 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4618 assert_eq!(node_txn[1].input.len(), 1);
4619 check_spends!(node_txn[1], revoked_htlc_txn[0]);
4621 mine_transaction(&nodes[0], &node_txn[1]);
4622 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4624 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4625 // didn't try to generate any new transactions.
4627 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4628 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4629 assert_eq!(spend_txn.len(), 3);
4630 assert_eq!(spend_txn[0].input.len(), 1);
4631 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4632 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4633 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4634 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4638 fn test_onchain_to_onchain_claim() {
4639 // Test that in case of channel closure, we detect the state of output and claim HTLC
4640 // on downstream peer's remote commitment tx.
4641 // First, have C claim an HTLC against its own latest commitment transaction.
4642 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4644 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4647 let chanmon_cfgs = create_chanmon_cfgs(3);
4648 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4649 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4650 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4652 // Create some initial channels
4653 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4654 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4656 // Ensure all nodes are at the same height
4657 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4658 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4659 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4660 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4662 // Rebalance the network a bit by relaying one payment through all the channels ...
4663 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4664 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4666 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4667 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4668 check_spends!(commitment_tx[0], chan_2.3);
4669 nodes[2].node.claim_funds(payment_preimage);
4670 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4671 check_added_monitors!(nodes[2], 1);
4672 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4673 assert!(updates.update_add_htlcs.is_empty());
4674 assert!(updates.update_fail_htlcs.is_empty());
4675 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4676 assert!(updates.update_fail_malformed_htlcs.is_empty());
4678 mine_transaction(&nodes[2], &commitment_tx[0]);
4679 check_closed_broadcast!(nodes[2], true);
4680 check_added_monitors!(nodes[2], 1);
4681 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4683 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4684 assert_eq!(c_txn.len(), 1);
4685 check_spends!(c_txn[0], commitment_tx[0]);
4686 assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4687 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4688 assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
4690 // 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
4691 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![commitment_tx[0].clone(), c_txn[0].clone()]));
4692 check_added_monitors!(nodes[1], 1);
4693 let events = nodes[1].node.get_and_clear_pending_events();
4694 assert_eq!(events.len(), 2);
4696 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4697 _ => panic!("Unexpected event"),
4700 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
4701 assert_eq!(fee_earned_msat, Some(1000));
4702 assert_eq!(prev_channel_id, Some(chan_1.2));
4703 assert_eq!(claim_from_onchain_tx, true);
4704 assert_eq!(next_channel_id, Some(chan_2.2));
4705 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
4707 _ => panic!("Unexpected event"),
4709 check_added_monitors!(nodes[1], 1);
4710 let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4711 assert_eq!(msg_events.len(), 3);
4712 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut msg_events);
4713 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut msg_events);
4715 match nodes_2_event {
4716 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
4717 _ => panic!("Unexpected event"),
4720 match nodes_0_event {
4721 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, .. } } => {
4722 assert!(update_add_htlcs.is_empty());
4723 assert!(update_fail_htlcs.is_empty());
4724 assert_eq!(update_fulfill_htlcs.len(), 1);
4725 assert!(update_fail_malformed_htlcs.is_empty());
4726 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4728 _ => panic!("Unexpected event"),
4731 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
4732 match msg_events[0] {
4733 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4734 _ => panic!("Unexpected event"),
4737 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4738 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4739 mine_transaction(&nodes[1], &commitment_tx[0]);
4740 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4741 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4742 // ChannelMonitor: HTLC-Success tx
4743 assert_eq!(b_txn.len(), 1);
4744 check_spends!(b_txn[0], commitment_tx[0]);
4745 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4746 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4747 assert_eq!(b_txn[0].lock_time.0, nodes[1].best_block_info().1); // Success tx
4749 check_closed_broadcast!(nodes[1], true);
4750 check_added_monitors!(nodes[1], 1);
4754 fn test_duplicate_payment_hash_one_failure_one_success() {
4755 // Topology : A --> B --> C --> D
4756 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4757 // Note that because C will refuse to generate two payment secrets for the same payment hash,
4758 // we forward one of the payments onwards to D.
4759 let chanmon_cfgs = create_chanmon_cfgs(4);
4760 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4761 // When this test was written, the default base fee floated based on the HTLC count.
4762 // It is now fixed, so we simply set the fee to the expected value here.
4763 let mut config = test_default_channel_config();
4764 config.channel_config.forwarding_fee_base_msat = 196;
4765 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4766 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4767 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4769 create_announced_chan_between_nodes(&nodes, 0, 1);
4770 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4771 create_announced_chan_between_nodes(&nodes, 2, 3);
4773 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4774 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4775 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4776 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4777 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4779 let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
4781 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
4782 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4783 // script push size limit so that the below script length checks match
4784 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
4785 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV - 40)
4786 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
4787 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000);
4788 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
4790 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4791 assert_eq!(commitment_txn[0].input.len(), 1);
4792 check_spends!(commitment_txn[0], chan_2.3);
4794 mine_transaction(&nodes[1], &commitment_txn[0]);
4795 check_closed_broadcast!(nodes[1], true);
4796 check_added_monitors!(nodes[1], 1);
4797 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4798 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
4800 let htlc_timeout_tx;
4801 { // Extract one of the two HTLC-Timeout transaction
4802 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4803 // ChannelMonitor: timeout tx * 2-or-3
4804 assert!(node_txn.len() == 2 || node_txn.len() == 3);
4806 check_spends!(node_txn[0], commitment_txn[0]);
4807 assert_eq!(node_txn[0].input.len(), 1);
4808 assert_eq!(node_txn[0].output.len(), 1);
4810 if node_txn.len() > 2 {
4811 check_spends!(node_txn[1], commitment_txn[0]);
4812 assert_eq!(node_txn[1].input.len(), 1);
4813 assert_eq!(node_txn[1].output.len(), 1);
4814 assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4816 check_spends!(node_txn[2], commitment_txn[0]);
4817 assert_eq!(node_txn[2].input.len(), 1);
4818 assert_eq!(node_txn[2].output.len(), 1);
4819 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
4821 check_spends!(node_txn[1], commitment_txn[0]);
4822 assert_eq!(node_txn[1].input.len(), 1);
4823 assert_eq!(node_txn[1].output.len(), 1);
4824 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4827 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4828 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4829 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
4830 // (with value 900 sats) will be claimed in the below `claim_funds` call.
4831 if node_txn.len() > 2 {
4832 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4833 htlc_timeout_tx = if node_txn[2].output[0].value < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
4835 htlc_timeout_tx = if node_txn[0].output[0].value < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
4839 nodes[2].node.claim_funds(our_payment_preimage);
4840 expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
4842 mine_transaction(&nodes[2], &commitment_txn[0]);
4843 check_added_monitors!(nodes[2], 2);
4844 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4845 let events = nodes[2].node.get_and_clear_pending_msg_events();
4847 MessageSendEvent::UpdateHTLCs { .. } => {},
4848 _ => panic!("Unexpected event"),
4851 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4852 _ => panic!("Unexepected event"),
4854 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4855 assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
4856 check_spends!(htlc_success_txn[0], commitment_txn[0]);
4857 check_spends!(htlc_success_txn[1], commitment_txn[0]);
4858 assert_eq!(htlc_success_txn[0].input.len(), 1);
4859 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4860 assert_eq!(htlc_success_txn[1].input.len(), 1);
4861 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4862 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
4863 assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
4865 mine_transaction(&nodes[1], &htlc_timeout_tx);
4866 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4867 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 }]);
4868 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4869 assert!(htlc_updates.update_add_htlcs.is_empty());
4870 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4871 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
4872 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4873 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4874 check_added_monitors!(nodes[1], 1);
4876 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4877 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4879 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4881 expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
4883 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4884 mine_transaction(&nodes[1], &htlc_success_txn[1]);
4885 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
4886 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4887 assert!(updates.update_add_htlcs.is_empty());
4888 assert!(updates.update_fail_htlcs.is_empty());
4889 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4890 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
4891 assert!(updates.update_fail_malformed_htlcs.is_empty());
4892 check_added_monitors!(nodes[1], 1);
4894 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4895 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4896 expect_payment_sent(&nodes[0], our_payment_preimage, None, true);
4900 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4901 let chanmon_cfgs = create_chanmon_cfgs(2);
4902 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4903 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4904 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4906 // Create some initial channels
4907 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4909 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
4910 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4911 assert_eq!(local_txn.len(), 1);
4912 assert_eq!(local_txn[0].input.len(), 1);
4913 check_spends!(local_txn[0], chan_1.3);
4915 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4916 nodes[1].node.claim_funds(payment_preimage);
4917 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
4918 check_added_monitors!(nodes[1], 1);
4920 mine_transaction(&nodes[1], &local_txn[0]);
4921 check_added_monitors!(nodes[1], 1);
4922 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4923 let events = nodes[1].node.get_and_clear_pending_msg_events();
4925 MessageSendEvent::UpdateHTLCs { .. } => {},
4926 _ => panic!("Unexpected event"),
4929 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4930 _ => panic!("Unexepected event"),
4933 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4934 assert_eq!(node_txn.len(), 1);
4935 assert_eq!(node_txn[0].input.len(), 1);
4936 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4937 check_spends!(node_txn[0], local_txn[0]);
4941 mine_transaction(&nodes[1], &node_tx);
4942 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4944 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4945 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4946 assert_eq!(spend_txn.len(), 1);
4947 assert_eq!(spend_txn[0].input.len(), 1);
4948 check_spends!(spend_txn[0], node_tx);
4949 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4952 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4953 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4954 // unrevoked commitment transaction.
4955 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4956 // a remote RAA before they could be failed backwards (and combinations thereof).
4957 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4958 // use the same payment hashes.
4959 // Thus, we use a six-node network:
4964 // And test where C fails back to A/B when D announces its latest commitment transaction
4965 let chanmon_cfgs = create_chanmon_cfgs(6);
4966 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
4967 // When this test was written, the default base fee floated based on the HTLC count.
4968 // It is now fixed, so we simply set the fee to the expected value here.
4969 let mut config = test_default_channel_config();
4970 config.channel_config.forwarding_fee_base_msat = 196;
4971 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
4972 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4973 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
4975 let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2);
4976 let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4977 let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
4978 let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
4979 let chan_3_5 = create_announced_chan_between_nodes(&nodes, 3, 5);
4981 // Rebalance and check output sanity...
4982 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
4983 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
4984 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
4986 let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
4987 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().holder_dust_limit_satoshis;
4989 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
4991 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
4992 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
4994 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
4996 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
4998 let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5000 let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5001 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5003 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());
5005 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());
5008 let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5010 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5011 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
5014 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
5016 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5017 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());
5019 // Double-check that six of the new HTLC were added
5020 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5021 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5022 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5023 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5025 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5026 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5027 nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5028 nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5029 nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5030 nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5031 check_added_monitors!(nodes[4], 0);
5033 let failed_destinations = vec![
5034 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5035 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5036 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5037 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5039 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5040 check_added_monitors!(nodes[4], 1);
5042 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5043 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5044 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5045 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5046 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5047 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5049 // Fail 3rd below-dust and 7th above-dust HTLCs
5050 nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5051 nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5052 check_added_monitors!(nodes[5], 0);
5054 let failed_destinations_2 = vec![
5055 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5056 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5058 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5059 check_added_monitors!(nodes[5], 1);
5061 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5062 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5063 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5064 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5066 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5068 // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5069 let failed_destinations_3 = vec![
5070 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5071 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5072 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5073 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5074 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5075 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5077 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5078 check_added_monitors!(nodes[3], 1);
5079 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5080 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5081 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5082 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5083 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5084 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5085 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5086 if deliver_last_raa {
5087 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5089 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5092 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5093 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5094 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5095 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5097 // We now broadcast the latest commitment transaction, which *should* result in failures for
5098 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5099 // the non-broadcast above-dust HTLCs.
5101 // Alternatively, we may broadcast the previous commitment transaction, which should only
5102 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5103 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5105 if announce_latest {
5106 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5108 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5110 let events = nodes[2].node.get_and_clear_pending_events();
5111 let close_event = if deliver_last_raa {
5112 assert_eq!(events.len(), 2 + 6);
5113 events.last().clone().unwrap()
5115 assert_eq!(events.len(), 1);
5116 events.last().clone().unwrap()
5119 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5120 _ => panic!("Unexpected event"),
5123 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5124 check_closed_broadcast!(nodes[2], true);
5125 if deliver_last_raa {
5126 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5128 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();
5129 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5131 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5132 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5134 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5137 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5139 check_added_monitors!(nodes[2], 3);
5141 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5142 assert_eq!(cs_msgs.len(), 2);
5143 let mut a_done = false;
5144 for msg in cs_msgs {
5146 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5147 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5148 // should be failed-backwards here.
5149 let target = if *node_id == nodes[0].node.get_our_node_id() {
5150 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5151 for htlc in &updates.update_fail_htlcs {
5152 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 });
5154 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5159 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5160 for htlc in &updates.update_fail_htlcs {
5161 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5163 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5164 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5167 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5168 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5169 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5170 if announce_latest {
5171 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5172 if *node_id == nodes[0].node.get_our_node_id() {
5173 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5176 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5178 _ => panic!("Unexpected event"),
5182 let as_events = nodes[0].node.get_and_clear_pending_events();
5183 assert_eq!(as_events.len(), if announce_latest { 10 } else { 6 });
5184 let mut as_failds = HashSet::new();
5185 let mut as_updates = 0;
5186 for event in as_events.iter() {
5187 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5188 assert!(as_failds.insert(*payment_hash));
5189 if *payment_hash != payment_hash_2 {
5190 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5192 assert!(!payment_failed_permanently);
5194 if let PathFailure::OnPath { network_update: Some(_) } = failure {
5197 } else if let &Event::PaymentFailed { .. } = event {
5198 } else { panic!("Unexpected event"); }
5200 assert!(as_failds.contains(&payment_hash_1));
5201 assert!(as_failds.contains(&payment_hash_2));
5202 if announce_latest {
5203 assert!(as_failds.contains(&payment_hash_3));
5204 assert!(as_failds.contains(&payment_hash_5));
5206 assert!(as_failds.contains(&payment_hash_6));
5208 let bs_events = nodes[1].node.get_and_clear_pending_events();
5209 assert_eq!(bs_events.len(), if announce_latest { 8 } else { 6 });
5210 let mut bs_failds = HashSet::new();
5211 let mut bs_updates = 0;
5212 for event in bs_events.iter() {
5213 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5214 assert!(bs_failds.insert(*payment_hash));
5215 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5216 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5218 assert!(!payment_failed_permanently);
5220 if let PathFailure::OnPath { network_update: Some(_) } = failure {
5223 } else if let &Event::PaymentFailed { .. } = event {
5224 } else { panic!("Unexpected event"); }
5226 assert!(bs_failds.contains(&payment_hash_1));
5227 assert!(bs_failds.contains(&payment_hash_2));
5228 if announce_latest {
5229 assert!(bs_failds.contains(&payment_hash_4));
5231 assert!(bs_failds.contains(&payment_hash_5));
5233 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5234 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5235 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5236 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5237 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5238 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5242 fn test_fail_backwards_latest_remote_announce_a() {
5243 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5247 fn test_fail_backwards_latest_remote_announce_b() {
5248 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5252 fn test_fail_backwards_previous_remote_announce() {
5253 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5254 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5255 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5259 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5260 let chanmon_cfgs = create_chanmon_cfgs(2);
5261 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5262 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5263 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5265 // Create some initial channels
5266 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5268 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5269 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5270 assert_eq!(local_txn[0].input.len(), 1);
5271 check_spends!(local_txn[0], chan_1.3);
5273 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5274 mine_transaction(&nodes[0], &local_txn[0]);
5275 check_closed_broadcast!(nodes[0], true);
5276 check_added_monitors!(nodes[0], 1);
5277 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5278 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5280 let htlc_timeout = {
5281 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5282 assert_eq!(node_txn.len(), 1);
5283 assert_eq!(node_txn[0].input.len(), 1);
5284 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5285 check_spends!(node_txn[0], local_txn[0]);
5289 mine_transaction(&nodes[0], &htlc_timeout);
5290 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5291 expect_payment_failed!(nodes[0], our_payment_hash, false);
5293 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5294 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5295 assert_eq!(spend_txn.len(), 3);
5296 check_spends!(spend_txn[0], local_txn[0]);
5297 assert_eq!(spend_txn[1].input.len(), 1);
5298 check_spends!(spend_txn[1], htlc_timeout);
5299 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5300 assert_eq!(spend_txn[2].input.len(), 2);
5301 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5302 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5303 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5307 fn test_key_derivation_params() {
5308 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5309 // manager rotation to test that `channel_keys_id` returned in
5310 // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5311 // then derive a `delayed_payment_key`.
5313 let chanmon_cfgs = create_chanmon_cfgs(3);
5315 // We manually create the node configuration to backup the seed.
5316 let seed = [42; 32];
5317 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5318 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);
5319 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[0].logger));
5320 let scorer = Mutex::new(test_utils::TestScorer::new());
5321 let router = test_utils::TestRouter::new(network_graph.clone(), &scorer);
5322 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)) };
5323 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5324 node_cfgs.remove(0);
5325 node_cfgs.insert(0, node);
5327 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5328 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5330 // Create some initial channels
5331 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5333 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2);
5334 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5335 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5337 // Ensure all nodes are at the same height
5338 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5339 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5340 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5341 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5343 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5344 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5345 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5346 assert_eq!(local_txn_1[0].input.len(), 1);
5347 check_spends!(local_txn_1[0], chan_1.3);
5349 // We check funding pubkey are unique
5350 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]));
5351 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]));
5352 if from_0_funding_key_0 == from_1_funding_key_0
5353 || from_0_funding_key_0 == from_1_funding_key_1
5354 || from_0_funding_key_1 == from_1_funding_key_0
5355 || from_0_funding_key_1 == from_1_funding_key_1 {
5356 panic!("Funding pubkeys aren't unique");
5359 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5360 mine_transaction(&nodes[0], &local_txn_1[0]);
5361 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5362 check_closed_broadcast!(nodes[0], true);
5363 check_added_monitors!(nodes[0], 1);
5364 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5366 let htlc_timeout = {
5367 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5368 assert_eq!(node_txn.len(), 1);
5369 assert_eq!(node_txn[0].input.len(), 1);
5370 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5371 check_spends!(node_txn[0], local_txn_1[0]);
5375 mine_transaction(&nodes[0], &htlc_timeout);
5376 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5377 expect_payment_failed!(nodes[0], our_payment_hash, false);
5379 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5380 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5381 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5382 assert_eq!(spend_txn.len(), 3);
5383 check_spends!(spend_txn[0], local_txn_1[0]);
5384 assert_eq!(spend_txn[1].input.len(), 1);
5385 check_spends!(spend_txn[1], htlc_timeout);
5386 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5387 assert_eq!(spend_txn[2].input.len(), 2);
5388 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5389 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5390 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5394 fn test_static_output_closing_tx() {
5395 let chanmon_cfgs = create_chanmon_cfgs(2);
5396 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5397 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5398 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5400 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5402 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5403 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5405 mine_transaction(&nodes[0], &closing_tx);
5406 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5407 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5409 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5410 assert_eq!(spend_txn.len(), 1);
5411 check_spends!(spend_txn[0], closing_tx);
5413 mine_transaction(&nodes[1], &closing_tx);
5414 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5415 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5417 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5418 assert_eq!(spend_txn.len(), 1);
5419 check_spends!(spend_txn[0], closing_tx);
5422 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5423 let chanmon_cfgs = create_chanmon_cfgs(2);
5424 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5425 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5426 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5427 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5429 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5431 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5432 // present in B's local commitment transaction, but none of A's commitment transactions.
5433 nodes[1].node.claim_funds(payment_preimage);
5434 check_added_monitors!(nodes[1], 1);
5435 expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5437 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5438 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5439 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5441 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5442 check_added_monitors!(nodes[0], 1);
5443 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5444 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5445 check_added_monitors!(nodes[1], 1);
5447 let starting_block = nodes[1].best_block_info();
5448 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5449 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5450 connect_block(&nodes[1], &block);
5451 block.header.prev_blockhash = block.block_hash();
5453 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5454 check_closed_broadcast!(nodes[1], true);
5455 check_added_monitors!(nodes[1], 1);
5456 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5459 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5460 let chanmon_cfgs = create_chanmon_cfgs(2);
5461 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5462 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5463 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5464 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5466 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5467 nodes[0].node.send_payment_with_route(&route, payment_hash,
5468 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
5469 check_added_monitors!(nodes[0], 1);
5471 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5473 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5474 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5475 // to "time out" the HTLC.
5477 let starting_block = nodes[1].best_block_info();
5478 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5480 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5481 connect_block(&nodes[0], &block);
5482 block.header.prev_blockhash = block.block_hash();
5484 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5485 check_closed_broadcast!(nodes[0], true);
5486 check_added_monitors!(nodes[0], 1);
5487 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5490 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5491 let chanmon_cfgs = create_chanmon_cfgs(3);
5492 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5493 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5494 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5495 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5497 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5498 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5499 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5500 // actually revoked.
5501 let htlc_value = if use_dust { 50000 } else { 3000000 };
5502 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5503 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5504 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5505 check_added_monitors!(nodes[1], 1);
5507 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5508 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5509 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5510 check_added_monitors!(nodes[0], 1);
5511 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5512 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5513 check_added_monitors!(nodes[1], 1);
5514 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5515 check_added_monitors!(nodes[1], 1);
5516 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5518 if check_revoke_no_close {
5519 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5520 check_added_monitors!(nodes[0], 1);
5523 let starting_block = nodes[1].best_block_info();
5524 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5525 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5526 connect_block(&nodes[0], &block);
5527 block.header.prev_blockhash = block.block_hash();
5529 if !check_revoke_no_close {
5530 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5531 check_closed_broadcast!(nodes[0], true);
5532 check_added_monitors!(nodes[0], 1);
5533 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5535 expect_payment_failed!(nodes[0], our_payment_hash, true);
5539 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5540 // There are only a few cases to test here:
5541 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5542 // broadcastable commitment transactions result in channel closure,
5543 // * its included in an unrevoked-but-previous remote commitment transaction,
5544 // * its included in the latest remote or local commitment transactions.
5545 // We test each of the three possible commitment transactions individually and use both dust and
5547 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5548 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5549 // tested for at least one of the cases in other tests.
5551 fn htlc_claim_single_commitment_only_a() {
5552 do_htlc_claim_local_commitment_only(true);
5553 do_htlc_claim_local_commitment_only(false);
5555 do_htlc_claim_current_remote_commitment_only(true);
5556 do_htlc_claim_current_remote_commitment_only(false);
5560 fn htlc_claim_single_commitment_only_b() {
5561 do_htlc_claim_previous_remote_commitment_only(true, false);
5562 do_htlc_claim_previous_remote_commitment_only(false, false);
5563 do_htlc_claim_previous_remote_commitment_only(true, true);
5564 do_htlc_claim_previous_remote_commitment_only(false, true);
5569 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5570 let chanmon_cfgs = create_chanmon_cfgs(2);
5571 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5572 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5573 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5574 // Force duplicate randomness for every get-random call
5575 for node in nodes.iter() {
5576 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5579 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5580 let channel_value_satoshis=10000;
5581 let push_msat=10001;
5582 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5583 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5584 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5585 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5587 // Create a second channel with the same random values. This used to panic due to a colliding
5588 // channel_id, but now panics due to a colliding outbound SCID alias.
5589 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5593 fn bolt2_open_channel_sending_node_checks_part2() {
5594 let chanmon_cfgs = create_chanmon_cfgs(2);
5595 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5596 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5597 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5599 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5600 let channel_value_satoshis=2^24;
5601 let push_msat=10001;
5602 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5604 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5605 let channel_value_satoshis=10000;
5606 // Test when push_msat is equal to 1000 * funding_satoshis.
5607 let push_msat=1000*channel_value_satoshis+1;
5608 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5610 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5611 let channel_value_satoshis=10000;
5612 let push_msat=10001;
5613 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
5614 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5615 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5617 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5618 // 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
5619 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5621 // 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.
5622 assert!(BREAKDOWN_TIMEOUT>0);
5623 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5625 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5626 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5627 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5629 // 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.
5630 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5631 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5632 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5633 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5634 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5638 fn bolt2_open_channel_sane_dust_limit() {
5639 let chanmon_cfgs = create_chanmon_cfgs(2);
5640 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5641 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5642 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5644 let channel_value_satoshis=1000000;
5645 let push_msat=10001;
5646 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5647 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5648 node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5649 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5651 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5652 let events = nodes[1].node.get_and_clear_pending_msg_events();
5653 let err_msg = match events[0] {
5654 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5657 _ => panic!("Unexpected event"),
5659 assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5662 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5663 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5664 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5665 // is no longer affordable once it's freed.
5667 fn test_fail_holding_cell_htlc_upon_free() {
5668 let chanmon_cfgs = create_chanmon_cfgs(2);
5669 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5670 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5671 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5672 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5674 // First nodes[0] generates an update_fee, setting the channel's
5675 // pending_update_fee.
5677 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5678 *feerate_lock += 20;
5680 nodes[0].node.timer_tick_occurred();
5681 check_added_monitors!(nodes[0], 1);
5683 let events = nodes[0].node.get_and_clear_pending_msg_events();
5684 assert_eq!(events.len(), 1);
5685 let (update_msg, commitment_signed) = match events[0] {
5686 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5687 (update_fee.as_ref(), commitment_signed)
5689 _ => panic!("Unexpected event"),
5692 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5694 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5695 let channel_reserve = chan_stat.channel_reserve_msat;
5696 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5697 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5699 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5700 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
5701 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5703 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5704 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5705 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5706 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5707 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5709 // Flush the pending fee update.
5710 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5711 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5712 check_added_monitors!(nodes[1], 1);
5713 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5714 check_added_monitors!(nodes[0], 1);
5716 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5717 // HTLC, but now that the fee has been raised the payment will now fail, causing
5718 // us to surface its failure to the user.
5719 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5720 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5721 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Freeing holding cell with 1 HTLC updates in channel {}", hex::encode(chan.2)), 1);
5722 let failure_log = format!("Failed to send HTLC with payment_hash {} due to Cannot send value that would put our balance under counterparty-announced channel reserve value ({}) in channel {}",
5723 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5724 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5726 // Check that the payment failed to be sent out.
5727 let events = nodes[0].node.get_and_clear_pending_events();
5728 assert_eq!(events.len(), 2);
5730 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5731 assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5732 assert_eq!(our_payment_hash.clone(), *payment_hash);
5733 assert_eq!(*payment_failed_permanently, false);
5734 assert_eq!(*short_channel_id, Some(route.paths[0].hops[0].short_channel_id));
5736 _ => panic!("Unexpected event"),
5739 &Event::PaymentFailed { ref payment_hash, .. } => {
5740 assert_eq!(our_payment_hash.clone(), *payment_hash);
5742 _ => panic!("Unexpected event"),
5746 // Test that if multiple HTLCs are released from the holding cell and one is
5747 // valid but the other is no longer valid upon release, the valid HTLC can be
5748 // successfully completed while the other one fails as expected.
5750 fn test_free_and_fail_holding_cell_htlcs() {
5751 let chanmon_cfgs = create_chanmon_cfgs(2);
5752 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5753 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5754 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5755 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5757 // First nodes[0] generates an update_fee, setting the channel's
5758 // pending_update_fee.
5760 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5761 *feerate_lock += 200;
5763 nodes[0].node.timer_tick_occurred();
5764 check_added_monitors!(nodes[0], 1);
5766 let events = nodes[0].node.get_and_clear_pending_msg_events();
5767 assert_eq!(events.len(), 1);
5768 let (update_msg, commitment_signed) = match events[0] {
5769 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5770 (update_fee.as_ref(), commitment_signed)
5772 _ => panic!("Unexpected event"),
5775 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5777 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5778 let channel_reserve = chan_stat.channel_reserve_msat;
5779 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5780 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5782 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5784 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
5785 let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5786 let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5788 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5789 nodes[0].node.send_payment_with_route(&route_1, payment_hash_1,
5790 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
5791 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5792 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
5793 let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
5794 nodes[0].node.send_payment_with_route(&route_2, payment_hash_2,
5795 RecipientOnionFields::secret_only(payment_secret_2), payment_id_2).unwrap();
5796 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5797 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
5799 // Flush the pending fee update.
5800 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5801 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5802 check_added_monitors!(nodes[1], 1);
5803 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
5804 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5805 check_added_monitors!(nodes[0], 2);
5807 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
5808 // but now that the fee has been raised the second payment will now fail, causing us
5809 // to surface its failure to the user. The first payment should succeed.
5810 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5811 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5812 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Freeing holding cell with 2 HTLC updates in channel {}", hex::encode(chan.2)), 1);
5813 let failure_log = format!("Failed to send HTLC with payment_hash {} due to Cannot send value that would put our balance under counterparty-announced channel reserve value ({}) in channel {}",
5814 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5815 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5817 // Check that the second payment failed to be sent out.
5818 let events = nodes[0].node.get_and_clear_pending_events();
5819 assert_eq!(events.len(), 2);
5821 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5822 assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
5823 assert_eq!(payment_hash_2.clone(), *payment_hash);
5824 assert_eq!(*payment_failed_permanently, false);
5825 assert_eq!(*short_channel_id, Some(route_2.paths[0].hops[0].short_channel_id));
5827 _ => panic!("Unexpected event"),
5830 &Event::PaymentFailed { ref payment_hash, .. } => {
5831 assert_eq!(payment_hash_2.clone(), *payment_hash);
5833 _ => panic!("Unexpected event"),
5836 // Complete the first payment and the RAA from the fee update.
5837 let (payment_event, send_raa_event) = {
5838 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
5839 assert_eq!(msgs.len(), 2);
5840 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
5842 let raa = match send_raa_event {
5843 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
5844 _ => panic!("Unexpected event"),
5846 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5847 check_added_monitors!(nodes[1], 1);
5848 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5849 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5850 let events = nodes[1].node.get_and_clear_pending_events();
5851 assert_eq!(events.len(), 1);
5853 Event::PendingHTLCsForwardable { .. } => {},
5854 _ => panic!("Unexpected event"),
5856 nodes[1].node.process_pending_htlc_forwards();
5857 let events = nodes[1].node.get_and_clear_pending_events();
5858 assert_eq!(events.len(), 1);
5860 Event::PaymentClaimable { .. } => {},
5861 _ => panic!("Unexpected event"),
5863 nodes[1].node.claim_funds(payment_preimage_1);
5864 check_added_monitors!(nodes[1], 1);
5865 expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
5867 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5868 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
5869 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
5870 expect_payment_sent!(nodes[0], payment_preimage_1);
5873 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
5874 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
5875 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
5878 fn test_fail_holding_cell_htlc_upon_free_multihop() {
5879 let chanmon_cfgs = create_chanmon_cfgs(3);
5880 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5881 // When this test was written, the default base fee floated based on the HTLC count.
5882 // It is now fixed, so we simply set the fee to the expected value here.
5883 let mut config = test_default_channel_config();
5884 config.channel_config.forwarding_fee_base_msat = 196;
5885 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5886 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5887 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5888 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
5890 // First nodes[1] generates an update_fee, setting the channel's
5891 // pending_update_fee.
5893 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
5894 *feerate_lock += 20;
5896 nodes[1].node.timer_tick_occurred();
5897 check_added_monitors!(nodes[1], 1);
5899 let events = nodes[1].node.get_and_clear_pending_msg_events();
5900 assert_eq!(events.len(), 1);
5901 let (update_msg, commitment_signed) = match events[0] {
5902 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5903 (update_fee.as_ref(), commitment_signed)
5905 _ => panic!("Unexpected event"),
5908 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
5910 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan_0_1.2);
5911 let channel_reserve = chan_stat.channel_reserve_msat;
5912 let feerate = get_feerate!(nodes[0], nodes[1], chan_0_1.2);
5913 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_0_1.2);
5915 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5917 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
5918 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
5919 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
5920 let payment_event = {
5921 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5922 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5923 check_added_monitors!(nodes[0], 1);
5925 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5926 assert_eq!(events.len(), 1);
5928 SendEvent::from_event(events.remove(0))
5930 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5931 check_added_monitors!(nodes[1], 0);
5932 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5933 expect_pending_htlcs_forwardable!(nodes[1]);
5935 chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
5936 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5938 // Flush the pending fee update.
5939 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
5940 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5941 check_added_monitors!(nodes[2], 1);
5942 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
5943 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
5944 check_added_monitors!(nodes[1], 2);
5946 // A final RAA message is generated to finalize the fee update.
5947 let events = nodes[1].node.get_and_clear_pending_msg_events();
5948 assert_eq!(events.len(), 1);
5950 let raa_msg = match &events[0] {
5951 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
5954 _ => panic!("Unexpected event"),
5957 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
5958 check_added_monitors!(nodes[2], 1);
5959 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
5961 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
5962 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
5963 assert_eq!(process_htlc_forwards_event.len(), 2);
5964 match &process_htlc_forwards_event[0] {
5965 &Event::PendingHTLCsForwardable { .. } => {},
5966 _ => panic!("Unexpected event"),
5969 // In response, we call ChannelManager's process_pending_htlc_forwards
5970 nodes[1].node.process_pending_htlc_forwards();
5971 check_added_monitors!(nodes[1], 1);
5973 // This causes the HTLC to be failed backwards.
5974 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
5975 assert_eq!(fail_event.len(), 1);
5976 let (fail_msg, commitment_signed) = match &fail_event[0] {
5977 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
5978 assert_eq!(updates.update_add_htlcs.len(), 0);
5979 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
5980 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
5981 assert_eq!(updates.update_fail_htlcs.len(), 1);
5982 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
5984 _ => panic!("Unexpected event"),
5987 // Pass the failure messages back to nodes[0].
5988 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
5989 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5991 // Complete the HTLC failure+removal process.
5992 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5993 check_added_monitors!(nodes[0], 1);
5994 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5995 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
5996 check_added_monitors!(nodes[1], 2);
5997 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
5998 assert_eq!(final_raa_event.len(), 1);
5999 let raa = match &final_raa_event[0] {
6000 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6001 _ => panic!("Unexpected event"),
6003 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6004 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6005 check_added_monitors!(nodes[0], 1);
6008 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6009 // 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.
6010 //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.
6013 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6014 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6015 let chanmon_cfgs = create_chanmon_cfgs(2);
6016 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6017 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6018 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6019 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6021 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6022 route.paths[0].hops[0].fee_msat = 100;
6024 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6025 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6026 ), true, APIError::ChannelUnavailable { ref err },
6027 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6028 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6029 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send less than their minimum HTLC value", 1);
6033 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6034 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6035 let chanmon_cfgs = create_chanmon_cfgs(2);
6036 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6037 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6038 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6039 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6041 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6042 route.paths[0].hops[0].fee_msat = 0;
6043 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6044 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)),
6045 true, APIError::ChannelUnavailable { ref err },
6046 assert_eq!(err, "Cannot send 0-msat HTLC"));
6048 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6049 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send 0-msat HTLC", 1);
6053 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6054 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6055 let chanmon_cfgs = create_chanmon_cfgs(2);
6056 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6057 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6058 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6059 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6061 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6062 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6063 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6064 check_added_monitors!(nodes[0], 1);
6065 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6066 updates.update_add_htlcs[0].amount_msat = 0;
6068 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6069 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6070 check_closed_broadcast!(nodes[1], true).unwrap();
6071 check_added_monitors!(nodes[1], 1);
6072 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6076 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6077 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6078 //It is enforced when constructing a route.
6079 let chanmon_cfgs = create_chanmon_cfgs(2);
6080 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6081 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6082 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6083 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6085 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6086 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
6087 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);
6088 route.paths[0].hops.last_mut().unwrap().cltv_expiry_delta = 500000001;
6089 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6090 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6091 ), true, APIError::InvalidRoute { ref err },
6092 assert_eq!(err, &"Channel CLTV overflowed?"));
6096 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6097 //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.
6098 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6099 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6100 let chanmon_cfgs = create_chanmon_cfgs(2);
6101 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6102 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6103 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6104 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6105 let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6106 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6108 for i in 0..max_accepted_htlcs {
6109 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6110 let payment_event = {
6111 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6112 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6113 check_added_monitors!(nodes[0], 1);
6115 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6116 assert_eq!(events.len(), 1);
6117 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6118 assert_eq!(htlcs[0].htlc_id, i);
6122 SendEvent::from_event(events.remove(0))
6124 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6125 check_added_monitors!(nodes[1], 0);
6126 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6128 expect_pending_htlcs_forwardable!(nodes[1]);
6129 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6131 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6132 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6133 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6134 ), true, APIError::ChannelUnavailable { ref err },
6135 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6137 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6138 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot push more than their max accepted HTLCs", 1);
6142 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6143 //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.
6144 let chanmon_cfgs = create_chanmon_cfgs(2);
6145 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6146 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6147 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6148 let channel_value = 100000;
6149 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6150 let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6152 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6154 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6155 // Manually create a route over our max in flight (which our router normally automatically
6157 route.paths[0].hops[0].fee_msat = max_in_flight + 1;
6158 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6159 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6160 ), true, APIError::ChannelUnavailable { ref err },
6161 assert!(regex::Regex::new(r"Cannot send value that would put us over the max HTLC value in flight our peer will accept \(\d+\)").unwrap().is_match(err)));
6163 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6164 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put us over the max HTLC value in flight our peer will accept", 1);
6166 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6169 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6171 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6172 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6173 let chanmon_cfgs = create_chanmon_cfgs(2);
6174 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6175 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6176 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6177 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6178 let htlc_minimum_msat: u64;
6180 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6181 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6182 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6183 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6186 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6187 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6188 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6189 check_added_monitors!(nodes[0], 1);
6190 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6191 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6192 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6193 assert!(nodes[1].node.list_channels().is_empty());
6194 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6195 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()));
6196 check_added_monitors!(nodes[1], 1);
6197 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6201 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6202 //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
6203 let chanmon_cfgs = create_chanmon_cfgs(2);
6204 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6205 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6206 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6207 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6209 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6210 let channel_reserve = chan_stat.channel_reserve_msat;
6211 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6212 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
6213 // The 2* and +1 are for the fee spike reserve.
6214 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6216 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6217 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6218 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6219 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6220 check_added_monitors!(nodes[0], 1);
6221 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6223 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6224 // at this time channel-initiatee receivers are not required to enforce that senders
6225 // respect the fee_spike_reserve.
6226 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6227 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6229 assert!(nodes[1].node.list_channels().is_empty());
6230 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6231 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6232 check_added_monitors!(nodes[1], 1);
6233 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6237 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6238 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6239 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6240 let chanmon_cfgs = create_chanmon_cfgs(2);
6241 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6242 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6243 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6244 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6246 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6247 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6248 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6249 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6250 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
6251 &route.paths[0], 3999999, RecipientOnionFields::secret_only(our_payment_secret), cur_height, &None).unwrap();
6252 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
6254 let mut msg = msgs::UpdateAddHTLC {
6258 payment_hash: our_payment_hash,
6259 cltv_expiry: htlc_cltv,
6260 onion_routing_packet: onion_packet.clone(),
6264 msg.htlc_id = i as u64;
6265 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6267 msg.htlc_id = (50) as u64;
6268 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6270 assert!(nodes[1].node.list_channels().is_empty());
6271 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6272 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6273 check_added_monitors!(nodes[1], 1);
6274 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6278 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6279 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6280 let chanmon_cfgs = create_chanmon_cfgs(2);
6281 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6282 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6283 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6284 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6286 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6287 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6288 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6289 check_added_monitors!(nodes[0], 1);
6290 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6291 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;
6292 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6294 assert!(nodes[1].node.list_channels().is_empty());
6295 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6296 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6297 check_added_monitors!(nodes[1], 1);
6298 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6302 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6303 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6304 let chanmon_cfgs = create_chanmon_cfgs(2);
6305 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6306 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6307 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6309 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6310 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6311 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6312 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6313 check_added_monitors!(nodes[0], 1);
6314 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6315 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6316 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6318 assert!(nodes[1].node.list_channels().is_empty());
6319 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6320 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6321 check_added_monitors!(nodes[1], 1);
6322 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6326 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6327 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6328 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6329 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6330 let chanmon_cfgs = create_chanmon_cfgs(2);
6331 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6332 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6333 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6335 create_announced_chan_between_nodes(&nodes, 0, 1);
6336 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6337 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6338 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6339 check_added_monitors!(nodes[0], 1);
6340 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6341 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6343 //Disconnect and Reconnect
6344 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
6345 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
6346 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: nodes[1].node.init_features(), remote_network_address: None }, true).unwrap();
6347 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6348 assert_eq!(reestablish_1.len(), 1);
6349 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: nodes[0].node.init_features(), remote_network_address: None }, false).unwrap();
6350 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6351 assert_eq!(reestablish_2.len(), 1);
6352 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6353 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6354 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6355 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6358 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6359 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6360 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6361 check_added_monitors!(nodes[1], 1);
6362 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6364 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6366 assert!(nodes[1].node.list_channels().is_empty());
6367 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6368 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6369 check_added_monitors!(nodes[1], 1);
6370 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6374 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6375 //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.
6377 let chanmon_cfgs = create_chanmon_cfgs(2);
6378 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6379 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6380 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6381 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6382 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6383 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6384 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6386 check_added_monitors!(nodes[0], 1);
6387 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6388 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6390 let update_msg = msgs::UpdateFulfillHTLC{
6393 payment_preimage: our_payment_preimage,
6396 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6398 assert!(nodes[0].node.list_channels().is_empty());
6399 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6400 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()));
6401 check_added_monitors!(nodes[0], 1);
6402 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6406 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6407 //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.
6409 let chanmon_cfgs = create_chanmon_cfgs(2);
6410 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6411 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6412 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6413 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6415 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6416 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6417 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6418 check_added_monitors!(nodes[0], 1);
6419 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6420 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6422 let update_msg = msgs::UpdateFailHTLC{
6425 reason: msgs::OnionErrorPacket { data: Vec::new()},
6428 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6430 assert!(nodes[0].node.list_channels().is_empty());
6431 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6432 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()));
6433 check_added_monitors!(nodes[0], 1);
6434 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6438 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6439 //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.
6441 let chanmon_cfgs = create_chanmon_cfgs(2);
6442 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6443 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6444 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6445 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6447 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6448 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6449 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6450 check_added_monitors!(nodes[0], 1);
6451 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6452 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6453 let update_msg = msgs::UpdateFailMalformedHTLC{
6456 sha256_of_onion: [1; 32],
6457 failure_code: 0x8000,
6460 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6462 assert!(nodes[0].node.list_channels().is_empty());
6463 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6464 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()));
6465 check_added_monitors!(nodes[0], 1);
6466 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6470 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6471 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6473 let chanmon_cfgs = create_chanmon_cfgs(2);
6474 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6475 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6476 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6477 create_announced_chan_between_nodes(&nodes, 0, 1);
6479 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6481 nodes[1].node.claim_funds(our_payment_preimage);
6482 check_added_monitors!(nodes[1], 1);
6483 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6485 let events = nodes[1].node.get_and_clear_pending_msg_events();
6486 assert_eq!(events.len(), 1);
6487 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6489 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, .. } } => {
6490 assert!(update_add_htlcs.is_empty());
6491 assert_eq!(update_fulfill_htlcs.len(), 1);
6492 assert!(update_fail_htlcs.is_empty());
6493 assert!(update_fail_malformed_htlcs.is_empty());
6494 assert!(update_fee.is_none());
6495 update_fulfill_htlcs[0].clone()
6497 _ => panic!("Unexpected event"),
6501 update_fulfill_msg.htlc_id = 1;
6503 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6505 assert!(nodes[0].node.list_channels().is_empty());
6506 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6507 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6508 check_added_monitors!(nodes[0], 1);
6509 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6513 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6514 //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.
6516 let chanmon_cfgs = create_chanmon_cfgs(2);
6517 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6518 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6519 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6520 create_announced_chan_between_nodes(&nodes, 0, 1);
6522 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6524 nodes[1].node.claim_funds(our_payment_preimage);
6525 check_added_monitors!(nodes[1], 1);
6526 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6528 let events = nodes[1].node.get_and_clear_pending_msg_events();
6529 assert_eq!(events.len(), 1);
6530 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6532 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, .. } } => {
6533 assert!(update_add_htlcs.is_empty());
6534 assert_eq!(update_fulfill_htlcs.len(), 1);
6535 assert!(update_fail_htlcs.is_empty());
6536 assert!(update_fail_malformed_htlcs.is_empty());
6537 assert!(update_fee.is_none());
6538 update_fulfill_htlcs[0].clone()
6540 _ => panic!("Unexpected event"),
6544 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6546 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6548 assert!(nodes[0].node.list_channels().is_empty());
6549 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6550 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6551 check_added_monitors!(nodes[0], 1);
6552 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6556 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6557 //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.
6559 let chanmon_cfgs = create_chanmon_cfgs(2);
6560 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6561 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6562 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6563 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6565 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6566 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6567 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6568 check_added_monitors!(nodes[0], 1);
6570 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6571 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6573 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6574 check_added_monitors!(nodes[1], 0);
6575 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6577 let events = nodes[1].node.get_and_clear_pending_msg_events();
6579 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6581 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, .. } } => {
6582 assert!(update_add_htlcs.is_empty());
6583 assert!(update_fulfill_htlcs.is_empty());
6584 assert!(update_fail_htlcs.is_empty());
6585 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6586 assert!(update_fee.is_none());
6587 update_fail_malformed_htlcs[0].clone()
6589 _ => panic!("Unexpected event"),
6592 update_msg.failure_code &= !0x8000;
6593 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6595 assert!(nodes[0].node.list_channels().is_empty());
6596 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6597 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6598 check_added_monitors!(nodes[0], 1);
6599 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6603 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6604 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6605 // * 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.
6607 let chanmon_cfgs = create_chanmon_cfgs(3);
6608 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6609 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6610 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6611 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6612 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000);
6614 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6617 let mut payment_event = {
6618 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6619 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6620 check_added_monitors!(nodes[0], 1);
6621 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6622 assert_eq!(events.len(), 1);
6623 SendEvent::from_event(events.remove(0))
6625 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6626 check_added_monitors!(nodes[1], 0);
6627 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6628 expect_pending_htlcs_forwardable!(nodes[1]);
6629 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6630 assert_eq!(events_2.len(), 1);
6631 check_added_monitors!(nodes[1], 1);
6632 payment_event = SendEvent::from_event(events_2.remove(0));
6633 assert_eq!(payment_event.msgs.len(), 1);
6636 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6637 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6638 check_added_monitors!(nodes[2], 0);
6639 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6641 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6642 assert_eq!(events_3.len(), 1);
6643 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6645 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 } } => {
6646 assert!(update_add_htlcs.is_empty());
6647 assert!(update_fulfill_htlcs.is_empty());
6648 assert!(update_fail_htlcs.is_empty());
6649 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6650 assert!(update_fee.is_none());
6651 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6653 _ => panic!("Unexpected event"),
6657 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6659 check_added_monitors!(nodes[1], 0);
6660 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6661 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 }]);
6662 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6663 assert_eq!(events_4.len(), 1);
6665 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6667 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, .. } } => {
6668 assert!(update_add_htlcs.is_empty());
6669 assert!(update_fulfill_htlcs.is_empty());
6670 assert_eq!(update_fail_htlcs.len(), 1);
6671 assert!(update_fail_malformed_htlcs.is_empty());
6672 assert!(update_fee.is_none());
6674 _ => panic!("Unexpected event"),
6677 check_added_monitors!(nodes[1], 1);
6681 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6682 let chanmon_cfgs = create_chanmon_cfgs(3);
6683 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6684 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6685 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6686 create_announced_chan_between_nodes(&nodes, 0, 1);
6687 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6689 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6692 let mut payment_event = {
6693 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6694 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6695 check_added_monitors!(nodes[0], 1);
6696 SendEvent::from_node(&nodes[0])
6699 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6700 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6701 expect_pending_htlcs_forwardable!(nodes[1]);
6702 check_added_monitors!(nodes[1], 1);
6703 payment_event = SendEvent::from_node(&nodes[1]);
6704 assert_eq!(payment_event.msgs.len(), 1);
6707 payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6708 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6709 check_added_monitors!(nodes[2], 0);
6710 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6712 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6713 assert_eq!(events_3.len(), 1);
6715 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6716 let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6717 // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6718 update_msg.failure_code |= 0x2000;
6720 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6721 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6723 _ => panic!("Unexpected event"),
6726 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6727 vec![HTLCDestination::NextHopChannel {
6728 node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6729 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6730 assert_eq!(events_4.len(), 1);
6731 check_added_monitors!(nodes[1], 1);
6734 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6735 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6736 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6738 _ => panic!("Unexpected event"),
6741 let events_5 = nodes[0].node.get_and_clear_pending_events();
6742 assert_eq!(events_5.len(), 2);
6744 // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6745 // the node originating the error to its next hop.
6747 Event::PaymentPathFailed { error_code, failure: PathFailure::OnPath { network_update: Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }) }, ..
6749 assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6750 assert!(is_permanent);
6751 assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
6753 _ => panic!("Unexpected event"),
6756 Event::PaymentFailed { payment_hash, .. } => {
6757 assert_eq!(payment_hash, our_payment_hash);
6759 _ => panic!("Unexpected event"),
6762 // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
6765 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6766 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6767 // 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
6768 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6770 let mut chanmon_cfgs = create_chanmon_cfgs(2);
6771 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6772 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6773 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6774 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6775 let chan =create_announced_chan_between_nodes(&nodes, 0, 1);
6777 let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6778 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6780 // We route 2 dust-HTLCs between A and B
6781 let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6782 let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6783 route_payment(&nodes[0], &[&nodes[1]], 1000000);
6785 // Cache one local commitment tx as previous
6786 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6788 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6789 nodes[1].node.fail_htlc_backwards(&payment_hash_2);
6790 check_added_monitors!(nodes[1], 0);
6791 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
6792 check_added_monitors!(nodes[1], 1);
6794 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6795 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6796 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6797 check_added_monitors!(nodes[0], 1);
6799 // Cache one local commitment tx as lastest
6800 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6802 let events = nodes[0].node.get_and_clear_pending_msg_events();
6804 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6805 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6807 _ => panic!("Unexpected event"),
6810 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6811 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6813 _ => panic!("Unexpected event"),
6816 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6817 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6818 if announce_latest {
6819 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6821 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6824 check_closed_broadcast!(nodes[0], true);
6825 check_added_monitors!(nodes[0], 1);
6826 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6828 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6829 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6830 let events = nodes[0].node.get_and_clear_pending_events();
6831 // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
6832 assert_eq!(events.len(), 4);
6833 let mut first_failed = false;
6834 for event in events {
6836 Event::PaymentPathFailed { payment_hash, .. } => {
6837 if payment_hash == payment_hash_1 {
6838 assert!(!first_failed);
6839 first_failed = true;
6841 assert_eq!(payment_hash, payment_hash_2);
6844 Event::PaymentFailed { .. } => {}
6845 _ => panic!("Unexpected event"),
6851 fn test_failure_delay_dust_htlc_local_commitment() {
6852 do_test_failure_delay_dust_htlc_local_commitment(true);
6853 do_test_failure_delay_dust_htlc_local_commitment(false);
6856 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6857 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6858 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6859 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6860 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6861 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6862 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6864 let chanmon_cfgs = create_chanmon_cfgs(3);
6865 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6866 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6867 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6868 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6870 let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6871 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6873 let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6874 let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6876 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6877 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6879 // We revoked bs_commitment_tx
6881 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6882 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
6885 let mut timeout_tx = Vec::new();
6887 // We fail dust-HTLC 1 by broadcast of local commitment tx
6888 mine_transaction(&nodes[0], &as_commitment_tx[0]);
6889 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6890 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6891 expect_payment_failed!(nodes[0], dust_hash, false);
6893 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
6894 check_closed_broadcast!(nodes[0], true);
6895 check_added_monitors!(nodes[0], 1);
6896 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6897 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6898 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6899 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
6900 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6901 mine_transaction(&nodes[0], &timeout_tx[0]);
6902 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6903 expect_payment_failed!(nodes[0], non_dust_hash, false);
6905 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
6906 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
6907 check_closed_broadcast!(nodes[0], true);
6908 check_added_monitors!(nodes[0], 1);
6909 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6910 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6912 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
6913 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
6914 .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
6915 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
6916 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
6917 // dust HTLC should have been failed.
6918 expect_payment_failed!(nodes[0], dust_hash, false);
6921 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6923 assert_eq!(timeout_tx[0].lock_time.0, 11);
6925 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
6926 mine_transaction(&nodes[0], &timeout_tx[0]);
6927 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6928 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6929 expect_payment_failed!(nodes[0], non_dust_hash, false);
6934 fn test_sweep_outbound_htlc_failure_update() {
6935 do_test_sweep_outbound_htlc_failure_update(false, true);
6936 do_test_sweep_outbound_htlc_failure_update(false, false);
6937 do_test_sweep_outbound_htlc_failure_update(true, false);
6941 fn test_user_configurable_csv_delay() {
6942 // We test our channel constructors yield errors when we pass them absurd csv delay
6944 let mut low_our_to_self_config = UserConfig::default();
6945 low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
6946 let mut high_their_to_self_config = UserConfig::default();
6947 high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
6948 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
6949 let chanmon_cfgs = create_chanmon_cfgs(2);
6950 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6951 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
6952 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6954 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
6955 if let Err(error) = Channel::new_outbound(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6956 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[1].node.init_features(), 1000000, 1000000, 0,
6957 &low_our_to_self_config, 0, 42)
6960 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())); },
6961 _ => panic!("Unexpected event"),
6963 } else { assert!(false) }
6965 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
6966 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6967 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6968 open_channel.to_self_delay = 200;
6969 if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6970 &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,
6971 &low_our_to_self_config, 0, &nodes[0].logger, 42)
6974 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())); },
6975 _ => panic!("Unexpected event"),
6977 } else { assert!(false); }
6979 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
6980 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6981 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()));
6982 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6983 accept_channel.to_self_delay = 200;
6984 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
6986 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
6988 &ErrorAction::SendErrorMessage { ref msg } => {
6989 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()));
6990 reason_msg = msg.data.clone();
6994 } else { panic!(); }
6995 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
6997 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
6998 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6999 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7000 open_channel.to_self_delay = 200;
7001 if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7002 &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,
7003 &high_their_to_self_config, 0, &nodes[0].logger, 42)
7006 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())); },
7007 _ => panic!("Unexpected event"),
7009 } else { assert!(false); }
7013 fn test_check_htlc_underpaying() {
7014 // Send payment through A -> B but A is maliciously
7015 // sending a probe payment (i.e less than expected value0
7016 // to B, B should refuse payment.
7018 let chanmon_cfgs = create_chanmon_cfgs(2);
7019 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7020 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7021 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7023 // Create some initial channels
7024 create_announced_chan_between_nodes(&nodes, 0, 1);
7026 let scorer = test_utils::TestScorer::new();
7027 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7028 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV).with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
7029 let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None, 10_000, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7030 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7031 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, None).unwrap();
7032 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
7033 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
7034 check_added_monitors!(nodes[0], 1);
7036 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7037 assert_eq!(events.len(), 1);
7038 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7039 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7040 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7042 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7043 // and then will wait a second random delay before failing the HTLC back:
7044 expect_pending_htlcs_forwardable!(nodes[1]);
7045 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7047 // Node 3 is expecting payment of 100_000 but received 10_000,
7048 // it should fail htlc like we didn't know the preimage.
7049 nodes[1].node.process_pending_htlc_forwards();
7051 let events = nodes[1].node.get_and_clear_pending_msg_events();
7052 assert_eq!(events.len(), 1);
7053 let (update_fail_htlc, commitment_signed) = match events[0] {
7054 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 } } => {
7055 assert!(update_add_htlcs.is_empty());
7056 assert!(update_fulfill_htlcs.is_empty());
7057 assert_eq!(update_fail_htlcs.len(), 1);
7058 assert!(update_fail_malformed_htlcs.is_empty());
7059 assert!(update_fee.is_none());
7060 (update_fail_htlcs[0].clone(), commitment_signed)
7062 _ => panic!("Unexpected event"),
7064 check_added_monitors!(nodes[1], 1);
7066 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7067 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7069 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7070 let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
7071 expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
7072 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7076 fn test_announce_disable_channels() {
7077 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7078 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7080 let chanmon_cfgs = create_chanmon_cfgs(2);
7081 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7082 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7083 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7085 create_announced_chan_between_nodes(&nodes, 0, 1);
7086 create_announced_chan_between_nodes(&nodes, 1, 0);
7087 create_announced_chan_between_nodes(&nodes, 0, 1);
7090 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
7091 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
7093 for _ in 0..DISABLE_GOSSIP_TICKS + 1 {
7094 nodes[0].node.timer_tick_occurred();
7096 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7097 assert_eq!(msg_events.len(), 3);
7098 let mut chans_disabled = HashMap::new();
7099 for e in msg_events {
7101 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7102 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7103 // Check that each channel gets updated exactly once
7104 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7105 panic!("Generated ChannelUpdate for wrong chan!");
7108 _ => panic!("Unexpected event"),
7112 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: nodes[1].node.init_features(), remote_network_address: None }, true).unwrap();
7113 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7114 assert_eq!(reestablish_1.len(), 3);
7115 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: nodes[0].node.init_features(), remote_network_address: None }, false).unwrap();
7116 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7117 assert_eq!(reestablish_2.len(), 3);
7119 // Reestablish chan_1
7120 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7121 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7122 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7123 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7124 // Reestablish chan_2
7125 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7126 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7127 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7128 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7129 // Reestablish chan_3
7130 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7131 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7132 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7133 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7135 for _ in 0..ENABLE_GOSSIP_TICKS {
7136 nodes[0].node.timer_tick_occurred();
7138 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7139 nodes[0].node.timer_tick_occurred();
7140 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7141 assert_eq!(msg_events.len(), 3);
7142 for e in msg_events {
7144 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7145 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7146 match chans_disabled.remove(&msg.contents.short_channel_id) {
7147 // Each update should have a higher timestamp than the previous one, replacing
7149 Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7150 None => panic!("Generated ChannelUpdate for wrong chan!"),
7153 _ => panic!("Unexpected event"),
7156 // Check that each channel gets updated exactly once
7157 assert!(chans_disabled.is_empty());
7161 fn test_bump_penalty_txn_on_revoked_commitment() {
7162 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7163 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7165 let chanmon_cfgs = create_chanmon_cfgs(2);
7166 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7167 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7168 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7170 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7172 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7173 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7174 .with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7175 let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000);
7176 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7178 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7179 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7180 assert_eq!(revoked_txn[0].output.len(), 4);
7181 assert_eq!(revoked_txn[0].input.len(), 1);
7182 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7183 let revoked_txid = revoked_txn[0].txid();
7185 let mut penalty_sum = 0;
7186 for outp in revoked_txn[0].output.iter() {
7187 if outp.script_pubkey.is_v0_p2wsh() {
7188 penalty_sum += outp.value;
7192 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7193 let header_114 = connect_blocks(&nodes[1], 14);
7195 // Actually revoke tx by claiming a HTLC
7196 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7197 connect_block(&nodes[1], &create_dummy_block(header_114, 42, vec![revoked_txn[0].clone()]));
7198 check_added_monitors!(nodes[1], 1);
7200 // One or more justice tx should have been broadcast, check it
7204 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7205 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7206 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7207 assert_eq!(node_txn[0].output.len(), 1);
7208 check_spends!(node_txn[0], revoked_txn[0]);
7209 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7210 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7211 penalty_1 = node_txn[0].txid();
7215 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7216 connect_blocks(&nodes[1], 15);
7217 let mut penalty_2 = penalty_1;
7218 let mut feerate_2 = 0;
7220 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7221 assert_eq!(node_txn.len(), 1);
7222 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7223 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7224 assert_eq!(node_txn[0].output.len(), 1);
7225 check_spends!(node_txn[0], revoked_txn[0]);
7226 penalty_2 = node_txn[0].txid();
7227 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7228 assert_ne!(penalty_2, penalty_1);
7229 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7230 feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7231 // Verify 25% bump heuristic
7232 assert!(feerate_2 * 100 >= feerate_1 * 125);
7236 assert_ne!(feerate_2, 0);
7238 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7239 connect_blocks(&nodes[1], 1);
7241 let mut feerate_3 = 0;
7243 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7244 assert_eq!(node_txn.len(), 1);
7245 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7246 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7247 assert_eq!(node_txn[0].output.len(), 1);
7248 check_spends!(node_txn[0], revoked_txn[0]);
7249 penalty_3 = node_txn[0].txid();
7250 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7251 assert_ne!(penalty_3, penalty_2);
7252 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7253 feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7254 // Verify 25% bump heuristic
7255 assert!(feerate_3 * 100 >= feerate_2 * 125);
7259 assert_ne!(feerate_3, 0);
7261 nodes[1].node.get_and_clear_pending_events();
7262 nodes[1].node.get_and_clear_pending_msg_events();
7266 fn test_bump_penalty_txn_on_revoked_htlcs() {
7267 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7268 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7270 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7271 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7272 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7273 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7274 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7276 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7277 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7278 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 50).with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
7279 let scorer = test_utils::TestScorer::new();
7280 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7281 let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7282 3_000_000, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7283 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7284 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50).with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7285 let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7286 3_000_000, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7287 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7289 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7290 assert_eq!(revoked_local_txn[0].input.len(), 1);
7291 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7293 // Revoke local commitment tx
7294 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7296 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7297 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone()]));
7298 check_closed_broadcast!(nodes[1], true);
7299 check_added_monitors!(nodes[1], 1);
7300 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7301 connect_blocks(&nodes[1], 50); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7303 let revoked_htlc_txn = {
7304 let txn = nodes[1].tx_broadcaster.unique_txn_broadcast();
7305 assert_eq!(txn.len(), 2);
7307 assert_eq!(txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7308 assert_eq!(txn[0].input.len(), 1);
7309 check_spends!(txn[0], revoked_local_txn[0]);
7311 assert_eq!(txn[1].input.len(), 1);
7312 assert_eq!(txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7313 assert_eq!(txn[1].output.len(), 1);
7314 check_spends!(txn[1], revoked_local_txn[0]);
7319 // Broadcast set of revoked txn on A
7320 let hash_128 = connect_blocks(&nodes[0], 40);
7321 let block_11 = create_dummy_block(hash_128, 42, vec![revoked_local_txn[0].clone()]);
7322 connect_block(&nodes[0], &block_11);
7323 let block_129 = create_dummy_block(block_11.block_hash(), 42, vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()]);
7324 connect_block(&nodes[0], &block_129);
7325 let events = nodes[0].node.get_and_clear_pending_events();
7326 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7327 match events.last().unwrap() {
7328 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7329 _ => panic!("Unexpected event"),
7335 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7336 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7337 // Verify claim tx are spending revoked HTLC txn
7339 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7340 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7341 // which are included in the same block (they are broadcasted because we scan the
7342 // transactions linearly and generate claims as we go, they likely should be removed in the
7344 assert_eq!(node_txn[0].input.len(), 1);
7345 check_spends!(node_txn[0], revoked_local_txn[0]);
7346 assert_eq!(node_txn[1].input.len(), 1);
7347 check_spends!(node_txn[1], revoked_local_txn[0]);
7348 assert_eq!(node_txn[2].input.len(), 1);
7349 check_spends!(node_txn[2], revoked_local_txn[0]);
7351 // Each of the three justice transactions claim a separate (single) output of the three
7352 // available, which we check here:
7353 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7354 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7355 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7357 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7358 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7360 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7361 // output, checked above).
7362 assert_eq!(node_txn[3].input.len(), 2);
7363 assert_eq!(node_txn[3].output.len(), 1);
7364 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7366 first = node_txn[3].txid();
7367 // Store both feerates for later comparison
7368 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7369 feerate_1 = fee_1 * 1000 / node_txn[3].weight() as u64;
7370 penalty_txn = vec![node_txn[2].clone()];
7374 // Connect one more block to see if bumped penalty are issued for HTLC txn
7375 let block_130 = create_dummy_block(block_129.block_hash(), 42, penalty_txn);
7376 connect_block(&nodes[0], &block_130);
7377 let block_131 = create_dummy_block(block_130.block_hash(), 42, Vec::new());
7378 connect_block(&nodes[0], &block_131);
7380 // Few more blocks to confirm penalty txn
7381 connect_blocks(&nodes[0], 4);
7382 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7383 let header_144 = connect_blocks(&nodes[0], 9);
7385 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7386 assert_eq!(node_txn.len(), 1);
7388 assert_eq!(node_txn[0].input.len(), 2);
7389 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7390 // Verify bumped tx is different and 25% bump heuristic
7391 assert_ne!(first, node_txn[0].txid());
7392 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7393 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7394 assert!(feerate_2 * 100 > feerate_1 * 125);
7395 let txn = vec![node_txn[0].clone()];
7399 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7400 connect_block(&nodes[0], &create_dummy_block(header_144, 42, node_txn));
7401 connect_blocks(&nodes[0], 20);
7403 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7404 // We verify than no new transaction has been broadcast because previously
7405 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7406 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7407 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7408 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7409 // up bumped justice generation.
7410 assert_eq!(node_txn.len(), 0);
7413 check_closed_broadcast!(nodes[0], true);
7414 check_added_monitors!(nodes[0], 1);
7418 fn test_bump_penalty_txn_on_remote_commitment() {
7419 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7420 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7423 // Provide preimage for one
7424 // Check aggregation
7426 let chanmon_cfgs = create_chanmon_cfgs(2);
7427 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7428 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7429 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7431 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7432 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7433 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7435 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7436 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7437 assert_eq!(remote_txn[0].output.len(), 4);
7438 assert_eq!(remote_txn[0].input.len(), 1);
7439 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7441 // Claim a HTLC without revocation (provide B monitor with preimage)
7442 nodes[1].node.claim_funds(payment_preimage);
7443 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7444 mine_transaction(&nodes[1], &remote_txn[0]);
7445 check_added_monitors!(nodes[1], 2);
7446 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7448 // One or more claim tx should have been broadcast, check it
7452 let feerate_timeout;
7453 let feerate_preimage;
7455 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7456 // 3 transactions including:
7457 // preimage and timeout sweeps from remote commitment + preimage sweep bump
7458 assert_eq!(node_txn.len(), 3);
7459 assert_eq!(node_txn[0].input.len(), 1);
7460 assert_eq!(node_txn[1].input.len(), 1);
7461 assert_eq!(node_txn[2].input.len(), 1);
7462 check_spends!(node_txn[0], remote_txn[0]);
7463 check_spends!(node_txn[1], remote_txn[0]);
7464 check_spends!(node_txn[2], remote_txn[0]);
7466 preimage = node_txn[0].txid();
7467 let index = node_txn[0].input[0].previous_output.vout;
7468 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7469 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
7471 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7472 (node_txn[2].clone(), node_txn[1].clone())
7474 (node_txn[1].clone(), node_txn[2].clone())
7477 preimage_bump = preimage_bump_tx;
7478 check_spends!(preimage_bump, remote_txn[0]);
7479 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7481 timeout = timeout_tx.txid();
7482 let index = timeout_tx.input[0].previous_output.vout;
7483 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7484 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
7488 assert_ne!(feerate_timeout, 0);
7489 assert_ne!(feerate_preimage, 0);
7491 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7492 connect_blocks(&nodes[1], 1);
7494 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7495 assert_eq!(node_txn.len(), 1);
7496 assert_eq!(node_txn[0].input.len(), 1);
7497 assert_eq!(preimage_bump.input.len(), 1);
7498 check_spends!(node_txn[0], remote_txn[0]);
7499 check_spends!(preimage_bump, remote_txn[0]);
7501 let index = preimage_bump.input[0].previous_output.vout;
7502 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7503 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
7504 assert!(new_feerate * 100 > feerate_timeout * 125);
7505 assert_ne!(timeout, preimage_bump.txid());
7507 let index = node_txn[0].input[0].previous_output.vout;
7508 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7509 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
7510 assert!(new_feerate * 100 > feerate_preimage * 125);
7511 assert_ne!(preimage, node_txn[0].txid());
7516 nodes[1].node.get_and_clear_pending_events();
7517 nodes[1].node.get_and_clear_pending_msg_events();
7521 fn test_counterparty_raa_skip_no_crash() {
7522 // Previously, if our counterparty sent two RAAs in a row without us having provided a
7523 // commitment transaction, we would have happily carried on and provided them the next
7524 // commitment transaction based on one RAA forward. This would probably eventually have led to
7525 // channel closure, but it would not have resulted in funds loss. Still, our
7526 // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7527 // check simply that the channel is closed in response to such an RAA, but don't check whether
7528 // we decide to punish our counterparty for revoking their funds (as we don't currently
7530 let chanmon_cfgs = create_chanmon_cfgs(2);
7531 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7532 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7533 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7534 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7536 let per_commitment_secret;
7537 let next_per_commitment_point;
7539 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7540 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7541 let keys = guard.channel_by_id.get_mut(&channel_id).unwrap().get_signer();
7543 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7545 // Make signer believe we got a counterparty signature, so that it allows the revocation
7546 keys.get_enforcement_state().last_holder_commitment -= 1;
7547 per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7549 // Must revoke without gaps
7550 keys.get_enforcement_state().last_holder_commitment -= 1;
7551 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7553 keys.get_enforcement_state().last_holder_commitment -= 1;
7554 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7555 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7558 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7559 &msgs::RevokeAndACK {
7561 per_commitment_secret,
7562 next_per_commitment_point,
7564 next_local_nonce: None,
7566 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7567 check_added_monitors!(nodes[1], 1);
7568 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
7572 fn test_bump_txn_sanitize_tracking_maps() {
7573 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7574 // verify we clean then right after expiration of ANTI_REORG_DELAY.
7576 let chanmon_cfgs = create_chanmon_cfgs(2);
7577 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7578 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7579 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7581 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7582 // Lock HTLC in both directions
7583 let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7584 let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7586 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7587 assert_eq!(revoked_local_txn[0].input.len(), 1);
7588 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7590 // Revoke local commitment tx
7591 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7593 // Broadcast set of revoked txn on A
7594 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7595 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7596 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7598 mine_transaction(&nodes[0], &revoked_local_txn[0]);
7599 check_closed_broadcast!(nodes[0], true);
7600 check_added_monitors!(nodes[0], 1);
7601 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7603 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7604 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7605 check_spends!(node_txn[0], revoked_local_txn[0]);
7606 check_spends!(node_txn[1], revoked_local_txn[0]);
7607 check_spends!(node_txn[2], revoked_local_txn[0]);
7608 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7612 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, penalty_txn));
7613 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7615 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7616 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7617 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7622 fn test_pending_claimed_htlc_no_balance_underflow() {
7623 // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
7624 // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
7625 let chanmon_cfgs = create_chanmon_cfgs(2);
7626 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7627 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7628 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7629 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
7631 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_010_000);
7632 nodes[1].node.claim_funds(payment_preimage);
7633 expect_payment_claimed!(nodes[1], payment_hash, 1_010_000);
7634 check_added_monitors!(nodes[1], 1);
7635 let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7637 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
7638 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
7639 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
7640 check_added_monitors!(nodes[0], 1);
7641 let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7643 // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
7644 // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
7645 // can get our balance.
7647 // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
7648 // the public key of the only hop. This works around ChannelDetails not showing the
7649 // almost-claimed HTLC as available balance.
7650 let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
7651 route.payment_params = None; // This is all wrong, but unnecessary
7652 route.paths[0].hops[0].pubkey = nodes[0].node.get_our_node_id();
7653 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
7654 nodes[1].node.send_payment_with_route(&route, payment_hash_2,
7655 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
7657 assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
7661 fn test_channel_conf_timeout() {
7662 // Tests that, for inbound channels, we give up on them if the funding transaction does not
7663 // confirm within 2016 blocks, as recommended by BOLT 2.
7664 let chanmon_cfgs = create_chanmon_cfgs(2);
7665 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7666 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7667 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7669 let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7671 // The outbound node should wait forever for confirmation:
7672 // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7673 // copied here instead of directly referencing the constant.
7674 connect_blocks(&nodes[0], 2016);
7675 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7677 // The inbound node should fail the channel after exactly 2016 blocks
7678 connect_blocks(&nodes[1], 2015);
7679 check_added_monitors!(nodes[1], 0);
7680 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7682 connect_blocks(&nodes[1], 1);
7683 check_added_monitors!(nodes[1], 1);
7684 check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
7685 let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7686 assert_eq!(close_ev.len(), 1);
7688 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
7689 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7690 assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7692 _ => panic!("Unexpected event"),
7697 fn test_override_channel_config() {
7698 let chanmon_cfgs = create_chanmon_cfgs(2);
7699 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7700 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7701 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7703 // Node0 initiates a channel to node1 using the override config.
7704 let mut override_config = UserConfig::default();
7705 override_config.channel_handshake_config.our_to_self_delay = 200;
7707 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7709 // Assert the channel created by node0 is using the override config.
7710 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7711 assert_eq!(res.channel_flags, 0);
7712 assert_eq!(res.to_self_delay, 200);
7716 fn test_override_0msat_htlc_minimum() {
7717 let mut zero_config = UserConfig::default();
7718 zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7719 let chanmon_cfgs = create_chanmon_cfgs(2);
7720 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7721 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7722 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7724 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7725 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7726 assert_eq!(res.htlc_minimum_msat, 1);
7728 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7729 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7730 assert_eq!(res.htlc_minimum_msat, 1);
7734 fn test_channel_update_has_correct_htlc_maximum_msat() {
7735 // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7736 // Bolt 7 specifies that if present `htlc_maximum_msat`:
7737 // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7738 // 90% of the `channel_value`.
7739 // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7741 let mut config_30_percent = UserConfig::default();
7742 config_30_percent.channel_handshake_config.announced_channel = true;
7743 config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7744 let mut config_50_percent = UserConfig::default();
7745 config_50_percent.channel_handshake_config.announced_channel = true;
7746 config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7747 let mut config_95_percent = UserConfig::default();
7748 config_95_percent.channel_handshake_config.announced_channel = true;
7749 config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7750 let mut config_100_percent = UserConfig::default();
7751 config_100_percent.channel_handshake_config.announced_channel = true;
7752 config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7754 let chanmon_cfgs = create_chanmon_cfgs(4);
7755 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7756 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)]);
7757 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7759 let channel_value_satoshis = 100000;
7760 let channel_value_msat = channel_value_satoshis * 1000;
7761 let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7762 let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7763 let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7765 let (node_0_chan_update, node_1_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
7766 let (node_2_chan_update, node_3_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
7768 // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7769 // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7770 assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7771 // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7772 // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7773 assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7775 // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7776 // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7778 assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7779 // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7780 // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7782 assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7786 fn test_manually_accept_inbound_channel_request() {
7787 let mut manually_accept_conf = UserConfig::default();
7788 manually_accept_conf.manually_accept_inbound_channels = true;
7789 let chanmon_cfgs = create_chanmon_cfgs(2);
7790 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7791 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7792 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7794 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7795 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7797 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7799 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7800 // accepting the inbound channel request.
7801 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7803 let events = nodes[1].node.get_and_clear_pending_events();
7805 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7806 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
7808 _ => panic!("Unexpected event"),
7811 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7812 assert_eq!(accept_msg_ev.len(), 1);
7814 match accept_msg_ev[0] {
7815 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7816 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7818 _ => panic!("Unexpected event"),
7821 nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7823 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7824 assert_eq!(close_msg_ev.len(), 1);
7826 let events = nodes[1].node.get_and_clear_pending_events();
7828 Event::ChannelClosed { user_channel_id, .. } => {
7829 assert_eq!(user_channel_id, 23);
7831 _ => panic!("Unexpected event"),
7836 fn test_manually_reject_inbound_channel_request() {
7837 let mut manually_accept_conf = UserConfig::default();
7838 manually_accept_conf.manually_accept_inbound_channels = true;
7839 let chanmon_cfgs = create_chanmon_cfgs(2);
7840 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7841 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7842 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7844 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7845 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7847 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7849 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7850 // rejecting the inbound channel request.
7851 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7853 let events = nodes[1].node.get_and_clear_pending_events();
7855 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7856 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7858 _ => panic!("Unexpected event"),
7861 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7862 assert_eq!(close_msg_ev.len(), 1);
7864 match close_msg_ev[0] {
7865 MessageSendEvent::HandleError { ref node_id, .. } => {
7866 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7868 _ => panic!("Unexpected event"),
7870 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
7874 fn test_reject_funding_before_inbound_channel_accepted() {
7875 // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
7876 // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
7877 // the node operator before the counterparty sends a `FundingCreated` message. If a
7878 // `FundingCreated` message is received before the channel is accepted, it should be rejected
7879 // and the channel should be closed.
7880 let mut manually_accept_conf = UserConfig::default();
7881 manually_accept_conf.manually_accept_inbound_channels = true;
7882 let chanmon_cfgs = create_chanmon_cfgs(2);
7883 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7884 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7885 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7887 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7888 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7889 let temp_channel_id = res.temporary_channel_id;
7891 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7893 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
7894 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7896 // Clear the `Event::OpenChannelRequest` event without responding to the request.
7897 nodes[1].node.get_and_clear_pending_events();
7899 // Get the `AcceptChannel` message of `nodes[1]` without calling
7900 // `ChannelManager::accept_inbound_channel`, which generates a
7901 // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
7902 // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
7903 // succeed when `nodes[0]` is passed to it.
7904 let accept_chan_msg = {
7905 let mut node_1_per_peer_lock;
7906 let mut node_1_peer_state_lock;
7907 let channel = get_channel_ref!(&nodes[1], nodes[0], node_1_per_peer_lock, node_1_peer_state_lock, temp_channel_id);
7908 channel.get_accept_channel_message()
7910 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
7912 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
7914 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
7915 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
7917 // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
7918 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
7920 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7921 assert_eq!(close_msg_ev.len(), 1);
7923 let expected_err = "FundingCreated message received before the channel was accepted";
7924 match close_msg_ev[0] {
7925 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
7926 assert_eq!(msg.channel_id, temp_channel_id);
7927 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7928 assert_eq!(msg.data, expected_err);
7930 _ => panic!("Unexpected event"),
7933 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
7937 fn test_can_not_accept_inbound_channel_twice() {
7938 let mut manually_accept_conf = UserConfig::default();
7939 manually_accept_conf.manually_accept_inbound_channels = true;
7940 let chanmon_cfgs = create_chanmon_cfgs(2);
7941 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7942 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7943 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7945 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7946 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7948 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7950 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7951 // accepting the inbound channel request.
7952 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7954 let events = nodes[1].node.get_and_clear_pending_events();
7956 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7957 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
7958 let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
7960 Err(APIError::APIMisuseError { err }) => {
7961 assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
7963 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
7964 Err(_) => panic!("Unexpected Error"),
7967 _ => panic!("Unexpected event"),
7970 // Ensure that the channel wasn't closed after attempting to accept it twice.
7971 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7972 assert_eq!(accept_msg_ev.len(), 1);
7974 match accept_msg_ev[0] {
7975 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7976 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7978 _ => panic!("Unexpected event"),
7983 fn test_can_not_accept_unknown_inbound_channel() {
7984 let chanmon_cfg = create_chanmon_cfgs(2);
7985 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
7986 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
7987 let nodes = create_network(2, &node_cfg, &node_chanmgr);
7989 let unknown_channel_id = [0; 32];
7990 let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
7992 Err(APIError::ChannelUnavailable { err }) => {
7993 assert_eq!(err, format!("Channel with id {} not found for the passed counterparty node_id {}", log_bytes!(unknown_channel_id), nodes[1].node.get_our_node_id()));
7995 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
7996 Err(_) => panic!("Unexpected Error"),
8001 fn test_onion_value_mpp_set_calculation() {
8002 // Test that we use the onion value `amt_to_forward` when
8003 // calculating whether we've reached the `total_msat` of an MPP
8004 // by having a routing node forward more than `amt_to_forward`
8005 // and checking that the receiving node doesn't generate
8006 // a PaymentClaimable event too early
8008 let chanmon_cfgs = create_chanmon_cfgs(node_count);
8009 let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8010 let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8011 let mut nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8013 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8014 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8015 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8016 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8018 let total_msat = 100_000;
8019 let expected_paths: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
8020 let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], total_msat);
8021 let sample_path = route.paths.pop().unwrap();
8023 let mut path_1 = sample_path.clone();
8024 path_1.hops[0].pubkey = nodes[1].node.get_our_node_id();
8025 path_1.hops[0].short_channel_id = chan_1_id;
8026 path_1.hops[1].pubkey = nodes[3].node.get_our_node_id();
8027 path_1.hops[1].short_channel_id = chan_3_id;
8028 path_1.hops[1].fee_msat = 100_000;
8029 route.paths.push(path_1);
8031 let mut path_2 = sample_path.clone();
8032 path_2.hops[0].pubkey = nodes[2].node.get_our_node_id();
8033 path_2.hops[0].short_channel_id = chan_2_id;
8034 path_2.hops[1].pubkey = nodes[3].node.get_our_node_id();
8035 path_2.hops[1].short_channel_id = chan_4_id;
8036 path_2.hops[1].fee_msat = 1_000;
8037 route.paths.push(path_2);
8040 let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
8041 let onion_session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
8042 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8043 nodes[0].node.test_send_payment_internal(&route, our_payment_hash,
8044 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8045 check_added_monitors!(nodes[0], expected_paths.len());
8047 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8048 assert_eq!(events.len(), expected_paths.len());
8051 let ev = remove_first_msg_event_to_node(&expected_paths[0][0].node.get_our_node_id(), &mut events);
8052 let mut payment_event = SendEvent::from_event(ev);
8053 let mut prev_node = &nodes[0];
8055 for (idx, &node) in expected_paths[0].iter().enumerate() {
8056 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
8058 if idx == 0 { // routing node
8059 let session_priv = [3; 32];
8060 let height = nodes[0].best_block_info().1;
8061 let session_priv = SecretKey::from_slice(&session_priv).unwrap();
8062 let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
8063 let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], 100_000,
8064 RecipientOnionFields::secret_only(our_payment_secret), height + 1, &None).unwrap();
8065 // Edit amt_to_forward to simulate the sender having set
8066 // the final amount and the routing node taking less fee
8067 onion_payloads[1].amt_to_forward = 99_000;
8068 let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
8069 payment_event.msgs[0].onion_routing_packet = new_onion_packet;
8072 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
8073 check_added_monitors!(node, 0);
8074 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
8075 expect_pending_htlcs_forwardable!(node);
8078 let mut events_2 = node.node.get_and_clear_pending_msg_events();
8079 assert_eq!(events_2.len(), 1);
8080 check_added_monitors!(node, 1);
8081 payment_event = SendEvent::from_event(events_2.remove(0));
8082 assert_eq!(payment_event.msgs.len(), 1);
8084 let events_2 = node.node.get_and_clear_pending_events();
8085 assert!(events_2.is_empty());
8092 let ev = remove_first_msg_event_to_node(&expected_paths[1][0].node.get_our_node_id(), &mut events);
8093 pass_along_path(&nodes[0], expected_paths[1], 101_000, our_payment_hash.clone(), Some(our_payment_secret), ev, true, None);
8095 claim_payment_along_route(&nodes[0], expected_paths, false, our_payment_preimage);
8098 fn do_test_overshoot_mpp(msat_amounts: &[u64], total_msat: u64) {
8100 let routing_node_count = msat_amounts.len();
8101 let node_count = routing_node_count + 2;
8103 let chanmon_cfgs = create_chanmon_cfgs(node_count);
8104 let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8105 let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8106 let nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8111 // Create channels for each amount
8112 let mut expected_paths = Vec::with_capacity(routing_node_count);
8113 let mut src_chan_ids = Vec::with_capacity(routing_node_count);
8114 let mut dst_chan_ids = Vec::with_capacity(routing_node_count);
8115 for i in 0..routing_node_count {
8116 let routing_node = 2 + i;
8117 let src_chan_id = create_announced_chan_between_nodes(&nodes, src_idx, routing_node).0.contents.short_channel_id;
8118 src_chan_ids.push(src_chan_id);
8119 let dst_chan_id = create_announced_chan_between_nodes(&nodes, routing_node, dst_idx).0.contents.short_channel_id;
8120 dst_chan_ids.push(dst_chan_id);
8121 let path = vec![&nodes[routing_node], &nodes[dst_idx]];
8122 expected_paths.push(path);
8124 let expected_paths: Vec<&[&Node]> = expected_paths.iter().map(|route| route.as_slice()).collect();
8126 // Create a route for each amount
8127 let example_amount = 100000;
8128 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);
8129 let sample_path = route.paths.pop().unwrap();
8130 for i in 0..routing_node_count {
8131 let routing_node = 2 + i;
8132 let mut path = sample_path.clone();
8133 path.hops[0].pubkey = nodes[routing_node].node.get_our_node_id();
8134 path.hops[0].short_channel_id = src_chan_ids[i];
8135 path.hops[1].pubkey = nodes[dst_idx].node.get_our_node_id();
8136 path.hops[1].short_channel_id = dst_chan_ids[i];
8137 path.hops[1].fee_msat = msat_amounts[i];
8138 route.paths.push(path);
8141 // Send payment with manually set total_msat
8142 let payment_id = PaymentId(nodes[src_idx].keys_manager.backing.get_secure_random_bytes());
8143 let onion_session_privs = nodes[src_idx].node.test_add_new_pending_payment(our_payment_hash,
8144 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8145 nodes[src_idx].node.test_send_payment_internal(&route, our_payment_hash,
8146 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8147 check_added_monitors!(nodes[src_idx], expected_paths.len());
8149 let mut events = nodes[src_idx].node.get_and_clear_pending_msg_events();
8150 assert_eq!(events.len(), expected_paths.len());
8151 let mut amount_received = 0;
8152 for (path_idx, expected_path) in expected_paths.iter().enumerate() {
8153 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
8155 let current_path_amount = msat_amounts[path_idx];
8156 amount_received += current_path_amount;
8157 let became_claimable_now = amount_received >= total_msat && amount_received - current_path_amount < total_msat;
8158 pass_along_path(&nodes[src_idx], expected_path, amount_received, our_payment_hash.clone(), Some(our_payment_secret), ev, became_claimable_now, None);
8161 claim_payment_along_route(&nodes[src_idx], &expected_paths, false, our_payment_preimage);
8165 fn test_overshoot_mpp() {
8166 do_test_overshoot_mpp(&[100_000, 101_000], 200_000);
8167 do_test_overshoot_mpp(&[100_000, 10_000, 100_000], 200_000);
8171 fn test_simple_mpp() {
8172 // Simple test of sending a multi-path payment.
8173 let chanmon_cfgs = create_chanmon_cfgs(4);
8174 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8175 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8176 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8178 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8179 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8180 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8181 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8183 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8184 let path = route.paths[0].clone();
8185 route.paths.push(path);
8186 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
8187 route.paths[0].hops[0].short_channel_id = chan_1_id;
8188 route.paths[0].hops[1].short_channel_id = chan_3_id;
8189 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
8190 route.paths[1].hops[0].short_channel_id = chan_2_id;
8191 route.paths[1].hops[1].short_channel_id = chan_4_id;
8192 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8193 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8197 fn test_preimage_storage() {
8198 // Simple test of payment preimage storage allowing no client-side storage to claim payments
8199 let chanmon_cfgs = create_chanmon_cfgs(2);
8200 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8201 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8202 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8204 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8207 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
8208 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8209 nodes[0].node.send_payment_with_route(&route, payment_hash,
8210 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8211 check_added_monitors!(nodes[0], 1);
8212 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8213 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8214 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8215 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8217 // Note that after leaving the above scope we have no knowledge of any arguments or return
8218 // values from previous calls.
8219 expect_pending_htlcs_forwardable!(nodes[1]);
8220 let events = nodes[1].node.get_and_clear_pending_events();
8221 assert_eq!(events.len(), 1);
8223 Event::PaymentClaimable { ref purpose, .. } => {
8225 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8226 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8228 _ => panic!("expected PaymentPurpose::InvoicePayment")
8231 _ => panic!("Unexpected event"),
8236 #[allow(deprecated)]
8237 fn test_secret_timeout() {
8238 // Simple test of payment secret storage time outs. After
8239 // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8240 let chanmon_cfgs = create_chanmon_cfgs(2);
8241 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8242 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8243 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8245 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8247 let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8249 // We should fail to register the same payment hash twice, at least until we've connected a
8250 // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8251 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8252 assert_eq!(err, "Duplicate payment hash");
8253 } else { panic!(); }
8255 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8256 create_dummy_block(node_1_blocks.last().unwrap().0.block_hash(), node_1_blocks.len() as u32 + 7200, Vec::new())
8258 connect_block(&nodes[1], &block);
8259 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8260 assert_eq!(err, "Duplicate payment hash");
8261 } else { panic!(); }
8263 // If we then connect the second block, we should be able to register the same payment hash
8264 // again (this time getting a new payment secret).
8265 block.header.prev_blockhash = block.header.block_hash();
8266 block.header.time += 1;
8267 connect_block(&nodes[1], &block);
8268 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8269 assert_ne!(payment_secret_1, our_payment_secret);
8272 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8273 nodes[0].node.send_payment_with_route(&route, payment_hash,
8274 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(payment_hash.0)).unwrap();
8275 check_added_monitors!(nodes[0], 1);
8276 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8277 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8278 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8279 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8281 // Note that after leaving the above scope we have no knowledge of any arguments or return
8282 // values from previous calls.
8283 expect_pending_htlcs_forwardable!(nodes[1]);
8284 let events = nodes[1].node.get_and_clear_pending_events();
8285 assert_eq!(events.len(), 1);
8287 Event::PaymentClaimable { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8288 assert!(payment_preimage.is_none());
8289 assert_eq!(payment_secret, our_payment_secret);
8290 // We don't actually have the payment preimage with which to claim this payment!
8292 _ => panic!("Unexpected event"),
8297 fn test_bad_secret_hash() {
8298 // Simple test of unregistered payment hash/invalid payment secret handling
8299 let chanmon_cfgs = create_chanmon_cfgs(2);
8300 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8301 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8302 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8304 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8306 let random_payment_hash = PaymentHash([42; 32]);
8307 let random_payment_secret = PaymentSecret([43; 32]);
8308 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8309 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8311 // All the below cases should end up being handled exactly identically, so we macro the
8312 // resulting events.
8313 macro_rules! handle_unknown_invalid_payment_data {
8314 ($payment_hash: expr) => {
8315 check_added_monitors!(nodes[0], 1);
8316 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8317 let payment_event = SendEvent::from_event(events.pop().unwrap());
8318 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8319 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8321 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8322 // again to process the pending backwards-failure of the HTLC
8323 expect_pending_htlcs_forwardable!(nodes[1]);
8324 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8325 check_added_monitors!(nodes[1], 1);
8327 // We should fail the payment back
8328 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8329 match events.pop().unwrap() {
8330 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8331 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8332 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8334 _ => panic!("Unexpected event"),
8339 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8340 // Error data is the HTLC value (100,000) and current block height
8341 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8343 // Send a payment with the right payment hash but the wrong payment secret
8344 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
8345 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8346 handle_unknown_invalid_payment_data!(our_payment_hash);
8347 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8349 // Send a payment with a random payment hash, but the right payment secret
8350 nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8351 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8352 handle_unknown_invalid_payment_data!(random_payment_hash);
8353 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8355 // Send a payment with a random payment hash and random payment secret
8356 nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8357 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8358 handle_unknown_invalid_payment_data!(random_payment_hash);
8359 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8363 fn test_update_err_monitor_lockdown() {
8364 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8365 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8366 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8369 // This scenario may happen in a watchtower setup, where watchtower process a block height
8370 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8371 // commitment at same time.
8373 let chanmon_cfgs = create_chanmon_cfgs(2);
8374 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8375 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8376 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8378 // Create some initial channel
8379 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8380 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8382 // Rebalance the network to generate htlc in the two directions
8383 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8385 // Route a HTLC from node 0 to node 1 (but don't settle)
8386 let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8388 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8389 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8390 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8391 let persister = test_utils::TestPersister::new();
8394 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8395 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8396 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8397 assert!(new_monitor == *monitor);
8400 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);
8401 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8404 let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8405 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8406 // transaction lock time requirements here.
8407 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 200));
8408 watchtower.chain_monitor.block_connected(&block, 200);
8410 // Try to update ChannelMonitor
8411 nodes[1].node.claim_funds(preimage);
8412 check_added_monitors!(nodes[1], 1);
8413 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8415 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8416 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8417 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8419 let mut node_0_per_peer_lock;
8420 let mut node_0_peer_state_lock;
8421 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8422 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8423 assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8424 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8425 } else { assert!(false); }
8427 // Our local monitor is in-sync and hasn't processed yet timeout
8428 check_added_monitors!(nodes[0], 1);
8429 let events = nodes[0].node.get_and_clear_pending_events();
8430 assert_eq!(events.len(), 1);
8434 fn test_concurrent_monitor_claim() {
8435 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8436 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8437 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8438 // state N+1 confirms. Alice claims output from state N+1.
8440 let chanmon_cfgs = create_chanmon_cfgs(2);
8441 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8442 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8443 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8445 // Create some initial channel
8446 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8447 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8449 // Rebalance the network to generate htlc in the two directions
8450 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8452 // Route a HTLC from node 0 to node 1 (but don't settle)
8453 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8455 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8456 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8457 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8458 let persister = test_utils::TestPersister::new();
8459 let alice_broadcaster = test_utils::TestBroadcaster::with_blocks(
8460 Arc::new(Mutex::new(nodes[0].blocks.lock().unwrap().clone())),
8462 let watchtower_alice = {
8464 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8465 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8466 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8467 assert!(new_monitor == *monitor);
8470 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &alice_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8471 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8474 let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8475 // Make Alice aware of enough blocks that it doesn't think we're violating transaction lock time
8476 // requirements here.
8477 const HTLC_TIMEOUT_BROADCAST: u32 = CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS;
8478 alice_broadcaster.blocks.lock().unwrap().resize((HTLC_TIMEOUT_BROADCAST) as usize, (block.clone(), HTLC_TIMEOUT_BROADCAST));
8479 watchtower_alice.chain_monitor.block_connected(&block, HTLC_TIMEOUT_BROADCAST);
8481 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8483 let mut txn = alice_broadcaster.txn_broadcast();
8484 assert_eq!(txn.len(), 2);
8488 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8489 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8490 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8491 let persister = test_utils::TestPersister::new();
8492 let bob_broadcaster = test_utils::TestBroadcaster::with_blocks(Arc::clone(&alice_broadcaster.blocks));
8493 let watchtower_bob = {
8495 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8496 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8497 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8498 assert!(new_monitor == *monitor);
8501 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &bob_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8502 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8505 watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST - 1);
8507 // Route another payment to generate another update with still previous HTLC pending
8508 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8509 nodes[1].node.send_payment_with_route(&route, payment_hash,
8510 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8511 check_added_monitors!(nodes[1], 1);
8513 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8514 assert_eq!(updates.update_add_htlcs.len(), 1);
8515 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8517 let mut node_0_per_peer_lock;
8518 let mut node_0_peer_state_lock;
8519 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8520 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8521 // Watchtower Alice should already have seen the block and reject the update
8522 assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8523 assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8524 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8525 } else { assert!(false); }
8527 // Our local monitor is in-sync and hasn't processed yet timeout
8528 check_added_monitors!(nodes[0], 1);
8530 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8531 watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST);
8533 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8536 let mut txn = bob_broadcaster.txn_broadcast();
8537 assert_eq!(txn.len(), 2);
8538 bob_state_y = txn.remove(0);
8541 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8542 let height = HTLC_TIMEOUT_BROADCAST + 1;
8543 connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
8544 check_closed_broadcast(&nodes[0], 1, true);
8545 check_closed_event(&nodes[0], 1, ClosureReason::CommitmentTxConfirmed, false);
8546 watchtower_alice.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, vec![bob_state_y.clone()]), height);
8547 check_added_monitors(&nodes[0], 1);
8549 let htlc_txn = alice_broadcaster.txn_broadcast();
8550 assert_eq!(htlc_txn.len(), 2);
8551 check_spends!(htlc_txn[0], bob_state_y);
8552 // Alice doesn't clean up the old HTLC claim since it hasn't seen a conflicting spend for
8553 // it. However, she should, because it now has an invalid parent.
8554 check_spends!(htlc_txn[1], alice_state);
8559 fn test_pre_lockin_no_chan_closed_update() {
8560 // Test that if a peer closes a channel in response to a funding_created message we don't
8561 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8564 // Doing so would imply a channel monitor update before the initial channel monitor
8565 // registration, violating our API guarantees.
8567 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8568 // then opening a second channel with the same funding output as the first (which is not
8569 // rejected because the first channel does not exist in the ChannelManager) and closing it
8570 // before receiving funding_signed.
8571 let chanmon_cfgs = create_chanmon_cfgs(2);
8572 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8573 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8574 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8576 // Create an initial channel
8577 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8578 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8579 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8580 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8581 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8583 // Move the first channel through the funding flow...
8584 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8586 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8587 check_added_monitors!(nodes[0], 0);
8589 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8590 let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8591 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8592 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8593 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("Hi".to_string()) }, true);
8597 fn test_htlc_no_detection() {
8598 // This test is a mutation to underscore the detection logic bug we had
8599 // before #653. HTLC value routed is above the remaining balance, thus
8600 // inverting HTLC and `to_remote` output. HTLC will come second and
8601 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8602 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8603 // outputs order detection for correct spending children filtring.
8605 let chanmon_cfgs = create_chanmon_cfgs(2);
8606 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8607 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8608 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8610 // Create some initial channels
8611 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8613 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8614 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8615 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8616 assert_eq!(local_txn[0].input.len(), 1);
8617 assert_eq!(local_txn[0].output.len(), 3);
8618 check_spends!(local_txn[0], chan_1.3);
8620 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8621 let block = create_dummy_block(nodes[0].best_block_hash(), 42, vec![local_txn[0].clone()]);
8622 connect_block(&nodes[0], &block);
8623 // We deliberately connect the local tx twice as this should provoke a failure calling
8624 // this test before #653 fix.
8625 chain::Listen::block_connected(&nodes[0].chain_monitor.chain_monitor, &block, nodes[0].best_block_info().1 + 1);
8626 check_closed_broadcast!(nodes[0], true);
8627 check_added_monitors!(nodes[0], 1);
8628 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8629 connect_blocks(&nodes[0], TEST_FINAL_CLTV);
8631 let htlc_timeout = {
8632 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8633 assert_eq!(node_txn.len(), 1);
8634 assert_eq!(node_txn[0].input.len(), 1);
8635 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8636 check_spends!(node_txn[0], local_txn[0]);
8640 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![htlc_timeout.clone()]));
8641 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8642 expect_payment_failed!(nodes[0], our_payment_hash, false);
8645 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8646 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8647 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8648 // Carol, Alice would be the upstream node, and Carol the downstream.)
8650 // Steps of the test:
8651 // 1) Alice sends a HTLC to Carol through Bob.
8652 // 2) Carol doesn't settle the HTLC.
8653 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8654 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8655 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8656 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8657 // 5) Carol release the preimage to Bob off-chain.
8658 // 6) Bob claims the offered output on the broadcasted commitment.
8659 let chanmon_cfgs = create_chanmon_cfgs(3);
8660 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8661 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8662 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8664 // Create some initial channels
8665 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8666 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8668 // Steps (1) and (2):
8669 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8670 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8672 // Check that Alice's commitment transaction now contains an output for this HTLC.
8673 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8674 check_spends!(alice_txn[0], chan_ab.3);
8675 assert_eq!(alice_txn[0].output.len(), 2);
8676 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8677 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8678 assert_eq!(alice_txn.len(), 2);
8680 // Steps (3) and (4):
8681 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8682 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8683 let mut force_closing_node = 0; // Alice force-closes
8684 let mut counterparty_node = 1; // Bob if Alice force-closes
8687 if !broadcast_alice {
8688 force_closing_node = 1;
8689 counterparty_node = 0;
8691 nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8692 check_closed_broadcast!(nodes[force_closing_node], true);
8693 check_added_monitors!(nodes[force_closing_node], 1);
8694 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8695 if go_onchain_before_fulfill {
8696 let txn_to_broadcast = match broadcast_alice {
8697 true => alice_txn.clone(),
8698 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8700 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8701 if broadcast_alice {
8702 check_closed_broadcast!(nodes[1], true);
8703 check_added_monitors!(nodes[1], 1);
8704 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8709 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8710 // process of removing the HTLC from their commitment transactions.
8711 nodes[2].node.claim_funds(payment_preimage);
8712 check_added_monitors!(nodes[2], 1);
8713 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8715 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8716 assert!(carol_updates.update_add_htlcs.is_empty());
8717 assert!(carol_updates.update_fail_htlcs.is_empty());
8718 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8719 assert!(carol_updates.update_fee.is_none());
8720 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8722 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8723 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
8724 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8725 if !go_onchain_before_fulfill && broadcast_alice {
8726 let events = nodes[1].node.get_and_clear_pending_msg_events();
8727 assert_eq!(events.len(), 1);
8729 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8730 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8732 _ => panic!("Unexpected event"),
8735 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8736 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8737 // Carol<->Bob's updated commitment transaction info.
8738 check_added_monitors!(nodes[1], 2);
8740 let events = nodes[1].node.get_and_clear_pending_msg_events();
8741 assert_eq!(events.len(), 2);
8742 let bob_revocation = match events[0] {
8743 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8744 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8747 _ => panic!("Unexpected event"),
8749 let bob_updates = match events[1] {
8750 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8751 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8754 _ => panic!("Unexpected event"),
8757 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8758 check_added_monitors!(nodes[2], 1);
8759 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8760 check_added_monitors!(nodes[2], 1);
8762 let events = nodes[2].node.get_and_clear_pending_msg_events();
8763 assert_eq!(events.len(), 1);
8764 let carol_revocation = match events[0] {
8765 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8766 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8769 _ => panic!("Unexpected event"),
8771 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8772 check_added_monitors!(nodes[1], 1);
8774 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8775 // here's where we put said channel's commitment tx on-chain.
8776 let mut txn_to_broadcast = alice_txn.clone();
8777 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8778 if !go_onchain_before_fulfill {
8779 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8780 // If Bob was the one to force-close, he will have already passed these checks earlier.
8781 if broadcast_alice {
8782 check_closed_broadcast!(nodes[1], true);
8783 check_added_monitors!(nodes[1], 1);
8784 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8786 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8787 if broadcast_alice {
8788 assert_eq!(bob_txn.len(), 1);
8789 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8791 assert_eq!(bob_txn.len(), 2);
8792 check_spends!(bob_txn[0], chan_ab.3);
8797 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8798 // broadcasted commitment transaction.
8800 let script_weight = match broadcast_alice {
8801 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8802 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8804 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8805 // Bob force-closed and broadcasts the commitment transaction along with a
8806 // HTLC-output-claiming transaction.
8807 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8808 if broadcast_alice {
8809 assert_eq!(bob_txn.len(), 1);
8810 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8811 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8813 assert_eq!(bob_txn.len(), 2);
8814 check_spends!(bob_txn[1], txn_to_broadcast[0]);
8815 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8821 fn test_onchain_htlc_settlement_after_close() {
8822 do_test_onchain_htlc_settlement_after_close(true, true);
8823 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8824 do_test_onchain_htlc_settlement_after_close(true, false);
8825 do_test_onchain_htlc_settlement_after_close(false, false);
8829 fn test_duplicate_temporary_channel_id_from_different_peers() {
8830 // Tests that we can accept two different `OpenChannel` requests with the same
8831 // `temporary_channel_id`, as long as they are from different peers.
8832 let chanmon_cfgs = create_chanmon_cfgs(3);
8833 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8834 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8835 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8837 // Create an first channel channel
8838 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8839 let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8841 // Create an second channel
8842 nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None).unwrap();
8843 let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8845 // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8846 // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8847 open_chan_msg_chan_2_0.temporary_channel_id = open_chan_msg_chan_1_0.temporary_channel_id;
8849 // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8850 // `temporary_channel_id` as they are from different peers.
8851 nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
8853 let events = nodes[0].node.get_and_clear_pending_msg_events();
8854 assert_eq!(events.len(), 1);
8856 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8857 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8858 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8860 _ => panic!("Unexpected event"),
8864 nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
8866 let events = nodes[0].node.get_and_clear_pending_msg_events();
8867 assert_eq!(events.len(), 1);
8869 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8870 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
8871 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8873 _ => panic!("Unexpected event"),
8879 fn test_duplicate_chan_id() {
8880 // Test that if a given peer tries to open a channel with the same channel_id as one that is
8881 // already open we reject it and keep the old channel.
8883 // Previously, full_stack_target managed to figure out that if you tried to open two channels
8884 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8885 // the existing channel when we detect the duplicate new channel, screwing up our monitor
8886 // updating logic for the existing channel.
8887 let chanmon_cfgs = create_chanmon_cfgs(2);
8888 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8889 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8890 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8892 // Create an initial channel
8893 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8894 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8895 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8896 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()));
8898 // Try to create a second channel with the same temporary_channel_id as the first and check
8899 // that it is rejected.
8900 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8902 let events = nodes[1].node.get_and_clear_pending_msg_events();
8903 assert_eq!(events.len(), 1);
8905 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8906 // Technically, at this point, nodes[1] would be justified in thinking both the
8907 // first (valid) and second (invalid) channels are closed, given they both have
8908 // the same non-temporary channel_id. However, currently we do not, so we just
8909 // move forward with it.
8910 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8911 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8913 _ => panic!("Unexpected event"),
8917 // Move the first channel through the funding flow...
8918 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8920 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8921 check_added_monitors!(nodes[0], 0);
8923 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8924 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8926 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8927 assert_eq!(added_monitors.len(), 1);
8928 assert_eq!(added_monitors[0].0, funding_output);
8929 added_monitors.clear();
8931 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
8933 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8935 let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8936 let channel_id = funding_outpoint.to_channel_id();
8938 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8941 // First try to open a second channel with a temporary channel id equal to the txid-based one.
8942 // Technically this is allowed by the spec, but we don't support it and there's little reason
8943 // to. Still, it shouldn't cause any other issues.
8944 open_chan_msg.temporary_channel_id = channel_id;
8945 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8947 let events = nodes[1].node.get_and_clear_pending_msg_events();
8948 assert_eq!(events.len(), 1);
8950 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8951 // Technically, at this point, nodes[1] would be justified in thinking both
8952 // channels are closed, but currently we do not, so we just move forward with it.
8953 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8954 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8956 _ => panic!("Unexpected event"),
8960 // Now try to create a second channel which has a duplicate funding output.
8961 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8962 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8963 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
8964 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()));
8965 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
8967 let funding_created = {
8968 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
8969 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
8970 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
8971 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
8972 // try to create another channel. Instead, we drop the channel entirely here (leaving the
8973 // channelmanager in a possibly nonsense state instead).
8974 let mut as_chan = a_peer_state.channel_by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
8975 let logger = test_utils::TestLogger::new();
8976 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8978 check_added_monitors!(nodes[0], 0);
8979 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8980 // At this point we'll look up if the channel_id is present and immediately fail the channel
8981 // without trying to persist the `ChannelMonitor`.
8982 check_added_monitors!(nodes[1], 0);
8984 // ...still, nodes[1] will reject the duplicate channel.
8986 let events = nodes[1].node.get_and_clear_pending_msg_events();
8987 assert_eq!(events.len(), 1);
8989 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8990 // Technically, at this point, nodes[1] would be justified in thinking both
8991 // channels are closed, but currently we do not, so we just move forward with it.
8992 assert_eq!(msg.channel_id, channel_id);
8993 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8995 _ => panic!("Unexpected event"),
8999 // finally, finish creating the original channel and send a payment over it to make sure
9000 // everything is functional.
9001 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9003 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9004 assert_eq!(added_monitors.len(), 1);
9005 assert_eq!(added_monitors[0].0, funding_output);
9006 added_monitors.clear();
9008 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9010 let events_4 = nodes[0].node.get_and_clear_pending_events();
9011 assert_eq!(events_4.len(), 0);
9012 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9013 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9015 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9016 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9017 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9019 send_payment(&nodes[0], &[&nodes[1]], 8000000);
9023 fn test_error_chans_closed() {
9024 // Test that we properly handle error messages, closing appropriate channels.
9026 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9027 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9028 // we can test various edge cases around it to ensure we don't regress.
9029 let chanmon_cfgs = create_chanmon_cfgs(3);
9030 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9031 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9032 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9034 // Create some initial channels
9035 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9036 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9037 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
9039 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9040 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9041 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9043 // Closing a channel from a different peer has no effect
9044 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9045 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9047 // Closing one channel doesn't impact others
9048 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9049 check_added_monitors!(nodes[0], 1);
9050 check_closed_broadcast!(nodes[0], false);
9051 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
9052 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9053 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9054 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);
9055 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);
9057 // A null channel ID should close all channels
9058 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9059 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9060 check_added_monitors!(nodes[0], 2);
9061 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
9062 let events = nodes[0].node.get_and_clear_pending_msg_events();
9063 assert_eq!(events.len(), 2);
9065 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9066 assert_eq!(msg.contents.flags & 2, 2);
9068 _ => panic!("Unexpected event"),
9071 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9072 assert_eq!(msg.contents.flags & 2, 2);
9074 _ => panic!("Unexpected event"),
9076 // Note that at this point users of a standard PeerHandler will end up calling
9077 // peer_disconnected.
9078 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9079 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9081 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9082 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9083 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9087 fn test_invalid_funding_tx() {
9088 // Test that we properly handle invalid funding transactions sent to us from a peer.
9090 // Previously, all other major lightning implementations had failed to properly sanitize
9091 // funding transactions from their counterparties, leading to a multi-implementation critical
9092 // security vulnerability (though we always sanitized properly, we've previously had
9093 // un-released crashes in the sanitization process).
9095 // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9096 // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9097 // gave up on it. We test this here by generating such a transaction.
9098 let chanmon_cfgs = create_chanmon_cfgs(2);
9099 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9100 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9101 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9103 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9104 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()));
9105 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()));
9107 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9109 // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9110 // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9111 // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9113 let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9114 let wit_program_script: Script = wit_program.into();
9115 for output in tx.output.iter_mut() {
9116 // Make the confirmed funding transaction have a bogus script_pubkey
9117 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9120 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9121 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()));
9122 check_added_monitors!(nodes[1], 1);
9123 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9125 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()));
9126 check_added_monitors!(nodes[0], 1);
9127 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9129 let events_1 = nodes[0].node.get_and_clear_pending_events();
9130 assert_eq!(events_1.len(), 0);
9132 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9133 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9134 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9136 let expected_err = "funding tx had wrong script/value or output index";
9137 confirm_transaction_at(&nodes[1], &tx, 1);
9138 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9139 check_added_monitors!(nodes[1], 1);
9140 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9141 assert_eq!(events_2.len(), 1);
9142 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9143 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9144 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9145 assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9146 } else { panic!(); }
9147 } else { panic!(); }
9148 assert_eq!(nodes[1].node.list_channels().len(), 0);
9150 // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9151 // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9152 // as its not 32 bytes long.
9153 let mut spend_tx = Transaction {
9154 version: 2i32, lock_time: PackedLockTime::ZERO,
9155 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9156 previous_output: BitcoinOutPoint {
9160 script_sig: Script::new(),
9161 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9162 witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9164 output: vec![TxOut {
9166 script_pubkey: Script::new(),
9169 check_spends!(spend_tx, tx);
9170 mine_transaction(&nodes[1], &spend_tx);
9173 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9174 // In the first version of the chain::Confirm interface, after a refactor was made to not
9175 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9176 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9177 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9178 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9179 // spending transaction until height N+1 (or greater). This was due to the way
9180 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9181 // spending transaction at the height the input transaction was confirmed at, not whether we
9182 // should broadcast a spending transaction at the current height.
9183 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9184 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9185 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9186 // until we learned about an additional block.
9188 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9189 // aren't broadcasting transactions too early (ie not broadcasting them at all).
9190 let chanmon_cfgs = create_chanmon_cfgs(3);
9191 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9192 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9193 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9194 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9196 create_announced_chan_between_nodes(&nodes, 0, 1);
9197 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
9198 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9199 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
9200 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9202 nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9203 check_closed_broadcast!(nodes[1], true);
9204 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9205 check_added_monitors!(nodes[1], 1);
9206 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9207 assert_eq!(node_txn.len(), 1);
9209 let conf_height = nodes[1].best_block_info().1;
9210 if !test_height_before_timelock {
9211 connect_blocks(&nodes[1], 24 * 6);
9213 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9214 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9215 if test_height_before_timelock {
9216 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9217 // generate any events or broadcast any transactions
9218 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9219 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9221 // We should broadcast an HTLC transaction spending our funding transaction first
9222 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9223 assert_eq!(spending_txn.len(), 2);
9224 assert_eq!(spending_txn[0].txid(), node_txn[0].txid());
9225 check_spends!(spending_txn[1], node_txn[0]);
9226 // We should also generate a SpendableOutputs event with the to_self output (as its
9228 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9229 assert_eq!(descriptor_spend_txn.len(), 1);
9231 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9232 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9233 // additional block built on top of the current chain.
9234 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9235 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9236 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 }]);
9237 check_added_monitors!(nodes[1], 1);
9239 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9240 assert!(updates.update_add_htlcs.is_empty());
9241 assert!(updates.update_fulfill_htlcs.is_empty());
9242 assert_eq!(updates.update_fail_htlcs.len(), 1);
9243 assert!(updates.update_fail_malformed_htlcs.is_empty());
9244 assert!(updates.update_fee.is_none());
9245 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9246 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9247 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9252 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9253 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9254 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9257 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9258 let chanmon_cfgs = create_chanmon_cfgs(2);
9259 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9260 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9261 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9263 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9265 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9266 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
9267 let route = get_route!(nodes[0], payment_params, 10_000).unwrap();
9269 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9272 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9273 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9274 check_added_monitors!(nodes[0], 1);
9275 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9276 assert_eq!(events.len(), 1);
9277 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9278 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9279 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9281 expect_pending_htlcs_forwardable!(nodes[1]);
9282 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9285 // Note that we use a different PaymentId here to allow us to duplicativly pay
9286 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9287 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9288 check_added_monitors!(nodes[0], 1);
9289 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9290 assert_eq!(events.len(), 1);
9291 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9292 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9293 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9294 // At this point, nodes[1] would notice it has too much value for the payment. It will
9295 // assume the second is a privacy attack (no longer particularly relevant
9296 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9297 // the first HTLC delivered above.
9300 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9301 nodes[1].node.process_pending_htlc_forwards();
9303 if test_for_second_fail_panic {
9304 // Now we go fail back the first HTLC from the user end.
9305 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9307 let expected_destinations = vec![
9308 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9309 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9311 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], expected_destinations);
9312 nodes[1].node.process_pending_htlc_forwards();
9314 check_added_monitors!(nodes[1], 1);
9315 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9316 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9318 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9319 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9320 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9322 let failure_events = nodes[0].node.get_and_clear_pending_events();
9323 assert_eq!(failure_events.len(), 4);
9324 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9325 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9326 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9327 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9329 // Let the second HTLC fail and claim the first
9330 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9331 nodes[1].node.process_pending_htlc_forwards();
9333 check_added_monitors!(nodes[1], 1);
9334 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9335 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9336 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9338 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9340 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9345 fn test_dup_htlc_second_fail_panic() {
9346 // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9347 // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9348 // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9349 // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9350 do_test_dup_htlc_second_rejected(true);
9354 fn test_dup_htlc_second_rejected() {
9355 // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9356 // simply reject the second HTLC but are still able to claim the first HTLC.
9357 do_test_dup_htlc_second_rejected(false);
9361 fn test_inconsistent_mpp_params() {
9362 // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9363 // such HTLC and allow the second to stay.
9364 let chanmon_cfgs = create_chanmon_cfgs(4);
9365 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9366 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9367 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9369 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9370 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9371 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9372 let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9374 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9375 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
9376 let mut route = get_route!(nodes[0], payment_params, 15_000_000).unwrap();
9377 assert_eq!(route.paths.len(), 2);
9378 route.paths.sort_by(|path_a, _| {
9379 // Sort the path so that the path through nodes[1] comes first
9380 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9381 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9384 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9386 let cur_height = nodes[0].best_block_info().1;
9387 let payment_id = PaymentId([42; 32]);
9389 let session_privs = {
9390 // We create a fake route here so that we start with three pending HTLCs, which we'll
9391 // ultimately have, just not right away.
9392 let mut dup_route = route.clone();
9393 dup_route.paths.push(route.paths[1].clone());
9394 nodes[0].node.test_add_new_pending_payment(our_payment_hash,
9395 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &dup_route).unwrap()
9397 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
9398 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9399 &None, session_privs[0]).unwrap();
9400 check_added_monitors!(nodes[0], 1);
9403 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9404 assert_eq!(events.len(), 1);
9405 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9407 assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9409 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9410 RecipientOnionFields::secret_only(our_payment_secret), 14_000_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9411 check_added_monitors!(nodes[0], 1);
9414 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9415 assert_eq!(events.len(), 1);
9416 let payment_event = SendEvent::from_event(events.pop().unwrap());
9418 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9419 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9421 expect_pending_htlcs_forwardable!(nodes[2]);
9422 check_added_monitors!(nodes[2], 1);
9424 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9425 assert_eq!(events.len(), 1);
9426 let payment_event = SendEvent::from_event(events.pop().unwrap());
9428 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9429 check_added_monitors!(nodes[3], 0);
9430 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9432 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9433 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9434 // post-payment_secrets) and fail back the new HTLC.
9436 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9437 nodes[3].node.process_pending_htlc_forwards();
9438 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9439 nodes[3].node.process_pending_htlc_forwards();
9441 check_added_monitors!(nodes[3], 1);
9443 let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9444 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9445 commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9447 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 }]);
9448 check_added_monitors!(nodes[2], 1);
9450 let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9451 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9452 commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9454 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9456 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9457 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9458 &None, session_privs[2]).unwrap();
9459 check_added_monitors!(nodes[0], 1);
9461 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9462 assert_eq!(events.len(), 1);
9463 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9465 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9466 expect_payment_sent(&nodes[0], our_payment_preimage, Some(None), true);
9470 fn test_keysend_payments_to_public_node() {
9471 let chanmon_cfgs = create_chanmon_cfgs(2);
9472 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9473 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9474 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9476 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9477 let network_graph = nodes[0].network_graph.clone();
9478 let payer_pubkey = nodes[0].node.get_our_node_id();
9479 let payee_pubkey = nodes[1].node.get_our_node_id();
9480 let route_params = RouteParameters {
9481 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
9482 final_value_msat: 10000,
9484 let scorer = test_utils::TestScorer::new();
9485 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9486 let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
9488 let test_preimage = PaymentPreimage([42; 32]);
9489 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage),
9490 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0)).unwrap();
9491 check_added_monitors!(nodes[0], 1);
9492 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9493 assert_eq!(events.len(), 1);
9494 let event = events.pop().unwrap();
9495 let path = vec![&nodes[1]];
9496 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9497 claim_payment(&nodes[0], &path, test_preimage);
9501 fn test_keysend_payments_to_private_node() {
9502 let chanmon_cfgs = create_chanmon_cfgs(2);
9503 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9504 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9505 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9507 let payer_pubkey = nodes[0].node.get_our_node_id();
9508 let payee_pubkey = nodes[1].node.get_our_node_id();
9510 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
9511 let route_params = RouteParameters {
9512 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
9513 final_value_msat: 10000,
9515 let network_graph = nodes[0].network_graph.clone();
9516 let first_hops = nodes[0].node.list_usable_channels();
9517 let scorer = test_utils::TestScorer::new();
9518 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9519 let route = find_route(
9520 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9521 nodes[0].logger, &scorer, &(), &random_seed_bytes
9524 let test_preimage = PaymentPreimage([42; 32]);
9525 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage),
9526 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0)).unwrap();
9527 check_added_monitors!(nodes[0], 1);
9528 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9529 assert_eq!(events.len(), 1);
9530 let event = events.pop().unwrap();
9531 let path = vec![&nodes[1]];
9532 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9533 claim_payment(&nodes[0], &path, test_preimage);
9537 fn test_double_partial_claim() {
9538 // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9539 // time out, the sender resends only some of the MPP parts, then the user processes the
9540 // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9542 let chanmon_cfgs = create_chanmon_cfgs(4);
9543 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9544 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9545 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9547 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9548 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9549 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9550 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9552 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9553 assert_eq!(route.paths.len(), 2);
9554 route.paths.sort_by(|path_a, _| {
9555 // Sort the path so that the path through nodes[1] comes first
9556 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9557 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9560 send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9561 // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9562 // amount of time to respond to.
9564 // Connect some blocks to time out the payment
9565 connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9566 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9568 let failed_destinations = vec![
9569 HTLCDestination::FailedPayment { payment_hash },
9570 HTLCDestination::FailedPayment { payment_hash },
9572 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9574 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
9576 // nodes[1] now retries one of the two paths...
9577 nodes[0].node.send_payment_with_route(&route, payment_hash,
9578 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9579 check_added_monitors!(nodes[0], 2);
9581 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9582 assert_eq!(events.len(), 2);
9583 let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
9584 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9586 // At this point nodes[3] has received one half of the payment, and the user goes to handle
9587 // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9588 nodes[3].node.claim_funds(payment_preimage);
9589 check_added_monitors!(nodes[3], 0);
9590 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9593 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9594 #[derive(Clone, Copy, PartialEq)]
9595 enum ExposureEvent {
9596 /// Breach occurs at HTLC forwarding (see `send_htlc`)
9598 /// Breach occurs at HTLC reception (see `update_add_htlc`)
9600 /// Breach occurs at outbound update_fee (see `send_update_fee`)
9601 AtUpdateFeeOutbound,
9604 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
9605 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9608 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9609 // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9610 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9611 // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9612 // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9613 // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9614 // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9615 // might be available again for HTLC processing once the dust bandwidth has cleared up.
9617 let chanmon_cfgs = create_chanmon_cfgs(2);
9618 let mut config = test_default_channel_config();
9619 config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
9620 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9621 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9622 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9624 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9625 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9626 open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9627 open_channel.max_accepted_htlcs = 60;
9629 open_channel.dust_limit_satoshis = 546;
9631 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9632 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9633 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9635 let opt_anchors = false;
9637 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9640 let mut node_0_per_peer_lock;
9641 let mut node_0_peer_state_lock;
9642 let mut chan = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, temporary_channel_id);
9643 chan.holder_dust_limit_satoshis = 546;
9646 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9647 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()));
9648 check_added_monitors!(nodes[1], 1);
9649 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9651 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()));
9652 check_added_monitors!(nodes[0], 1);
9653 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9655 let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9656 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9657 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9659 let dust_buffer_feerate = {
9660 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9661 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9662 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
9663 chan.get_dust_buffer_feerate(None) as u64
9665 let dust_outbound_htlc_on_holder_tx_msat: u64 = (dust_buffer_feerate * htlc_timeout_tx_weight(opt_anchors) / 1000 + open_channel.dust_limit_satoshis - 1) * 1000;
9666 let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9668 let dust_inbound_htlc_on_holder_tx_msat: u64 = (dust_buffer_feerate * htlc_success_tx_weight(opt_anchors) / 1000 + open_channel.dust_limit_satoshis - 1) * 1000;
9669 let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9671 let dust_htlc_on_counterparty_tx: u64 = 25;
9672 let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9675 if dust_outbound_balance {
9676 // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9677 // Outbound dust balance: 4372 sats
9678 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9679 for _ in 0..dust_outbound_htlc_on_holder_tx {
9680 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9681 nodes[0].node.send_payment_with_route(&route, payment_hash,
9682 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9685 // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9686 // Inbound dust balance: 4372 sats
9687 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9688 for _ in 0..dust_inbound_htlc_on_holder_tx {
9689 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9693 if dust_outbound_balance {
9694 // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9695 // Outbound dust balance: 5000 sats
9696 for _ in 0..dust_htlc_on_counterparty_tx {
9697 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9698 nodes[0].node.send_payment_with_route(&route, payment_hash,
9699 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9702 // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9703 // Inbound dust balance: 5000 sats
9704 for _ in 0..dust_htlc_on_counterparty_tx {
9705 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9710 let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
9711 if exposure_breach_event == ExposureEvent::AtHTLCForward {
9712 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if on_holder_tx { dust_outbound_htlc_on_holder_tx_msat } else { dust_htlc_on_counterparty_tx_msat });
9713 let mut config = UserConfig::default();
9714 // With default dust exposure: 5000 sats
9716 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
9717 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
9718 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9719 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9720 ), true, APIError::ChannelUnavailable { ref err },
9721 assert_eq!(err, &format!("Cannot send 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 }, config.channel_config.max_dust_htlc_exposure_msat)));
9723 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9724 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9725 ), true, APIError::ChannelUnavailable { ref err },
9726 assert_eq!(err, &format!("Cannot send value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx", dust_overflow, config.channel_config.max_dust_htlc_exposure_msat)));
9728 } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9729 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 });
9730 nodes[1].node.send_payment_with_route(&route, payment_hash,
9731 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9732 check_added_monitors!(nodes[1], 1);
9733 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9734 assert_eq!(events.len(), 1);
9735 let payment_event = SendEvent::from_event(events.remove(0));
9736 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9737 // With default dust exposure: 5000 sats
9739 // Outbound dust balance: 6399 sats
9740 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9741 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9742 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 }, config.channel_config.max_dust_htlc_exposure_msat), 1);
9744 // Outbound dust balance: 5200 sats
9745 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 counterparty commitment tx", dust_overflow, config.channel_config.max_dust_htlc_exposure_msat), 1);
9747 } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9748 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
9749 nodes[0].node.send_payment_with_route(&route, payment_hash,
9750 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9752 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9753 *feerate_lock = *feerate_lock * 10;
9755 nodes[0].node.timer_tick_occurred();
9756 check_added_monitors!(nodes[0], 1);
9757 nodes[0].logger.assert_log_contains("lightning::ln::channel", "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure", 1);
9760 let _ = nodes[0].node.get_and_clear_pending_msg_events();
9761 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9762 added_monitors.clear();
9766 fn test_max_dust_htlc_exposure() {
9767 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
9768 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
9769 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
9770 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
9771 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
9772 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
9773 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
9774 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
9775 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
9776 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
9777 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
9778 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
9782 fn test_non_final_funding_tx() {
9783 let chanmon_cfgs = create_chanmon_cfgs(2);
9784 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9785 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9786 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9788 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9789 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9790 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9791 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9792 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
9794 let best_height = nodes[0].node.best_block.read().unwrap().height();
9796 let chan_id = *nodes[0].network_chan_count.borrow();
9797 let events = nodes[0].node.get_and_clear_pending_events();
9798 let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
9799 assert_eq!(events.len(), 1);
9800 let mut tx = match events[0] {
9801 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9802 // Timelock the transaction _beyond_ the best client height + 1.
9803 Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 2), input: vec![input], output: vec![TxOut {
9804 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9807 _ => panic!("Unexpected event"),
9809 // Transaction should fail as it's evaluated as non-final for propagation.
9810 match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
9811 Err(APIError::APIMisuseError { err }) => {
9812 assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
9817 // However, transaction should be accepted if it's in a +1 headroom from best block.
9818 tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
9819 assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
9820 get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9824 fn accept_busted_but_better_fee() {
9825 // If a peer sends us a fee update that is too low, but higher than our previous channel
9826 // feerate, we should accept it. In the future we may want to consider closing the channel
9827 // later, but for now we only accept the update.
9828 let mut chanmon_cfgs = create_chanmon_cfgs(2);
9829 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9830 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9831 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9833 create_chan_between_nodes(&nodes[0], &nodes[1]);
9835 // Set nodes[1] to expect 5,000 sat/kW.
9837 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
9838 *feerate_lock = 5000;
9841 // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
9843 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9844 *feerate_lock = 1000;
9846 nodes[0].node.timer_tick_occurred();
9847 check_added_monitors!(nodes[0], 1);
9849 let events = nodes[0].node.get_and_clear_pending_msg_events();
9850 assert_eq!(events.len(), 1);
9852 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9853 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9854 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9856 _ => panic!("Unexpected event"),
9859 // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
9862 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9863 *feerate_lock = 2000;
9865 nodes[0].node.timer_tick_occurred();
9866 check_added_monitors!(nodes[0], 1);
9868 let events = nodes[0].node.get_and_clear_pending_msg_events();
9869 assert_eq!(events.len(), 1);
9871 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9872 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9873 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9875 _ => panic!("Unexpected event"),
9878 // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
9881 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9882 *feerate_lock = 1000;
9884 nodes[0].node.timer_tick_occurred();
9885 check_added_monitors!(nodes[0], 1);
9887 let events = nodes[0].node.get_and_clear_pending_msg_events();
9888 assert_eq!(events.len(), 1);
9890 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
9891 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9892 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
9893 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000 (- 250)".to_owned() });
9894 check_closed_broadcast!(nodes[1], true);
9895 check_added_monitors!(nodes[1], 1);
9897 _ => panic!("Unexpected event"),
9901 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
9902 let mut chanmon_cfgs = create_chanmon_cfgs(2);
9903 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9904 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9905 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9906 let min_final_cltv_expiry_delta = 120;
9907 let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
9908 min_final_cltv_expiry_delta - 2 };
9909 let recv_value = 100_000;
9911 create_chan_between_nodes(&nodes[0], &nodes[1]);
9913 let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), final_cltv_expiry_delta as u32);
9914 let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
9915 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
9916 Some(recv_value), Some(min_final_cltv_expiry_delta));
9917 (payment_hash, payment_preimage, payment_secret)
9919 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
9920 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
9922 let route = get_route!(nodes[0], payment_parameters, recv_value).unwrap();
9923 nodes[0].node.send_payment_with_route(&route, payment_hash,
9924 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9925 check_added_monitors!(nodes[0], 1);
9926 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9927 assert_eq!(events.len(), 1);
9928 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9929 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9930 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9931 expect_pending_htlcs_forwardable!(nodes[1]);
9934 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
9935 None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
9937 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9939 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
9941 check_added_monitors!(nodes[1], 1);
9943 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9944 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
9945 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
9947 expect_payment_failed!(nodes[0], payment_hash, true);
9952 fn test_payment_with_custom_min_cltv_expiry_delta() {
9953 do_payment_with_custom_min_final_cltv_expiry(false, false);
9954 do_payment_with_custom_min_final_cltv_expiry(false, true);
9955 do_payment_with_custom_min_final_cltv_expiry(true, false);
9956 do_payment_with_custom_min_final_cltv_expiry(true, true);